Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# difference between let add1 x = x + 1 and let add2 x = x +1

Tags:

types

f#

What is the difference between let add1 x = x + 1 and let add2 x = x +1. The accidental removal of space changed the type of function from
val add1 : x:int->int to
val add2 : x:(int -> 'a) -> 'a

As far as I understand, the first type statement says add1 maps int onto int. But what is the meaning of the second one.

Well, 'a represents a generic type, but how is the function 'add2' returning a generic?

Thanks for your help.

like image 473
Yelena Avatar asked Jun 29 '18 00:06

Yelena


1 Answers

That's a quirk of F# syntax: a plus or minus sign immediately followed by a number literal is treated as a positive or negative number respectively, and not as an operator followed by a number.

> 42
it : int = 42

> +42
it : int = 42

> -42
it : int = -42

So your second example let add2 x = x +1 is equivalent to let add2 x = x 1. The expression x 1 means that x is a function and it's being applied to the argument 1, which is exactly what your type is telling you:

add2 : x:(int -> 'a) -> 'a

This says that add2 takes a function named x, which takes an int and returns some 'a, and that add2 itself also returns the same 'a.

like image 170
Fyodor Soikin Avatar answered Sep 20 '22 14:09

Fyodor Soikin