Composing functions

Lambda expressions that are represented via the Function interface can be composed via the Function.andThen() and Function.compose() methods.

andThen​(Function<? super R,​? extends V> after) returns a composed Function that does the following:

  • Applies this function to its input
  • Applies the after function to the result

Let's take a look at an example of this:

Function<Double, Double> f = x -> x * 2;
Function<Double, Double> g = x -> Math.pow(x, 2);
Function<Double, Double> gf = f.andThen(g);
double resultgf = gf.apply(4d); // 64.0

In this example, the f function is applied to its input (4). The result of applying f is 8 (f(4) = 4 * 2). This result is the input of the second function, g. The result of applying g is 64 (g(8) = Math.pow(8, 2)). The following diagram depicts the flow for four inputs – 1, 2, 3, and 4:

So, this is like g(f(x)). The opposite, f(g(x)), can be shaped using Function.compose(). The returned composed function applies the before function to its input, and then applies this function to the result:

double resultfg = fg.apply(4d); // 32.0

In this example, the g function is applied to its input (4). The result of applying g is 16 (g(4) = Math.pow(4, 2)). This result is the input of the second function, f. The result of applying f is 32 (f(16) = 16 * 2). The following diagram depicts the flow for four inputs – 1, 2, 3, and 4:

Based on the same principles, we can develop an application for editing an article by composing the addIntroduction(), addBody(), and addConclusion() methods. Please take a look at the code that's bundled with this book to see an implementation of this.

We can write other pipelines as well by simply juggling this with the composition process.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.165.115