3
\$\begingroup\$

Working on an exercise from Functional Programming in Scala, I implemented a Traverse instance for Option:

override def traverse[G[_],A,B](oa: Option[A])(f: A => G[B])(implicit G: Applicative[G]):
    G[Option[B]] =
  oa match {
    case None => G.unit(None)
    case _ => {
              val a: A = oa.get
              val x: G[B] = f(a)
              G.map(x)(Some(_))
            }
  }

Is this idiomatic? Besides condensing the case _'s 3 lines to 1, perhaps there's a more concise way to write this method?

\$\endgroup\$
2
  • \$\begingroup\$ Can't you just use G.unit(oa map f)? \$\endgroup\$
    – senia
    Commented Jan 28, 2014 at 22:16
  • \$\begingroup\$ oa map f produces a type of Option[G[B]]. Applying G.unit would give G[Option[G[B]]. \$\endgroup\$ Commented Jan 28, 2014 at 22:20

1 Answer 1

2
\$\begingroup\$
  1. Never use get method on option. In this case you could use case Some(a) instead.
  2. You don't need curly braces in case branches
oa match {
  case None => G.unit(None)
  case Some(a) =>
    val x: G[B] = f(a)
    G.map(x)(Some(_))
}

I don't know if variable x makes any sense in this case. I'd just use this:

case Some(a) => G.map(f(a))(Some(_))

You could also use methods of Option like fold of map + getOrElse, but I guess pattern matching is the best solution in this case.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.