在 Nat 种类上定义自定义类型族
Defining custom type families over the Nat kind
如何定义基于种类 GHC.TypeLits.Nat
的新计算?我希望能够定义一个类型族
type family WIDTH (n :: Nat) :: Nat
这样 WIDTH 0 ~ 0
和 WIDTH (n+1) ~ log2 n
我们可以对任何文字进行模式匹配 Nat
,然后使用内置操作进行递归。
{-# LANGUAGE UndecidableInstances #-}
import GHC.TypeLits
type family Div2 n where
Div2 0 = 0
Div2 1 = 0
Div2 n = Div2 (n - 2) + 1
type family Log2 n where
Log2 0 = 0 -- there has to be a case, else we get nontermination
-- or we could return Maybe Nat
Log2 1 = 0
Log2 n = Log2 (Div2 n) + 1
type family WIDTH n where
WIDTH 0 = 0
WIDTH n = Log2 (n - 1)
如何定义基于种类 GHC.TypeLits.Nat
的新计算?我希望能够定义一个类型族
type family WIDTH (n :: Nat) :: Nat
这样 WIDTH 0 ~ 0
和 WIDTH (n+1) ~ log2 n
我们可以对任何文字进行模式匹配 Nat
,然后使用内置操作进行递归。
{-# LANGUAGE UndecidableInstances #-}
import GHC.TypeLits
type family Div2 n where
Div2 0 = 0
Div2 1 = 0
Div2 n = Div2 (n - 2) + 1
type family Log2 n where
Log2 0 = 0 -- there has to be a case, else we get nontermination
-- or we could return Maybe Nat
Log2 1 = 0
Log2 n = Log2 (Div2 n) + 1
type family WIDTH n where
WIDTH 0 = 0
WIDTH n = Log2 (n - 1)