Part IA Michaelmas Term
Anonymous Functions
fun-notation
The fun-notation expresses a non-recursive function value without giving the function a name:
fun n -> n * 2
(* : int -> int = <fun> *)
This is the function f such that f(n) = n × 2. It can be applied immediately:
(fun n -> n * 2) 17
(* : int = 34 *)
The expression fun n -> n * 2 has the same value as a named declaration:
let double n = n * 2
(* val double : int -> int = <fun> *)
These two forms are equivalent. The fun form is used when the function is needed only once or is being passed as an argument to another function.
Pattern-matching anonymous functions
There are three equivalent ways to define an is_zero function:
| Form | Expression |
|---|---|
fun with match | fun x -> match x with 0 -> true | _ -> false |
function keyword | function 0 -> true | _ -> false |
Named with fun | let is_zero = fun x -> match x with 0 -> true | _ -> false |
Named with function | let is_zero = function 0 -> true | _ -> false |
The function keyword is shorthand for fun x -> match x with .... It introduces an anonymous argument that is immediately pattern-matched against the clauses that follow. This is convenient for functions defined by pattern-matching on a single argument.
When to use each form
- Use
fun x -> Ewhen you need a simple unnamed function taking one argument. - Use
function P1 -> E1 | P2 -> E2when the anonymous function pattern-matches on its single argument. - Use
let f x = Ewhen you want to give the function a name for reuse. - Use
let recwhen the function needs to call itself recursively (anonymous functions viafuncannot be recursive).