scala - 结合2个偏函数

标签 scala function

我有两个部分函数返回单元( f1f2 )。例如,这样的事情:

val f1 = {
   case s: arg => //do some
   //etc... lots of cases
}

val f2 = {
   case s: anotherArg => //do some
   //lots of cases
}

有没有一种简洁的方法来将它组合成部分函数,​​就像那样
f(x) = {f1(x); f2(x)} iff f1.isDefinedAt(x) && f2.isDefinedAt(x)
f(x) = f1(x); iff f1.isDefinedAt(x) && !f2.isDefinedAt(x) 
f(x) = f2(x); iff !f1.isDefinedAt(x) && f2.isDefinedAt(x) 

最佳答案

要不然

f1 orElse f2

Scala REPL
scala> val f: PartialFunction[Int, Int] = { case 1 => 1 }
f: PartialFunction[Int,Int] = <function1>

scala> val g: PartialFunction[Int, Int] = { case 2 => 2 }
g: PartialFunction[Int,Int] = <function1>

scala> val h = f orElse g
h: PartialFunction[Int,Int] = <function1>

scala> h(1)
res3: Int = 1

scala> h(2)
res4: Int = 2

scala> h.isDefinedAt(1)
res6: Boolean = true

scala> h.isDefinedAt(2)
res7: Boolean = true

这两个函数都在常见情况下执行

使用部分函数列表和 foldLeft

Scala REPL
scala> val f: PartialFunction[Int, Int] = { case 1 => 1 case 3 => 3}
f: PartialFunction[Int,Int] = <function1>

scala> val g: PartialFunction[Int, Int] = { case 2 => 2  case 3 => 3}
g: PartialFunction[Int,Int] = <function1>

scala> val h = f orElse g
h: PartialFunction[Int,Int] = <function1>

scala> h(3)
res10: Int = 3

scala> h(3)
res11: Int = 3

scala> val h = List(f, g)
h: List[PartialFunction[Int,Int]] = List(<function1>, <function1>)

scala> def i(arg: Int) = h.foldLeft(0){(result, f) => if (f.isDefinedAt(arg)) result + f(arg) else result }
i: (arg: Int)Int

scala> i(3)
res12: Int = 6

关于scala - 结合2个偏函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44545869/

相关文章:

Scala sys.process 非零退出值

scala - 为什么在未指定参数名称时 foreach 只执行一次?

Scala 的 Stream 和 StackOverflowError

scala - 如何在scala中保存RandomForestClassifier Spark模型?

c++ - 指向未指定大小 "(*p)[]"的数组的指针在 C++ 中非法但在 C 中合法

javascript - 为对象属性分配新值

java - java返回类型可以像Scala那样写 this.type

function - Scala:尾递归幂函数

c - 请解释一下C程序的这个功能是如何工作的?

javascript - forEach 函数调用的调用上下文 (this)