Partial application and function composition
I had a small problem a while ago that requires me to iterate a list (specifically a functional style cons-list) and print the current index and the current element to the console. In F♯, you can use
to print an integer and a generic argument to the console. However if you call this while iterating a list, like
Current index: 0 Current element: 'a'
Current index: 1 Current element: 'b'
Current index: 2 Current element: 'c'
Current index: 3 Current element: 'd'
Current index: 4 Current element: 'e'
You can see that the indices are zero-based but I would like to convert it to the more user readable one-based. Of course, you can tackle this problem in many ways, such as using an explicit lambda when using List.iteri
Note that I am still using a partially applied printfn function so that the signature still matches what List.iteri requires.
Here, I would like to present yet another way to solve this problem without using lambda. First, let me present yet another set of functions, which will be pertinent to the solution
Because of currying, they are all analogous. Also, infix operators are treated as normal functions in F♯ which can be called normally when wrapped in brackets.
I now define a function that adds one to the input
Since addition is communicate (i.e. x + y = y + x), it can use partial application to perform a eta reduction.
Let’s compare the signatures of addOne and List.iteri:
Specifically, note that addOne and function parameter of List.iteri are composable. That is, you can write the following the solve my original problem:
which will gives you the one-based indices
Current index: 1 Current element: 'a'
Current index: 2 Current element: 'b'
Current index: 3 Current element: 'c'
Current index: 4 Current element: 'd'
Current index: 5 Current element: 'e'
Usually, I will just inline the addOne function and just write