Haskell式的家庭

AJF*_*mar 10 haskell type-families idris

在Haskell中,我可能会编写一个带有type声明的类型类来创建一个类型族,如下所示:

class ListLike k where
    type Elem ::  * -> *
    fromList :: [Elem k] -> k
Run Code Online (Sandbox Code Playgroud)

然后写这样的实例:

instance ListLike [a] where
    type Elem [a] = a
    fromList = id

instance ListLike Bytestring where
    type Elem Bytestring = Char
    fromList = pack
Run Code Online (Sandbox Code Playgroud)

我知道您可以在Idris中创建类型类和类型级函数,但这些方法对给定类型的数据进行操作,而不是类型本身.

如何在Idris中创建类型类约束类型系列,如上所述?

Car*_*ten 8

我不知道你是否会找到一个用途,但我认为显而易见的翻译应该是

class ListLike k where
    llElem : Type
    fromList : List llElem -> k

instance ListLike (List a) where
    llElem = a
    fromList = id

instance ListLike (Maybe a) where
  llElem = a
  fromList [] = Nothing
  fromList (a::_) = Just a
Run Code Online (Sandbox Code Playgroud)

用法

??> the (Maybe Int) (fromList [3])
Just 3 : Maybe Int
??> the (List Int) (fromList [3])
[3] : List Int
Run Code Online (Sandbox Code Playgroud)

  • @AJFarmar`llElem`不能单独使用,但可以使用`fromList`确定适当的实例.Idris实际上并没有在这个类的定义中检查这个(但它应该并且很快就会). (2认同)