简体   繁体   English

Haskell式的家庭

[英]Haskell-style type families

In Haskell, I might write a typeclass with a type declaration to create a type family, like so: 在Haskell中,我可能会编写一个带type声明的类型类来创建一个类型族,如下所示:

class ListLike k where
    type Elem ::  * -> *
    fromList :: [Elem k] -> k

And then write instances like this: 然后写这样的实例:

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

instance ListLike Bytestring where
    type Elem Bytestring = Char
    fromList = pack

I'm aware that you can create typeclasses and type-level functions in Idris, but the methods operate on data of the given type, not the type itself. 我知道您可以在Idris中创建类型类和类型级函数,但这些方法对给定类型的数据进行操作,而不是类型本身。

How can I make a typeclass-constrained type family in Idris like the one above? 如何在Idris中创建类型类约束类型系列,如上所述?

I have no clue if you will ever find a use for this, but I think the obvious translation should be 我不知道你是否会找到它的用途,但我认为显而易见的翻译应该是

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

usage 用法

λΠ> the (Maybe Int) (fromList [3])
Just 3 : Maybe Int
λΠ> the (List Int) (fromList [3])
[3] : List Int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM