gpt4 book ai didi

scala - 结合2个偏函数

转载 作者:行者123 更新时间:2023-12-02 07:21:32 26 4
gpt4 key购买 nike

我有两个部分函数返回单元( 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com