Question

It seems to me that Scalaz' NonEmptyList has a monad instance, so a monad transformer for it (a bit similar to ListT) should be possible. Is that correct?

If so, is there one out there? (I couldn't find one in Scalaz 7 itself.)

If not, i.e. a monad transformer for it would be impossible or not make any sense, I would be grateful for any additional explanation as to why not.

Was it helpful?

Solution

It's certainly possible, as it can be shown that any monad which has a Traverse instance can be made into a monad transformer:

import scalaz._
import Scalaz._

object MonadT {
  implicit def monadTransformerFromTraverse[M[_]: Monad, N[_]: Monad: Traverse]: Monad[({type MN[A]=M[N[A]]})#MN] = new Monad[({type MN[A]=M[N[A]]})#MN] {
    def point[A](a: => A): M[N[A]] = a.point[N].point[M]
    def bind[A,B](fa: M[N[A]])(f: A=>M[N[B]]) : M[N[B]] = {
      val M = implicitly[Monad[M]]
      val NT = implicitly[Traverse[N]]
      val N = implicitly[Monad[N]]

      M.map(M.join(M.map(M.map(fa)(N.map(_)(f)))(NT.sequence(_))))(N.join)
//                       |- => M[N[M[N[B]]]]  -|
//                 |-       => M[M[N[N[B]]]]                   -|
//         |-               => M[N[N[B]]]                       -|
//    |-                    => M[N[B]]                                  -|


    }
  }

  def main(argv: Array[String]) {
    val x: Option[NonEmptyList[Int]] = Some(NonEmptyList(1))
    val f: Int => Option[NonEmptyList[Int]] = { x: Int => Some(NonEmptyList(x+1)) }

    val MT =  monadTransformerFromTraverse[Option, NonEmptyList]
    println(MT.bind(x)(f)) // Some(NonEmptyList(2))
  }
}

This is clearly not the most convenient form to work with, but shows that it is, indeed, possible. Tom Switzer is currently working on adding a much more useful and generic TraverseT monad transformer to scalaz. You can see his progress on GitHub

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top