gpt4 book ai didi

scala - 函数组合,累积中间结果

转载 作者:行者123 更新时间:2023-12-01 08:26:51 25 4
gpt4 key购买 nike

假设我有几个函数 Int => Option[Int]:

val f1: Int => Option[Int] = x => if (x < 10) Some(x + 1) else None
val f2: Int => Option[Int] = x => if (x < 10) Some(x + 2) else None
val f3: Int => Option[Int] = x => if (x < 10) Some(x + 3) else None

现在我想组合它们创建一个新函数,该函数累积中间结果,即f1f2的结果, 和 f3

所以我添加了一个新类Accumulator:

class Accumulator(x: Int) {
val ox1 = f1(x)
val ox2 = ox1.flatMap(f2)
val ox3 = ox2.flatMap(f3)
def apply() = ox3
}

val f = {x => new Accumulator(x)}

现在我可以看到计算的所有中间结果:

scala> f(0)
res18: X = $$$a5cddfc4633c5dd8aa603ddc4f9aad5$$$$w$X@10596df6

scala> res18.ox1
res19: Option[Int] = Some(1)

scala> res18.ox2
res20: Option[Int] = Some(3)

scala> res18()
res21: Option[Int] = Some(6)

我不喜欢这种方法,因为每次计算都需要一个新类。您能否建议另一种方法来编写由 f1f2f3 组成的函数 f,该函数还返回中间结果,即f1f2f3调用的结果。

最佳答案

您可以使用 .scanLeftListFunction ,其中(来自文档):

Produces a collection containing cumulative results of applying the operator going left to right.

scala> val f1: Int => Option[Int] = x => if (x < 10) Some(x + 1) else None
f1: Int => Option[Int] = <function1>

scala> val f2: Int => Option[Int] = x => if (x < 10) Some(x + 2) else None
f2: Int => Option[Int] = <function1>

scala> val f3: Int => Option[Int] = x => if (x < 10) Some(x + 3) else None
f3: Int => Option[Int] = <function1>

scala> val fList = List(f1,f2,f3)
fList: List[Int => Option[Int]] = List(<function1>, <function1>, <function1>)

scala> val composed = fList.scanLeft((x:Int) => Option(x)) {
case (composedFun, f) => (x:Int) => (composedFun(x)) flatMap f
}.tail
composedFunctions: List[Int => Option[Int]] = List(<function1>, <function1>, <function1>)

scala> composed.map(_(2))
res24: List[Option[Int]] = List(Some(3), Some(5), Some(8))

scala> composed.map(_(8))
res25: List[Option[Int]] = List(Some(9), Some(11), None)

请注意,我必须引入一个初始值(z,此处为 (x:Int) => Option(x))。
您可能想编写一个函数,它接受函数列表并使用 funList.head作为初始值(并在 .scanLeft 上调用 funList.tail 而不是 funList )。

关于scala - 函数组合,累积中间结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32313901/

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