组成 return 未来的一系列功能
Composing a sequence of functions that return future
我正在寻找一种优雅的方式来组合 return Future
的函数序列。即,对于 (f1, f2, ..., f_n)
的序列,每个函数都是 T=>Future[T]
类型,我想生成一个新函数 g
,其中 g(x) = f_n(...f2(f1(x))...)
。
我的实现如下:
def doInOrder[T] (fs : (T => Future[T])*)(implicit ec:ExecutionContext): T=>Future[T] = {
(t:T) => {
fs.reduceLeft((future1: T=>Future[T], future2: T=>Future[T]) =>
(arg:T) => future1(arg).flatMap((arg2:T) => future2(arg2))
)(t)
}
}
据我所知,这是可行的。解决方案似乎有点复杂,但有许多嵌套的 lambda。 可以简化吗?
问题来自 Horstmann 的书 Scala for the impatient,它要求
Write a function doInOrder
that, given two functions f: T =>
Future[U]
and g: U
=> Future[V]
, produces a function T => Future[U]
that, for a given t, eventually yields g(f(t))
然后到:
Repeat the preceding exercise for any sequence of functions of type T
=> Future[T]
.
这个怎么样?
def doInOrder[T] (fs : (T => Future[T])*)(implicit ec:ExecutionContext): T=>Future[T] = {
t => fs.foldLeft(Future.successful(t))((acc, f) => acc.flatMap(f))
}
我正在寻找一种优雅的方式来组合 return Future
的函数序列。即,对于 (f1, f2, ..., f_n)
的序列,每个函数都是 T=>Future[T]
类型,我想生成一个新函数 g
,其中 g(x) = f_n(...f2(f1(x))...)
。
我的实现如下:
def doInOrder[T] (fs : (T => Future[T])*)(implicit ec:ExecutionContext): T=>Future[T] = {
(t:T) => {
fs.reduceLeft((future1: T=>Future[T], future2: T=>Future[T]) =>
(arg:T) => future1(arg).flatMap((arg2:T) => future2(arg2))
)(t)
}
}
据我所知,这是可行的。解决方案似乎有点复杂,但有许多嵌套的 lambda。 可以简化吗?
问题来自 Horstmann 的书 Scala for the impatient,它要求
Write a function
doInOrder
that, given two functionsf: T => Future[U]
andg: U => Future[V]
, produces a functionT => Future[U]
that, for a given t, eventually yieldsg(f(t))
然后到:
Repeat the preceding exercise for any sequence of functions of type
T => Future[T]
.
这个怎么样?
def doInOrder[T] (fs : (T => Future[T])*)(implicit ec:ExecutionContext): T=>Future[T] = {
t => fs.foldLeft(Future.successful(t))((acc, f) => acc.flatMap(f))
}