The ListT
monad transformer in Scalaz is actually a little better than your first version (or at least more concise—you only have to worry about one layer):
import scalaz._, Scalaz._
val a = ListT(List(1, 2, 3).some)
val b = for { el <- a } yield el + 1
Or equivalently:
val b = a.map(_ + 1)
Here a
and b
are both instances of ListT[Option, Int]
. You can unwrap these values and get a plain old Option[List[Int]]
using underlying
:
scala> b.underlying
res0: Option[List[Int]] = Some(List(2, 3, 4))
You can do lots of other things with ListT
, like sequence functions from values into options of lists, etc.