如果您有约束类型和类型族,则很容易做到。首先,让我说DataKinds
为了清楚起见我更喜欢使用
data HList ls where
HNil :: HList '[]
HCons :: x -> HList xs -> HList (x ': xs)
type family ConstrainAll (c :: * -> Constraint) (ls :: [*]) :: Constraint
type instance ConstrainAll c '[] = ()
type instance ConstrainAll c (x ': xs) = (c x, ConstrainAll c xs)
showAll :: ConstrainAll Show xs => HList xs -> [String]
showAll HNil = []
showAll (HCons x xs) = (show x) : showAll xs
如果你不使用新的扩展,它是可能的,但更丑陋。一种选择是为所有内容定义自定义类
class ShowAll ls where
showAll :: HList ls -> [Show]
instance ShowAll () where
showAll _ = []
instance (ShowAll xs, Show x) => ShowAll (x,xs)
showAll (HCons x xs) = (show x) : (showAll xs)
我觉得很难看。一个更聪明的方法是伪造约束类型
class Constrained tag aType where
isConstained :: tag aType
data HListT tag ls where
HNilT :: HListT tag ()
HConsT :: x -> tag x -> HListT tag xs -> HListT tag (x,xs)
data Proxy (f :: * -> *) = Proxy
class ConstainedAll tag ls where
tagThem :: Proxy tag -> HList ls -> HListT tag ls
instance ConstainedAll tag () where
tagThem _ _ = HNilT
instance (ConstainedAll tag xs, Constrained tag x) => ConstainedAll tag (x,xs) where
tagThem p (HCons x xs) = HConsT x isConstained (tagThem p xs)
然后你可以使用它
data Showable x where Showable :: Show x => Showable x
instance Show x => Constrained Showable x where isConstained = Showable
--inferred type showAll' :: HListT Showable xs -> [String]
showAll' HNilT = []
showAll' (HConsT x Showable xs) = (show x) : showAll' xs
--inferred type: showAll :: ConstainedAll Showable xs => HList xs -> [String]
showAll xs = showAll' (tagThem (Proxy :: Proxy Showable) xs)
example = showAll (HCons "hello" (HCons () HNil))
它应该(尚未测试)与任何具有 GADT、MPTC、灵活上下文/实例和种类签名的 GHC 一起使用(您可以轻松摆脱最后一个)。
编辑:在 GHC 7.6+ 你应该使用
type family ConstrainAll (c :: k -> Constraint) (ls :: [k]) :: Constraint
(k
而不是*
)并打开 PolyKinds,但这不适用于 PolyKinds 的 GHC 7.4 实现(因此是单态代码)。同理,定义
data HList f ls where
HNil :: HList f '[]
HCons :: !(f x) -> !(HList f xs) -> HList f (x ': xs)
当您想要惰性与严格的 HLists 或想要字典列表或更高种类的通用变体等时,可以避免代码重复。