Frage

Solange wir eine PartialFunction[X,R] haben, es ist sehr einfach, es zu einer Funktion Rückkehr Option[R] zu konvertieren, z.

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

Was aber, wenn die Aufgabe Gegenteil: Ich nehme an, eine Funktion f habe immer X als Argument und Rückkehr Option[R] als Ergebnis. Und ich möchte eine PartialFunction[X,R] machen aus ihm heraus. Was ist der beste Weg?

Was ich mit Blicken ziemlich hässlich nach meinem Geschmack kommen:

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 }
}

Gibt es einen besseren Weg, ich verpasst?

War es hilfreich?

Lösung

Starten Scala 2.9, Function.unlift tut genau dies:

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

Schaltet eine Funktion T => Option [R] in eine Partielle Funktion [T, R].

Andere Tipps

Wie wäre es damit:

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>

Ich nehme an, Sie von Hand anwenden und isDefinedAt außer Kraft setzen könnte, aber ich würde es die Art und Weise tun Sie hässlich finden.

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
}

Test:

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top