The most basic kind of function in OCaml is the anonymous function.
This anonymous function takes in an argument, x, and returns x + 1.
(fun x -> x + 1)
- : int -> int = <fun>
What does this output mean?
<fun>. The angle brackets mean that this is an unprintable value. utop cannot fully display this type. It tells us that it's a function, but it cannot tell us more about the value.int -> int is the type of the function. int -> int means that the function takes in an integer as input, and returns an integer.- means that it's anonymous.This has a lot of parallels to other things we've seen.
3110;;
- : int = 3110
Here we have the anonymous integer 3110. See the -? That means it's anonymous.
Let's try to call our function!
(fun x -> x + 1) 3110;;
- : int = 3111
In OCaml, we just write our arguments immediately after our function. Here, 3110 is parsed as the argument and fun x -> x + 1 is the function.
Here we have a function that takes the average of two floats.
(fun x y -> (x +. y) /. 2.);;
- : float -> float -> float = <fun>
We can also call this function the same way!
(fun x y -> (x +. y) /. 2.) 2110. 3110.;;
- : float = 2610.