# Forward piping in F#

January 29, 2017 Leave a comment

In F# it’s possible to chain function calls and feed the return value of each function to the next using the forward type operator which looks like this: |> . We can literally read it as “pipe forward”.

If we have a function that increments an integer like this…:

let incrementByOne x = x + 1

Then we normally call it as follows:

let res = incrementByOne 10

With forward piping we can supply the input parameter first as follows:

let resAlt = 10 |> incrementByOne

A useful application of forward piping is that we can chain functions. We have the following simple functions:

let incrementByOne x = x + 1 let triple x = x * 3 let halve x = x / 2 let double x = x * 2

We can chain them and supply the return value of each function to the next stage as follows:

let res = 10 |> incrementByOne |> triple |> halve |> double

So 10 is fed to incrementByOne, whose return value will be 11. 11 is then supplied to triple and so on. The end result will be 32.

Note that the single pipe forward operator works on functions that have one input parameter only.

If a function requires 2 or more input parameters then we need to increase the number of pipes as follows:

let addThreeNumbers x y z = x + y + z let addTwoNumbers x y = x + y let two = (15, 28) ||> addTwoNumbers let three = (10, 20, 30) |||> addThreeNumbers

View all F# related articles here.