【发布时间】:2025-12-06 01:15:02
【问题描述】:
我正在尝试创建一个转换链来定义给定函数的可能转换:
type Transformation[T] = T => Future[T]
def transformationChain[T](chain: Seq[Transformation[T]]): Transformation[T] = {
}
val t1: Transformation[Int] = t => Future.successful(t + t)
val t2: Transformation[Int] = _ => Future.failed(new NoSuchElementException)
val t3: Transformation[Int] = t =>
if (t > 2) Future.successful(t * t)
else Future.failed(new NoSuchElementException)
val tc = transformationChain(Seq(t1, t2, t2, t3))
val tc2 = transformationChain(Seq(t2, t2, t2))
val tc3 = transformationChain(Seq(t2, t3, t1))
println(Await.result(tc(2), 5.seconds)) // 16
println(Await.result(tc2(2), 5.seconds)) // throw NoSuchElementException
println(Await.result(tc3(2), 5.seconds)) // 4
问题是我不明白如何在“transformationChain”方法中解开这些函数,以通过循环或递归调用它们将结果发送到链中的每个下一个函数。
【问题讨论】:
-
在给定
t2的定义的情况下,为什么他们不应该都返回Future.failed(NoSuchElementException)? -
如果所有函数都返回 NoSuchElementException 而没有任何数值结果,则 transformationChain 的结果应该返回 Transformation[Int] = _ => Future.failed(new NoSuchElementException) 在其他情况下它应该返回一些没有数值的结果例外。
-
所以在其他情况下,它应该“忽略”所有抛出
NoSuchElementException的转换并继续将“上一个结果”传递给下一个? -
完全一样
-
不只是
reduce和flatMap应该完成这项工作吗?
标签: scala functional-programming concurrent.futures