简体   繁体   中英

Define scalaz monad instance for a shapeless hlist

I've tried to define a Monad (scalaz) for shapeless HList through point and bind implementation. The first problem is that HList trait is not a type constructor, but that can be solved with type lambdas, point is simple, but i couldn't find right implementation for bind , i guess i need some function of type Poly1 with some Aux/Mapper tricks, but that side of shapeless is still dark to me. HList has all functions to be a Monad, like simple List, so is it possible to implement one from Scalaz?

A monoid is a set with some operations that obey particular laws. What elements are you considering as possible HListM[A] ? If you declare HListM[A] = HList , ie any HList , then you'll quickly find that you can't map with f: A => B , except by treating all map s as identity and you've reinvented the rather uninteresting monad Id (with a few extra but inert inhabitants).

We could make a monad with the type HListM[A] = A :: ... :: A :: HNil (though even actually expressing that type in Scala is a challenge - you'd need an auxiliary trait trait CopiesOf[N <: Nat, A] {type Out <: HList }, implicit s to provide instances of this, and then an existential to actually write it ( CopiesOf[N, A]#Out forSome {type N <: Nat} )). Writing monad operations for this is possible, though you'd need to require shapeless auxiliary classes like Prepend at the point of operation, since there's no real way to express a "forall" type in Scala - you can declare instances of your type for _0 and Succ[N] , but there's no way to prove to the compiler that there is an instance for any N <: Nat , you just have to require implicit ones whenever you need to use them.

But after a lot of work you'd end up with something isomorphic to List[A] ; why not just use List[A] for that case?

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