Vasu Balakrishnan’s Blog

F# |> operator

leave a comment »

 

As I was reading this blog, it made it clear to me the usefulness of currying, partial application forward pipe concepts of a functional program.

Look at the following lines of code in C#. If we don’t want to store intermediate results we have to write our algorithm in reverse order and with heavily use of brackets. The function we want to apply last has to be written first. This is not the way we think about it.

 
var list = new List<int> {4,2,6,5,9,3,8,1,3,0};
Console.WriteLine(Square(CalculateSum(FilterEven(list))));

 

The same can be written in F# as below. We describe the data flow in exactly the same order we talked about it.

 
let list = [4; 2; 6; 5; 9; 3; 8; 1; 3; 0] 
let square x = x * x
list 
    |> List.filter (fun x -> x % 2 = 0) // partial application 
    |> List.sum 
    |> square 
    |> printfn "%A" // partial application

 

Advertisements

Written by nbvasu

June 18, 2009 at 10:59 pm

Posted in F#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: