Skip to content
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:

FormExpression
fun with matchfun x -> match x with 0 -> true | _ -> false
function keywordfunction 0 -> true | _ -> false
Named with funlet is_zero = fun x -> match x with 0 -> true | _ -> false
Named with functionlet 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 -> E when you need a simple unnamed function taking one argument.
  • Use function P1 -> E1 | P2 -> E2 when the anonymous function pattern-matches on its single argument.
  • Use let f x = E when you want to give the function a name for reuse.
  • Use let rec when the function needs to call itself recursively (anonymous functions via fun cannot be recursive).