Oct 282009

The weird looking symbol which follows this post is the F#’s very simple but useful operator – the pipeline.  To sum up what it does in one sentence, I would say it reverses the function call and gives the impression that we are passing the argument to the function. Sounds trivial? Not so much.

One of F#’s advantages is its concise code unlike other .NET languages like VB.NET which are verbose, however this can affect the readability of code especially when you are using nested function calls.

The pipeline operator can reverse this call. For e.g. see this code

// Turn on the lightweight syntax

Seq.iter(fun n-> printfn "%d" n) ((Seq.filter (fun n->n%3=0){0 .. 200}))

Not exactly readable!! what it does is creates a sequence from 0 to 200 and filters it selecting only elements that are divisible by 3. It then iterates through the sequence printing all the values. The fun keyword is an anonymous function, which makes things more clearer and we are spared with the pain of declaring one more function.

Now lets pipeline this code:-

{0 .. 200} |> Seq.filter (fun n->n%3=0) |> Seq.iter (fun n->printfn "%d" n)

As you can see now without the parentheses, its far more simpler to understand this function. Just follow the pipeline. The execution starts with the sequence which gives way to the filter which is then iterated to print the values.

In bigger functions the pipeline is invaluable in making the code readable and more aesthetic. So next time when you are solving that really complex mathematical problem, don’t parenthesize, just pipeline it!!!