Function composition in F#
February 4, 2017 Leave a comment
F# lets us build new functions that consists of other functions using the composition operators >> and <<. The direction of the arrows determines how the individual constituent functions are linked.
Consider the following simple functions:
let incrementByOne x = x + 1
let triple x = x * 3
let halve x = x / 2
let double x = x * 2
A common feature of each function is that each accepts a single parameter and has a return value. The input and return types are also identical. These functions are good candidates for function composition.
Here’s how to do it:
let chained = incrementByOne >> triple >> halve >> double
If we call “chained” like this…:
let chainedRes = chained 10
…then 10 is first supplied to te incrementByOne function yielding 11. 11 is the sent to triple whose end result is fed to halve and so on. The end result will be 32.
We can reverse the order of the chain by changing the direction of the arrows:
let chainedReversed = incrementByOne << triple << halve << double let chainedReversedRes = chainedReversed 10
chainedReversedRes will be 31. In the this case 10 is first applied to “double” making it 20, which is forwarded to “halve” making it 10 again and so on.
View all F# related articles here.