简体   繁体   中英

Haskell-style type families

In Haskell, I might write a typeclass with a type declaration to create a type family, like so:

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.

How can I make a typeclass-constrained type family in Idris like the one above?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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