问题描述
PartialFunction
的 lift
方法将 PartialFunction 转换为返回 Option
结果的 Function
.
PartialFunction
's lift
method turns a PartialFunction into a Function
returning an Option
result.
是否有相反的操作,将 Function1[A, Option[B]]
变成 PartialFunction[A, B]
?
Is there an inverse operation to this, that turns a Function1[A, Option[B]]
into a PartialFunction[A, B]
?
推荐答案
不在库中,但很容易构建.但是,isDefinedAt 必须对函数进行全面评估,这使得它比通过模式匹配构建的部分函数的典型成本更高,并且还可能导致不必要的副作用.
Not in the library, but it's easy to build. However, isDefinedAt will have to fully evaluate the function making it more expensive than is typical for partial functions built from pattern matching and also possibly result in unwanted side effects.
scala> def unlift[A, B](f : (A => Option[B])) = new PartialFunction[A,B] {
| def isDefinedAt(x : A) = f(x).isDefined
| def apply(x : A) = f(x).get
| }
unlift: [A,B](f: (A) => Option[B])java.lang.Object with PartialFunction[A,B]
scala> def f(x : Int) = if (x == 1) Some(1) else None
f: (x: Int)Option[Int]
scala> val g = unlift(f)
g: java.lang.Object with PartialFunction[Int,Int] = <function1>
scala> g.isDefinedAt(1)
res0: Boolean = true
scala> g.isDefinedAt(2)
res1: Boolean = false
scala> g(1)
res2: Int = 1
scala> g(2)
java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:262)
at scala.None$.get(Option.scala:260)
at $anon$1.apply(<console>:7)
at scala.Function1$class.apply$mcII$sp(Function1.scala:39)
at $anon$1.apply$mcII$sp(<console>:5)
at .<init>(<console>:9)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:9)
at RequestResult$.<clinit>(<console>)
at RequestResult$scala_repl_result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$17.apply(Interpreter.scala:988)
at scala.tools....
纯粹主义者也可能用 try/catch 块包装 isDefinedAt 以在异常时返回 false.
A purist might also wrap isDefinedAt with a try/catch block to return false on exceptions.
这篇关于PartialFunction 的提升方法的逆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!