F # Adding Function

I want to implement (simple) adding math functions to F #, which means:

Imagine that F is the field of all functions that map an element A to an element B : enter image description here
Then my "add function" should be defined as follows: enter image description here

I tried the following code to implement adding a function as an 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 sure that this is caused by some simple logical error, but I still could not find it.
So my question is: how to determine the addition of a function in F #?

+5
source share
1 answer

Pretty close! Two main problems:

  • !+ is a unary operator. See the rules for F # statements.

  • your function takes tuples. It was not.

Correct it and you will get it:

 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 do not need annotation for any type, F # will figure it out for you:

 let inline (++) f1 f2 x = f1 x + f2 x 

If you read the signature, you will notice that your functions can have any type of input, only the corresponding types of results should correspond:

 let inline f1 x = -(float x) let f2 x : float = float (2 * x) let f3 = f1 ++ f2 
+8
source

Source: https://habr.com/ru/post/1259043/


All Articles