Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert X => Option[R] to PartialFunction[X,R]

As long as we have a PartialFunction[X,R] it's very easy to convert it to a function returning Option[R], e.g.

def pfToOptf[X, R](f: PartialFunction[X,R])(x: X) =
    if (f.isDefinedAt(x)) Some(f(x))
    else None

However, what if the task is opposite: suppose I have a function f getting X as an argument and returning Option[R] as a result. And I want to make a PartialFunction[X,R] out of it. What is the best way?

What I've come up with looks pretty ugly to my taste:

def optfToPf[X,R](f: X => Option[R]) : PartialFunction[X,R] = {
    object extractor {
        def unapply(x: X): Option[R] = f(x)
    }

    { case extractor(r) => r }
}

Is there some better way I missed?

like image 852
Alexander Azarov Avatar asked Dec 15 '09 15:12

Alexander Azarov


3 Answers

How about this:

Welcome to Scala version 2.8.0.r19650-b20091114020153 (Java HotSpot(TM) Client VM, Java 1.6.0_17).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def optfToPf[X,R](f: X => Option[R]): PartialFunction[X,R] = x => f(x) match {
     |     case Some(r) => r
     | }
optfToPf: [X,R](f: (X) => Option[R])PartialFunction[X,R]

scala>
like image 35
Eastsun Avatar answered Nov 04 '22 02:11

Eastsun


Starting Scala 2.9, Function.unlift does precisely this:

def unlift[T, R](f: (T) => Option[R]): PartialFunction[T, R]

Turns a function T => Option[R] into a PartialFunction[T, R].

like image 84
Thayne Avatar answered Nov 04 '22 01:11

Thayne


I suppose you could override apply and isDefinedAt by hand, but I'd do it the way you find ugly.

def optfToPf[X,R](f: X => Option[R]) = new PartialFunction[X,R] {
  def apply(x: X): R = f(x).get
  def isDefinedAt(x: X): Boolean = f(x) != None
}

Testing:

scala> val map = Map(1 -> 2)
map: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2)

scala> map(1)
res0: Int = 2

scala> def mapOpt(key: Int) = map.get(key)
mapOpt: (key: Int)Option[Int]

scala> mapOpt(1)
res1: Option[Int] = Some(2)

scala> mapOpt(2)
res2: Option[Int] = None

scala> val mapPf = optfToPf(mapOpt _)
mapPf: java.lang.Object with PartialFunction[Int,Int] = <function1>

scala> mapPf.isDefinedAt(2)
res3: Boolean = false

scala> mapPf.isDefinedAt(1)
res4: Boolean = true

scala> mapPf(1)
res5: Int = 2

scala> mapPf(2)
java.util.NoSuchElementException: None.get
like image 5
Daniel C. Sobral Avatar answered Nov 04 '22 01:11

Daniel C. Sobral