我正在研究Haskell通过阅读Thinking with types
可以为依存类型提供什么。
这是一个定义为GADT的异构列表。
data HList (ts :: [Type]) where
HNil :: HList '[]
(:#) :: t -> HList ts -> HList (t ': ts)
infixr 5 :#
instance Eq (HList '[]) where
HNil == HNil = True
instance (Eq t, Eq (HList ts)) => Eq (HList (t ': ts)) where
(a :# as) == (b :# bs) = a == b && as == bs
instance Ord (HList '[]) where
compare HNil HNil = EQ
instance (Ord t, Ord (HList ts)) => Ord (HList (t ': ts)) where
compare (a :# as) (b :# bs) = case compare a b of
EQ -> compare as bs
x -> x
instance Show (HList '[]) where
show HNil = "[]"
instance (Show t, Show (HList ts)) => Show (HList (t ': ts)) where
show xs = "[" ++ (show' xs "") ++ "]"
where
show' (y :# ys) prefix = prefix ++ (show y) ++ rest
where rest = case of
HNil -> ""
_ -> show' ys ", "
这是我得到的错误。
• Occurs check: cannot construct the infinite type: ts2 ~ t1 : ts2
Expected type: HList ts2 -> [Char] -> [Char]
Actual type: HList ts1 -> p -> p1
• In the expression: show' ys ", "
In a case alternative: _ -> show' ys ", "
In the expression:
case ys of
HNil -> ""
_ -> show' ys ", "
• Relevant bindings include
ys :: HList ts2 (bound at src/Lib.hs:43:25)
y :: t1 (bound at src/Lib.hs:43:20)
|
46 | _ -> show' ys ", "
我阅读了HList源代码,它们的作用是我认为的丑陋之处,他们在show ys
返回的字符串上进行模式匹配,如果等于[]
,则基本上停止递归,我认为是骇客。
如果您定义自己的自定义类,然后对该类进行递归,则会更容易。这是因为我们无法将prefix
参数传递给标准show
方法,但是在自定义类中这不再是问题。
class HShow ts where
hshow :: HList ts -> String -> String
instance HShow '[] where
hshow HNil _ = ""
instance (Show t, HShow ts) => HShow (t ': ts) where
hshow (y :# ys) p = p ++ show y ++ hshow ys ", "
之后,我们可以添加方括号并获得标准的Show
类实例:
instance HShow ts => Show (HList ts) where
show xs = "[" ++ hshow xs "" ++ "]"
test :: HList '[ Int, Char, Bool ]
test = 42 :# 'a' :# True :# HNil
-- > test
-- [42, 'a', True]
基于类型族的替代方案。并不是特别简单。
type family All (c :: a -> Constraint) (xs :: [a]) :: Constraint where
All c '[] = ()
All c (x ': xs) = (c x, All c xs)
hshow :: All Show ts => HList ts -> String
hshow HNil = ""
hshow (x :# HNil) = show x
hshow (x :# xs ) = show x ++ ", " ++ hshow xs
instance All Show ts => Show (HList ts) where
show xs = "[" ++ hshow xs ++ "]"