Since functions are values, it's actually the same as giving names to other values. We can assign functions the same way we assign any other function, like let x = 3110;;.
let inc = fun x -> x + 1;;
val inc : int -> int = <fun>
Now our function is bound to the name inc! It will increment any int value passed to it.
inc 3110;;
- : int = 3111
OCaml also provides a shorthand for this.
let inc x = x + 1;;
val inc : int -> int = <fun>
inc 3110;;
- : int = 3111
Note that the parameter goes on the left hand side of the equals sign. Here's another example:
let avg x y = (x +. y) /. 2.;;
val avg : float -> float -> float = <fun>
avg 0. 1.;;
- : float = 0.5
These two syntaxes are different, but are semantically equivalent
let inc = fun x -> x + 1;;
let inc x = x + 1;;
The latter is syntactic sugar. It's not necessary, but it makes the language sweeter. We've actually seen syntactic sugar before:
These two lines are syntactically different, but semantically equivalent:
(fun x -> x + 1) 2;;
let x = 2 in x + 1;;
In fact, if you go back to the evaluation rules lecture, you can see that OCaml processes these two statements in the exact same way under the hood, so we can see here that the let expression is syntactic sugar!
Here's another example:
let f x y = x - y in f 1 2;;
- : int = -1