unknown6656
unknown6656

Reputation: 2963

F# Function Addition

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: enter image description here
Then, my "function addition" should be defined as follows: enter image description here

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

Answers (1)

Gus
Gus

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

Related Questions