Functional Composition in F#
- 26 Oct, 2010
I was checking out the Channel 9 lectures on functional programming using Haskell. It’s like getting a semester of a functional programming class for free! You can find the list of channel 9 lectures here.
I’m more interested in functional programming in F# than Haskell so after an example is presented, I’m translating it into F# as an exercise and to test my understanding.
One of the first concepts introduced in chapter 2 is functional composition. Functional composition is a way to express a function in a shorter form without changing its meaning. It is a way of expressing a function without variable repetition.
The example used from Haskell was as follows:
double x = x + x quad
x = double (double x)
This is in the form f(x) = g(g(x))
Restating this with functional composition would look as follows:
double x = x + x
quad x = double . double
Here the . operator means “restated with functional composition”, not multiplication as you might expect.
This is equivalent to f(x) = g . g
F# also has a functional composition operator: >>
Here’s the same example in F#:
let double x = x + x
let quad = double >> double
We could do something similar with the F# pipe:
let double x = x + x
let quad x = x |> double |> double
I like the conciseness of the first example but I think intent is clearer to most readers in the second.