Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more idiomatic way of getting IO[Option[A]] from Option[IO[Option[A]] then using sequence and mapping join?

Tags:

scala

scalaz

I'm running into quite a few places where I have something akin to

def f(s: String): Option[Long] = ...
def g(l: Long): IO[Option[Wibble]] = ...

val a: IO[Option[Wibble]] = f(param).flatMap(g).sequence.map(_.join)

Seeing the .sequence.map(_.join) repeated over and over is starting to bother me. Is there a more idiomatic way of accomplishing the same thing?

like image 464
rwallace Avatar asked Jan 11 '12 23:01

rwallace


2 Answers

This sounds like the use case for monad transformers, see here for an explanation in Haskell and here for a discussion in Scala.

like image 75
Ozymandias Avatar answered Oct 10 '22 23:10

Ozymandias


The idiomatic method for dealing with Option chains is to use for-comprehensions and a getOrElse call.

val a = for {
    val temp <- f(param)
    val result <- Some(g(temp))
} yield result getOrElse <Default Here>

There's no getting around either having a default or raising an exception if you are going to categorically unpack the Option since f can return None and g can't accept that.

like image 20
David Skoog Avatar answered Oct 10 '22 21:10

David Skoog