# Forward piping in F#

January 29, 2017 3 Comments

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.

Thank you for writting this article. Without it, I would have had to write these ugly lines forever:

let f x y = x // This silly function returns the first parameter.

// I used to write like this

printf “\n >> Result: %d” (5 |> f > Result: %d” ( 6 |> ( 5 |> f ) )

// Less hillarious but still so … corny.

// After readling your article, now I can write an elegant

// line like this:

printf “\n >> Result: %d” ( (5 , 6) ||> a )

// This does look way better. Thank you so much !

Still me. I just want to edit my comment above:

”

Thank you for writting this article. Without it, I would have had to write these ugly lines forever:

let f x y = x // This silly function returns the first parameter.

// I used to write like this

printf “\n >> Result: %d” ( 5 |> f > Result: %d” (5 |> f > Result: %d” ( 6 |> ( 5 |> f ) )

// Less hillarious but still so … corny.

// After readling your article, now I can write an elegant

// line like this:

printf “\n >> Result: %d” ( (5 , 6) ||> a )

// This does look way better. Thank you so much !

“

Urrgg !! Something CHANGED content of my comments. Those two comments are not exactly what I wrote before pressing “Post Comment” button.