Reputation: 2963
I want to implement a (simple) mathematical function addition in F#, meaning:
Imagine F being the field of all functions, which map an element of A to an element of B:
Then, my "function addition" should be defined as follows:
I have tried the following code to implement the function addition as the operator !+
:
let inline (!+) (f1 : ^a -> ^b, f2 : ^a -> ^b) : ^a -> ^b =
let f (x : ^a) : ^b =
(f1 x) + (f2 x)
f
However, if I want to compile the following lines, I will get an error:
let f1 x : float = -x // negate x
let f2 x : float = 2. * x // multiply by 2
let f3 = f1 !+ f2 //error : Expexceted `float`, got `'a -> 'b`
I am pretty sure, that it is caused by some simple logical error, but I was yet unable to find it.
My question therefore is: How does one define a function addition in F#?
Upvotes: 5
Views: 246
Reputation: 26174
Quite close ! Two main issues:
!+
is a unary operator. See the rules for F# operators.
your function is taking tuples. It's not curried.
Correct it and you get it working:
let inline (++) (f1 : ^a -> ^b) (f2 : ^a -> ^b) : ^a -> ^b =
let f (x : ^a) : ^b =
(f1 x) + (f2 x)
f
let f1 x : float = -x
let f2 x : float = 2. * x
let f3 = f1 ++ f2
Let me add that you don't need any type annotation, F# will figure it out for you:
let inline (++) f1 f2 x = f1 x + f2 x
If you read the signature you'll notice that your functions can have any input type, just the result types should match:
let inline f1 x = -(float x)
let f2 x : float = float (2 * x)
let f3 = f1 ++ f2
Upvotes: 8