Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 214
unknown6656 Avatar asked Oct 31 '16 14:10

unknown6656


People also ask

How can I recover my Facebook password without code?

To reset your password if you're not logged in to Facebook: Click Forgot Password?. Type the email, mobile phone number, full name or username associated with your account, then click Search. Follow the on-screen instructions.

How do I log into Facebook for free?

Email: You can log in with any email that's listed on your Facebook account. Phone number: If you have a mobile number confirmed on your account, you can enter it here (don't add any zeros before the country code, or any symbols). Username: You can also log in with your username, if you set one up.

How do u change ur Facebook name?

On the Mobile App (Android and iOS)Step 1: Click on the hamburger menu on the mobile app and scroll down to tap on Settings and Privacy. Select Settings from the dropdown menu. Step 2: Go to the Personal Information section and tap on your name to type in the new name. Step 3: Click on Review Change.


1 Answers

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
like image 65
Gus Avatar answered Sep 28 '22 15:09

Gus