Combining Future Return Functions

Suppose I have two functions that return futures:

std::future<T> foo(int); std::future<U> bar(T const &); 

I want to combine two functions with a function that takes an int as parameter and returns std::future<U> . How to write this function? Is it possible to generalize the composition of functions for functions that return futures?

 std::future<U> foobar1(int x) { auto foo_x = foo(x); return bar(foo_x.get()); } 

This function will be blocked until the future returned by foo is complete, right? This is clearly not what I want.

 std::future<U> foobar2(int x) { return std::async([=]() { auto foo_x = foo(x); return bar(foo_x.get()).get(); }); } 

It seems silly to me to call get() in the future returned by bar to turn it into a new future std::async

 std::future<U> foobar3(int x) { return foo(x).then([](std::future<T> f) { return bar(f.get()).get(); }; } 

Here again, I have to call get() in the future returned by bar , otherwise I will have future<future<U>> . Is this the right approach?

+6
source share
1 answer

What you want is a monad. std::future is almost, but not quite a monad, but it does not have the ability to correctly compose functions, raising them, as you noticed. See this blog post for more on this.

The summary is that for C ++ 17 an additional method was proposed for std::future : either next or then , which will use a function that will be applied to the future value when it is available. This is roughly equivalent to bind in Haskell, for example (note: not std::bind ).

Let's take two functions:

 T foo(int); U bar(T const &); 

Here we have the mapping int -> T -> U , you need to raise this mapping to int -> std::future<T> -> std::future<U> . It might look like this:

 int x = 2; std::async([=](){return foo(x);}).then(bar); 

Where then is a function that automatically maps T -> U to std::future<T> -> std::future<U> .

Disclaimer: I am not a Haskell programmer and understand that I have probably messed up everything. I welcome the corrections.

+6
source

Source: https://habr.com/ru/post/981669/


All Articles