1
votes

I have the following code snippet:

let add n x = x + n
let times n x = x * n
let addTimes = add 5 >> times 5
addTimes 4 

and this works without any problem. But when I change like this

let add n x = x + n
let times n x = x * n
let addTimes = add >> times
addTimes 4 

I've got the compiling error

error FS0071: Type constraint mismatch when applying the default type '(int -> int)' for a type inference variable. Expecting a type supporting the operator '*' but given a function type. You may be missing an argument to a function. Consider adding further type constraints

Why?

1
Function composition is basically f(g(x)), but your g(x) here returns a single value while f takes 2 arguments - how would composition be expected to work? - shree.pat18
My problem is, I do not know how composition works. It so wired. - softshipper

1 Answers

2
votes

The signature of (>>) is ('T1 -> 'T2) -> ('T2 -> 'T3) -> 'T1 -> 'T3. I.e., it composes two unary functions – you are attempting to supply two binary functions, which is valid in general (though arguably not useful, or at the least unclear), but not for your function types:

Given that (f >> g) x is equivalent to g(f(x)), what would the expected outcome be when f is binary? In your case, x (int) is partially-applied to add (int -> int -> int), and that partial application ((int -> int)) is passed to times (also int -> int -> int), which obviously expects an int as its first parameter rather than the function type (int -> int).