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?
-
2This isn't possible in the straightforward sense, but it's an interesting question. See for example [my answer here](http://stackoverflow.com/a/14456938/334519) (involving applicative functors instead of monads), [this related example](https://github.com/milessabin/shapeless/blob/master/examples/src/main/scala/shapeless/examples/cartesianproduct.scala) in Shapeless, and my (unanswered) question [here](https://twitter.com/travisbrown/status/294064540235210752). – Travis Brown Sep 22 '13 at 00:06
-
ScalaZ is still uncharted territory for me, but this might contain the methods and interoperability you need: [Shapeless Contrib](https://github.com/typelevel/shapeless-contrib) – EECOLOR Feb 22 '14 at 21:57
-
1mandubian (http://stackoverflow.com/users/601296/mandubian) wrote a blog post about a monoid for HList: http://mandubian.com/2014/07/29/hmonoid/ , that can be of interest to you. – Alex Archambault Aug 02 '14 at 11:49
1 Answers
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
, i.e. 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?

- 17,386
- 3
- 26
- 37