同时测试定义性和评估
那就是applyOrElse
。collect
它被用来lift
避免双重评估。
这个递归版本说,应用下一个函数并使用它来构建结果,或者只是继续并构建其余的结果。
def f(ff: List[PartialFunction[Any, Int]]): List[Int] = ff match {
case hd :: tail => hd.applyOrElse(num, (_: Any) => return f(tail)) :: f(tail)
case _ => Nil
}
这是我第一次return
在 Scala 中使用。我不得不在索引中查找它。
这种手动构造避免Lifted
了Option
在Option
.
scala> :pa
// Entering paste mode (ctrl-D to finish)
val funcs: Seq[PartialFunction[Any, Int]] = Vector(
{ case i: Int if i % 2 == 0 => i*2 }
,
{ case i: Int if i % 2 == 1 => i*3 }
,
{ case i: Int if i % 6 == 0 => i*5 }
)
val num = 66
def f(ff: List[PartialFunction[Any, Int]]): List[Int] = ff match {
case hd :: tail => hd.applyOrElse(num, (_: Any) => return f(tail)) :: f(tail)
case _ => Nil
}
// Exiting paste mode, now interpreting.
funcs: Seq[PartialFunction[Any,Int]] = Vector(<function1>, <function1>, <function1>)
num: Int = 66
f: (ff: List[PartialFunction[Any,Int]])List[Int]
scala> f(funcs.toList)
res0: List[Int] = List(132, 330)
scala> funcs flatMap (_ lift num)
res1: Seq[Int] = Vector(132, 330)
第二个版本只是为相同的想法使用了一个标志。
scala> :pa
// Entering paste mode (ctrl-D to finish)
def f(ff: List[PartialFunction[Any, Int]]): List[Int] = ff match {
case hd :: tail =>
var ok = true
val x = hd.applyOrElse(num, (_: Any) => { ok = false ; 0 })
if (ok) x :: f(tail) else f(tail)
case _ => Nil
}
// Exiting paste mode, now interpreting.
f: (ff: List[PartialFunction[Any,Int]])List[Int]
scala> f(funcs.toList)
res2: List[Int] = List(132, 330)