Higher-order functions can be used to implement generic algorithms, giving up the responsibility of providing final details to the user. For instance List.sort
expects a comparison function, which allows to implement various ways of sorting. Here we implement case-insensitive sorting of strings:
let string_case_insensitive_sort lst =
let case_insensitive_compare a b =
String.compare (String.lowercase a) (String.lowercase b)
in
List.sort case_insensitive_compare lst
There is a rich list of higher-order functions in the standard library, especially in the List module, see List.fold_left
and List.sort
for instance. More advanced examples can be found in third-party libraries. A good example is the simulated annealing implemented in ocaml-gsl. Simulated annealing is a generic optimisation procedure which is parametrised by a function used to explore the set of states of the problem and an error function (called here energy function).
Users familiar with C++ can compare this to the Strategy pattern.