24

只要我们有 a PartialFunction[X,R],就很容易将其转换为返回的函数Option[R],例如

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

但是,如果任务相反怎么办:假设我有一个函数作为参数f获取并作为结果返回。我想从中受益。什么是最好的方法?XOption[R]PartialFunction[X,R]

我想出的东西对我的口味来说看起来很丑:

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

我错过了一些更好的方法吗?

4

3 回答 3

35

开始Scala 2.9Function.unlift正是这样做的:

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

将函数 T => Option[R] 转换为 PartialFunction[T, R]。

于 2013-12-20T07:04:01.363 回答
12

这个怎么样:

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>
于 2009-12-15T16:01:45.127 回答
5

我想你可以手动覆盖 apply 和 isDefinedAt,但我会按照你觉得丑陋的方式来做。

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
}

测试:

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
于 2009-12-15T16:53:04.303 回答