Wednesday, February 4, 2009

F# – Pipeline

One of the unique functional elements of F# is piping. Piping means

let (|>) x f = f x

So a |> b means b a. It’s a reverse application function. Let’s see an example:


let replace from tos list = (fun item -> 
                if item = from then tos
                else item )
let count list =
    List.length list
let printList list =
    List.iter (fun item -> printfn "[%s]" item) list
let abc = ["a";"b";"c"]
abc |> printList

abc |> replace "a" "k" |> count |> printfn "Number of items: %d"
abc |> replace "a" "k" |> printList
Number of items: 3

replace function changes list elements from to tos(tring). count function counts the number of list elements. printList prints the elements of the list.

Piping can be used to chain the results of the functions after each other. It’s very similar to the piping pattern employed on Unix/Linux systems.