I am new to F# and I recently discovered the function composition operator >>
I understand the basic principle so that something like this is possible….
let Add1ToNum x = x +1
let Mul2ToNum y = y * 2
let FuncComp = Add1ToNum >> Mul2ToNum
However, how would one handle composition when you have several functions that have a varying number of input parameters… for instance I would like to be able to do the following…
let AddNums (x,y) = x+y
let MulNums (x,y) = x*y
let FuncComp = Add1 >> Mul2
Which obviously doesn’t work because AddNums is returning an int, and MulNums is expecting a tuple.
Is there some form of syntax that allows me to accomplish this, or if I am wanting to use Function Composition do I have to always perform some sort of intermediary function to transform the values?
Anyone suggestions on this would be much appreciated.
As Yin and codekaizen pointed out, you cannot compose the two functions to create a function that passes the input to the first one and then passes the output of this call to the second function (that is, using th
>>operator). Using a diagram, you cannot do:One option is to change the function and specify one of the parameters, so that the functions can be composed. The example by codekaizen uses this and could be also written like this (if you used currying instead of tupled parameters):
Another option for composing the functions is to create a function that takes several inputs, passes two numbers to the first function and then calls the second function with the result and another number from the original inputs. Using a diagram:
If you need something like that, then the best option is to write that directly, because this probably won’t be a frequently repeated pattern. Directly, this is easy (using the curried variant):
If you wanted to write something like that more generally (or just for curiosity), you could write something like this (using the tupled version of functions this time). The
&&&operator is inspired by Arrows: