假设我们有异构列表
data Nil
data Cons a b
我可以为任何类型类A
class AList a
instance AList Nil
instance (A x, AList xs) => AList (Cons x xs)
现在,有没有办法概括该代码,使其在A
中具有参数?
说,像这样编写语法
class List (class A) a
instance List (class A) Nil
instance (A x, List (class A) xs) => List (class A) (Cons x xs)
答案 0 :(得分:3)
我不确定我理解动机,但是,你可以用GHC的ConstraintKinds
扩展来表达这一点:
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeclasses #-}
{-# LANGUAGE UndecidableInstances #-}
import GHC.Exts (Constraint)
class List (c :: * -> Constraint) a
data Nil
data Cons a b
instance List c Nil
instance (c x, List c xs) => List c (Cons x xs)