简体   繁体   中英

Composing a sequence of functions that return future

I am looking for an elegant way of composing a sequence of functions that return Future . Ie, for a sequence of (f1, f2, ..., f_n) , each function being of type T=>Future[T] , I want to produce a new function, g , where g(x) = f_n(...f2(f1(x))...) .

My implementation is as follows:

  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)
    }
  }

This works, as far as I can tell. The solution seems a little convoluted though, with a number of nested lambdas. Can it be simplified?

The problem comes from Horstmann's book, Scala for the impatient , which asks to

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))

and then to:

Repeat the preceding exercise for any sequence of functions of type T => Future[T] .

How about this?

def doInOrder[T] (fs : (T => Future[T])*)(implicit ec:ExecutionContext): T=>Future[T] = {
    t => fs.foldLeft(Future.successful(t))((acc, f) => acc.flatMap(f))
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM