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:

#light

let replace from tos list =
    List.map (fun item -> 
                if item = from then tos
                else item )
             list
        
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
[a]
[b]
[c]
Number of items: 3
[k]
[b]
[c]

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.

No comments:

Post a Comment