REVISED: Sunday, September 21, 2025
1. INTRODUCTION
An anonymous function, also known as a lambda or closure, is a function defined without being bound to a name. Its primary purpose is to be created "on the fly" for immediate use, typically as an argument to a higher-order function (a function that takes other functions as input). This makes code more concise and readable by keeping the logic localized where it's used.
The core syntax for an anonymous function in OCaml uses the fun keyword: fun argument -> expression.
Basic Syntax
An anonymous function is created using the fun keyword, followed by its parameter(s), an arrow ->, and the function body. It's an expression that evaluates to a function value.
Let's see a basic example where we define an anonymous function and immediately apply it.
(* OCaml Script: ocaml C:\AI2025\basic_anonymous_function.m *)
(*
This entire expression `(fun x -> x * 2)` creates an anonymous function.
- `fun x`: Declares an anonymous function that accepts one argument, `x`.l
- `-> x * 2`: Defines the body of the function, which doubles the input `x`.
The parentheses `()` group the function definition so it can be immediately applied.
*)
let result = (fun x -> x * 2) 10;; (* The function is applied to the argument `10`. *)
(*
`print_int result` will print the value of `result`, which is 20.
`print_newline ()` prints a newline character for clean formatting.
*)
let () = print_int result; print_newline ();; (* Expected output: 20 *)
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows
OCaml version: The OCaml toplevel, version 5.3.0
Coq-LSP version: 0.2.3
Loading personal and system profiles took 1096ms.
PS C:\Users\User> ocaml C:\AI2025\basic_anonymous_function.ml
20
PS C:\Users\User>
2. LIST.FOLD_LEFT
While the above example works, the most common and powerful use of anonymous functions is with higher-order functions like those in the List module.
Use with Higher-Order Functions
Anonymous functions shine when used with functions like List.map, List.filter, and List.fold_left. They allow you to pass a simple, one-off operation without the need to define a separate, named helper function.
Anonymous Functions with Multiple Arguments
You can easily define anonymous functions that accept multiple arguments. This is particularly useful for functions like List.fold_left.
The List.fold_left function (a "fold" or "reduce" operation) iterates through a list to build up a single value. It takes a function, an initial accumulator value, and a list. The function it takes must accept two arguments: the accumulator and the current list element.
(* OCaml Script: fold_example.ml *)
let values = [1; 2; 3; 4; 5];; (* Define a list of integers to be summed. *)
(*
`List.fold_left` takes a function, an initial value, and a list.
- `(fun acc elem -> acc + elem)`: Our anonymous function with two arguments.
- `acc`: The accumulator, which holds the running total.
- `elem`: The current element from the list being processed.
- `acc + elem`: The body, which returns the new value for the accumulator.
- `0`: The initial value of the accumulator (`acc`) before the iteration starts.
- `values`: The list to fold over.
*)
let sum = List.fold_left (fun acc elem -> acc + elem) 0 values;;
(*
Print the final accumulated value.
*)
let () = Printf.printf "The sum is: %d\n" sum;; (* Expected output: The sum is: 15 *)
3. LIST.MAP
The List.map function applies a given function to every element of a list, returning a new list with the results.
(* OCaml Script: map_example.ml *)
let numbers = [1; 2; 3; 4; 5];; (* Define an initial list of integers. *)
(*
`List.map` takes two arguments: a function and a list.
Here, we pass an anonymous function directly to `List.map`.
- `(fun n -> n * n)`: This is our anonymous function. It takes an integer `n` and returns its square.
- `numbers`: This is the list the function will be applied to.
The result is a new list where each element is the square of the corresponding element in the original list.
*)
let squares = List.map (fun n -> n * n) numbers;;
(*
This line iterates through the `squares` list and prints each element.
- `List.iter`: Applies a function to each element of a list, but doesn't return anything (its result is `unit`).
- `(fun x -> Printf.printf "%d " x)`: An anonymous function that takes an integer `x` and prints it followed by a space.
*)
let () = List.iter (fun x -> Printf.printf "%d " x) squares; print_newline ();; (* Expected output: 1 4 9 16 25 *)
(* Without an anonymous function, you would have to write a named helper function, which adds verbosity for such a simple operation: *)
let square_it n = n * n;;
let squares = List.map square_it numbers;;
4. LIST.FILTER
The List.filter function creates a new list containing only the elements of the original list that satisfy a given predicate (a function that returns a boolean).
(* OCaml Script: filter_example.ml *)
let data = [10; 25; 30; 42; 55; 60];; (* Define a list of integers. *)
(* `List.filter` takes a predicate function and a list. - `(fun x -> x mod 2 = 0)`: This anonymous function is the predicate. - It takes an integer `x`. - It returns `true` if `x` is even (`x mod 2 = 0`) and `false` otherwise. `List.filter` builds a new list containing only the elements from `data` for which the function returned `true`.*)let evens = List.filter (fun x -> x mod 2 = 0) data;;
(* Iterate through the `evens` list and print each element.*)let () = List.iter (fun x -> Printf.printf "%d " x) evens; print_newline ();; (* Expected output: 10 30 42 60 *)
5. CONCLUSION
In summary, use an anonymous function whenever you need a simple, one-time-use function, especially when passing it as an argument to another function. This avoids polluting the namespace with named helper functions and keeps your logic concise and right where it's needed.
6. REFERENCES
Bird, R. (2015). Thinking Functionally with Haskell. Cambridge, England: Cambridge University Press.
Davie, A. (1992). Introduction to Functional Programming Systems Using Haskell. Cambridge, England: Cambridge University Press.
Goerzen, J. & O'Sullivan, B. & Stewart, D. (2008). Real World Haskell. Sebastopol, CA: O'Reilly Media, Inc.
Hutton, G. (2007). Programming in Haskell. New York: Cambridge University Press.
Lipovača, M. (2011). Learn You a Haskell for Great Good!: A Beginner's Guide. San Francisco, CA: No Starch Press, Inc.
Thompson, S. (2011). The Craft of Functional Programming. Edinburgh Gate, Harlow, England: Pearson Education Limited.