Summing a list of integers Lists are one of the fundamental datatypes in OCaml. The following code example defines a recursive function sum that accepts one argument, integers, which is supposed to be a list of integers. Note the keyword rec which denotes that the function is recursive. The function recursively iterates over the given list of integers and provides a sum of the elements. The match statement has similarities to C's switch element, though it is far more general. let rec sum integers = (* Keyword rec means 'recursive'. *) match integers with | [] -> 0 (* Yield 0 if integers is the empty list []. *) | first :: rest -> first + sum rest;; (* Recursive call if integers is a non- empty list; first is the first element of the list, and rest is a list of the rest of the elements, possibly []. *) # sum [1;2;3;4;5];; - : int = 15 Another way is to use standard fold function that works with lists. let sum integers = List.fold_left (fun accumulator x -> accumulator + x) 0 integers;; # sum [1;2;3;4;5];; - : int = 15 Since the anonymous function is simply the application of the + operator, this can be shortened to: let sum integers = List.fold_left (+) 0 integers Furthermore, one can omit the list argument by making use of a partial application: let sum = List.fold_left (+) 0 Quicksort OCaml lends itself to concisely expressing recursive algorithms. The following code example implements an algorithm similar to quicksort that sorts a list in increasing order. let rec qsort = function | [] -> [] | pivot :: rest -> let is_less x = x < pivot in let left, right = List.partition is_less rest in qsort left @ [pivot] @ qsort right Or using partial application of the >= operator. let rec qsort = function | [] -> [] | pivot :: rest -> let is_less = (>=) pivot in let left, right = List.partition is_less rest in qsort left @ [pivot] @ qsort right Birthday problem The following program calculates the smallest number of people in a room for whom the probability of completely unique birthdays is less than 50% (the birthday problem, where for 1 person the probability is 365/365 (or 100%), for 2 it is 364/365, for 3 it is 364/365 × 363/365, etc.) (answer = 23). let year_size