Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything like Haskell's 'maybe' function built into Scala?

What I'm looking for is this function:

def maybe[A, B](a: Option[A])(f: A => B)(g: () => B): B = a match 
{
    case Some(x) => f(x)
    case None => g()
}

It's in the Haskell prelude so I'm thinking it might be in the Scala standard library somewhere and I've just missed it. I hate having to recode it in projects so I'm wondering if anyone knows where it is, or if it's definitively not there. Or is there a better method for getting this functionality?

like image 319
Will Avatar asked Aug 07 '09 10:08

Will


1 Answers

Other answers have given the map + getOrElse composition. Just for the record, you can "add" a maybe function to Option in the following way:

implicit def optionWithMaybe[A](opt: Option[A]) = new {
  def maybe[B](f: A=>B)(g: =>B) = opt map f getOrElse g
}

It's worth noting that the syntax of higher-order functions in Scala is usually nicer when the function parameter comes last. Thus, a better way to organize maybe would be as follows:

def maybe[B](g: =>B)(f: A=>B) = opt map f getOrElse g

This could be used as follows:

val opt: Option[String] = ...
opt.maybe("") { _.toUpperCase }
like image 117
Daniel Spiewak Avatar answered Oct 23 '22 14:10

Daniel Spiewak