05 Named Functions

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;;.

Now our function is bound to the name inc! It will increment any int value passed to it.

OCaml also provides a shorthand for this.

Note that the parameter goes on the left hand side of the equals sign. Here's another example:

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: