Learning F# — Part 9 — |>

Vijesh Salian
2 min readJan 11, 2019

|> is called the pipe forward operator. Generally speaking, pipe connects 2 ends and have something of value flow through in a particular direction. With many pipes you can have a series of connections.

In F#, pipes allow the flow of values through functions. Pipes connect the values to the next function and the resulting value to another function and so on until it passes through all pipes and results in a new value.

Consider these functions below. Pretty trivial here; I have 4 functions to add, double, square and multiply. If you want to know about function check out my previous post about functions.

let add num1 num2 = num1 + num2let double num = num*2let square num = num * numlet multiply num1 num2 = num1 * num2

Lets say you have certain operations to be performed in a sequence. For example,

you have to add 2 numbers, say 4 and 5.

Then double the result of add.

Then square the result of double.

Then multiply the result of double with 6.

A brain not used to functional programming would come up with this.

multiply (square ((double (add 4 5)))) 6

Nothing wrong with the above expression. It works in F#. But its a tad bit ugly, if you ask me.

But, with the pipe operator, we can come up with elegant code.

add 4 5 |> double |> square |> multiply 6

Elegant and more readable, isn’t it?

The evaluation starts from left to right. add 4 5 is evaluated first and the result value is piped forward as an argument to the double function. The result value is piped as an argument to square and the result of square is piped to the mutiply as a second argument to it since there already exists the first argument 6.

If you see a need to series of connected function calls, consider using the |> operator.

Until next time. Cheers.

--

--