私は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 ++ "]"
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加