HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Writing Traverse Instance for Option

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
writingtraverseinstanceoptionfor

Problem

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?

Solution


  • Never use get method on option. In this case you could use case Some(a) instead.



  • 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.

Code Snippets

oa match {
  case None => G.unit(None)
  case Some(a) =>
    val x: G[B] = f(a)
    G.map(x)(Some(_))
}
case Some(a) => G.map(f(a))(Some(_))

Context

StackExchange Code Review Q#40127, answer score: 2

Revisions (0)

No revisions yet.