Wednesday, September 30, 2009

F# Forward composition operator

I was trying to understand the difference between the plain pipe operator (|>) and the forward composition operator (>>) in F# when the F# forum pointed me to this blog post. After reading the blog post, I still didn't quite understand. I distilled it down to perhaps the simplest possible sample which I think is much easier to understand what it does and why:

let squares wrist =
List.map (fun x -> x*x) wrist

let sum wrist =
List.fold (+) 0 wrist

// Forward composition operator
// don't need to declare any value: it's implied.
let functionComp = squares >> sum

// Equivalent function as above using pipe operator.
// Note how above is more terse
let pipage wrist = wrist |> squares |> sum

let wrist = [1;2;3]

// results are the same
let fc = functionComp wrist
let p = pipage wrist

No comments: