TExcelTAD
Home › OCaml › OCaml Higher-Order Functions

OCaml Higher-Order Functions

A higher-order function takes a function as an argument or returns one. In OCaml they replace most hand-written loops. Three of them cover a huge range of tasks:

Function Type Purpose
List.map ('a -> 'b) -> 'a list -> 'b list transform every element
List.filter ('a -> bool) -> 'a list -> 'a list keep elements that pass a test
List.fold_left ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc combine all elements into one result

List.map

map applies a function to each element and returns the list of results. The new list can have a different element type:

ocaml · try it yourself
let () =
  let prices = [ 4.5; 12.0; 7.25 ] in
  let with_vat = List.map (fun p -> p *. 1.2) prices in
  let labels = List.map (Printf.sprintf "%.2f EUR") with_vat in
  List.iter print_endline labels;
  let lengths = List.map String.length [ "map"; "filter"; "fold_left" ] in
  print_endline (String.concat "," (List.map string_of_int lengths))
5.40 EUR
14.40 EUR
8.70 EUR
3,6,9

List.filter

filter keeps the elements for which a predicate (a function returning bool) is true:

ocaml · try it yourself
let is_prime n =
  let rec check d = d * d > n || (n mod d <> 0 && check (d + 1)) in
  n >= 2 && check 2

let () =
  let numbers = List.init 30 (fun i -> i + 1) in
  let primes = List.filter is_prime numbers in
  print_endline (String.concat " " (List.map string_of_int primes));
  let long_words = List.filter (fun w -> String.length w > 4) [ "sun"; "planet"; "moon"; "galaxy" ] in
  print_endline (String.concat " " long_words)
2 3 5 7 11 13 17 19 23 29
planet galaxy

List.fold_left

fold_left f init lst walks the list from left to right, keeping an accumulator. It starts with init, and for each element x computes f acc x:

ocaml · try it yourself
let () =
  let nums = [ 3; 8; 1; 6 ] in
  let total = List.fold_left ( + ) 0 nums in
  let largest = List.fold_left max min_int nums in
  let reversed = List.fold_left (fun acc x -> x :: acc) [] nums in
  let sentence = List.fold_left (fun acc w -> acc ^ w ^ " ") "" [ "fold"; "is"; "flexible" ] in
  Printf.printf "%d %d\n" total largest;
  print_endline (String.concat " " (List.map string_of_int reversed));
  print_endline sentence
18 8
6 1 8 3
fold is flexible 

Step by step, fold_left ( + ) 0 [3; 8; 1; 6] computes ((((0 + 3) + 8) + 1) + 6) = 18.

List.fold_right f lst init goes from right to left: f 3 (f 8 (f 1 (f 6 init))). It is natural for building lists in order, but it is not tail-recursive, so prefer fold_left on long lists.

Folding into a richer accumulator

The accumulator can be any type, such as a tuple holding several running values:

ocaml · try it yourself
type stats = { count : int; sum : float; min : float; max : float }

let summarize = function
  | [] -> None
  | x :: rest ->
      let start = { count = 1; sum = x; min = x; max = x } in
      let step s v = { count = s.count + 1; sum = s.sum +. v; min = Float.min s.min v; max = Float.max s.max v } in
      Some (List.fold_left step start rest)

let () =
  match summarize [ 21.5; 19.0; 24.25; 18.75; 22.0 ] with
  | None -> print_endline "no data"
  | Some s ->
      Printf.printf "n=%d mean=%.2f min=%.2f max=%.2f\n" s.count (s.sum /. float s.count) s.min s.max
n=5 mean=21.10 min=18.75 max=24.25

More helpers

ocaml · try it yourself
let () =
  let words = [ "3"; "apple"; "12"; "x"; "7" ] in
  (* filter_map: transform and drop failures in one pass *)
  let nums = List.filter_map int_of_string_opt words in
  print_endline (String.concat " " (List.map string_of_int nums));
  (* concat_map: each element becomes a list, results are joined *)
  let expanded = List.concat_map (fun n -> [ n; n * 10 ]) [ 1; 2; 3 ] in
  print_endline (String.concat " " (List.map string_of_int expanded));
  (* mapi: the index is passed too *)
  List.mapi (fun i w -> Printf.sprintf "%d:%s" i w) [ "a"; "b"; "c" ] |> String.concat " " |> print_endline;
  (* map2: walk two lists together *)
  List.map2 (fun q p -> float q *. p) [ 2; 1; 4 ] [ 1.5; 3.0; 0.25 ]
  |> List.fold_left ( +. ) 0.0 |> Printf.printf "basket total %.2f\n"
3 12 7
1 10 2 20 3 30
0:a 1:b 2:c
basket total 7.00

Returning functions

Higher-order functions can also produce functions. Here a function builds validators from rules:

ocaml · try it yourself
let at_least n = fun s -> String.length s >= n
let contains_digit s = String.exists (fun c -> c >= '0' && c <= '9') s
let all_of rules = fun s -> List.for_all (fun rule -> rule s) rules

let strong_password = all_of [ at_least 8; contains_digit ]

let () =
  List.iter
    (fun p -> Printf.printf "%-12s %b\n" p (strong_password p))
    [ "short1"; "longenough"; "longenough9" ]
short1       false
longenough   false
longenough9  true

Test yourself

What is List.map (fun x -> x * x) [1; 2; 3]?

  1. 14
  2. [1; 4; 9]
  3. [2; 4; 6]
  4. [1; 2; 3]

What is List.fold_left (fun acc x -> acc - x) 10 [1; 2; 3]?

  1. 4
  2. 16
  3. -4
  4. 8

Which function transforms elements and drops the ones that give None?

  1. List.filter
  2. List.map
  3. List.filter_map
  4. List.concat_map