OCaml Functions Anonymous functions


Example

Since functions are ordinary values, there is a convenient syntax for creating functions without names:

List.map (fun x -> x * x) [1; 2; 3; 4]
(* - : int list = [1; 4; 9; 16] *)

This is handy, as we would otherwise have to name the function first (see let) to be able to use it:

let square x = x * x
(* val square : int -> int = <fun> *)

List.map square [1; 2; 3; 4]
(* - : int list = [1; 4; 9; 16] *)