# OCaml

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/OCaml
> Markdown URL: https://mediated.wiki/source/OCaml.md
> Source: https://en.wikipedia.org/wiki/OCaml
> Source revision: 1343769161
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

{{Short description|Programming language}}
{{Distinguish|occam (programming language)}}
{{Use dmy dates|date=November 2022}}
{{Infobox programming language
 | name = OCaml
 | logo = OCaml Logo.svg
 | logo caption = 
 | screenshot = 
 | screenshot caption = 
 | paradigms = [Multi-paradigm](/source/Programming_paradigm): [functional](/source/Functional_programming), [imperative](/source/Imperative_programming), [modular](/source/Modular_programming),<ref>{{cite web|title=Modules|url=https://ocaml.org/learn/tutorials/modules.html|access-date=22 February 2020}}</ref> [object-oriented](/source/Object-oriented_programming)
 | family = [ML](/source/ML_(programming_language)): [Caml](/source/Caml)
 | scope =
 | released = {{Start date and age|1996}}<ref>{{cite web |url=https://sympa.inria.fr/sympa/arc/caml-list/1996-05/msg00003.html |title=Objective Caml 1.00 |last=Leroy |first=Xavier |author-link=Xavier Leroy |year=1996 |publisher=caml-list mailing list}}</ref>
 | designers = [Xavier Leroy](/source/Xavier_Leroy), Jérôme Vouillon, [Damien Doligez](/source/Damien_Doligez), Didier Rémy, Ascánder Suárez
 | developer = [Inria](/source/French_Institute_for_Research_in_Computer_Science_and_Automation)
 | latest release version = {{wikidata|property|edit|reference|P548=Q2804309|P348}}
 | latest release date = {{start date and age|{{wikidata|qualifier|P548=Q2804309|P348|P577}}}}
 | latest preview version = 
 | latest preview date = <!-- {{Start date and age|yyyy|mm|dd}} -->
 | typing = [Inferred](/source/Type_inference), [static](/source/Static_typing), [strong](/source/Strong_and_weak_typing), [structural](/source/Structural_typing)
 | programming language = OCaml, [C](/source/C_(programming_language))
 | platform = [IA-32](/source/IA-32), [x86-64](/source/x86-64), [Power](/source/Power_ISA), [SPARC](/source/SPARC), [ARM 32-64](/source/ARM_architecture), [RISC-V](/source/RISC-V)
 | operating system = [Cross-platform](/source/Cross-platform_software): [Linux](/source/Linux), [Unix](/source/Unix), [macOS](/source/macOS), [Windows](/source/Microsoft_Windows)
 | license = [LGPLv2.1](/source/GNU_Lesser_General_Public_License)
 | file ext = .ml, .mli
 | implementations = 
 | influenced by = [C](/source/C_(programming_language)), [Caml](/source/Caml), [Modula-3](/source/Modula-3), [Pascal](/source/Pascal_(programming_language)), [Standard ML](/source/Standard_ML)
 | influenced = [ATS](/source/ATS_(programming_language)), [Rocq](/source/Rocq) (former name: ''Coq''), [Elm](/source/Elm_(programming_language)), [F#](/source/F_Sharp_(programming_language)), [F*](/source/F*_(programming_language)), [Haxe](/source/Haxe), [Opa](/source/Opa_(programming_language)), [Rust](/source/Rust_(programming_language)),<ref>{{Cite web |url=https://doc.rust-lang.org/reference/influences.html |title=Influences - The Rust Reference |website=The Rust Reference |access-date=2023-12-31}}</ref> [Scala](/source/Scala_(programming_language)), [Gleam](/source/Gleam_(programming_language))
 | wikibooks = OCaml
}}
'''OCaml''' ({{IPAc-en|oʊ|ˈ|k|æ|m|əl}} {{respell|oh|KAM|əl}}, formerly '''Objective Caml''') is a [general-purpose](/source/General-purpose_programming_language), [high-level](/source/High-level_programming_language), [multi-paradigm](/source/Comparison_of_multi-paradigm_programming_languages) [programming language](/source/programming_language) which extends the [Caml](/source/Caml) dialect of [ML](/source/ML_(programming_language)) with [object-oriented](/source/Object-oriented_programming) features. OCaml was created in 1996 by [Xavier Leroy](/source/Xavier_Leroy), Jérôme Vouillon,<ref>{{Cite web |title=Jérôme Vouillon |url=https://www.irif.fr/~vouillon/ |access-date=2024-06-14 |website=www.irif.fr}}</ref> [Damien Doligez](/source/Damien_Doligez), Didier Rémy,<ref>{{Cite web |title=Didier Remy |url=https://pauillac.inria.fr/~remy/ |access-date=2024-06-14 |website=pauillac.inria.fr}}</ref> Ascánder Suárez, and others.

The OCaml [toolchain](/source/toolchain) includes an interactive top-level [interpreter](/source/Interpreter_(computing)), a [bytecode](/source/bytecode) [compiler](/source/compiler), an optimizing [native code](/source/native_code) compiler, a reversible [debugger](/source/debugger), and a [package manager](/source/package_manager) ([https://opam.ocaml.org/packages/ OPAM]) together with a composable build system for OCaml ([https://dune.build/ Dune]). OCaml was developed first in the context of [automated theorem proving](/source/automated_theorem_proving), and is used in [static analysis](/source/static_program_analysis) and [formal methods](/source/formal_methods) software. Beyond these areas, it has found use in [systems programming](/source/systems_programming), [web development](/source/web_development), and specific financial utilities, among other application domains.

The acronym ''CAML'' originally stood for ''Categorical Abstract Machine Language'', but OCaml omits this [abstract machine](/source/abstract_machine).<ref>{{cite web|url= http://ocaml.org/learn/history.html|title= A History of OCaml|access-date= 24 December 2016}}</ref> OCaml is a [free and open-source software](/source/free_and_open-source_software) project managed and principally maintained by the [French Institute for Research in Computer Science and Automation](/source/French_Institute_for_Research_in_Computer_Science_and_Automation) (Inria). In the early 2000s, elements from OCaml were adopted by many languages, notably [F#](/source/F_Sharp_(programming_language)) and [Scala](/source/Scala_(programming_language)).

==Philosophy==
[ML](/source/ML_(programming_language))-derived languages are best known for their static [type system](/source/type_system)s and [type-inferring](/source/type_inference) compilers. OCaml unifies [functional](/source/functional_programming), [imperative](/source/imperative_programming), and [object-oriented programming](/source/object-oriented_programming) under an ML-like type system. Thus, programmers need not be highly familiar with the pure functional language [paradigm](/source/Programming_paradigm) to use OCaml.

By requiring the programmer to work within the constraints of its static [type system](/source/type_system), OCaml eliminates many of the type-related [runtime](/source/Run-time_type_information) problems associated with [dynamically typed](/source/Type_system) languages. Also, OCaml's type-inferring compiler greatly reduces the need for the manual type annotations that are required in most statically typed languages. For example, the [data type](/source/data_type)s of variables and the [signature](/source/Type_signature)s of functions usually need not be declared explicitly, as they do in languages like [Java](/source/Java_(programming_language)) and [C#](/source/C_Sharp_(programming_language)), because they can be [inferred](/source/Type_inference) from the operators and other functions that are applied to the variables and other values in the code. Effective use of OCaml's type system can require some sophistication on the part of a programmer, but this discipline is rewarded with reliable, high-performance software. 

OCaml is perhaps most distinguished from other languages with origins in academia by its emphasis on performance. Its static type system prevents runtime type mismatches and thus obviates runtime type and safety checks that burden the performance of dynamically typed languages, while still guaranteeing runtime safety, except when [array bounds checking](/source/array_bounds_checking) is turned off or when some type-unsafe features like [serialization](/source/serialization) are used. These are rare enough that avoiding them is quite possible in practice.

Aside from type-checking overhead, [functional programming](/source/functional_programming) languages are, in general, challenging to compile to efficient machine language code, due to issues such as the [funarg problem](/source/funarg_problem). Along with standard loop, register, and instruction optimizations, OCaml's [optimizing compiler](/source/optimizing_compiler) employs [static program analysis](/source/static_program_analysis) methods to optimize value [boxing](/source/Boxing_(computer_science)) and [closure](/source/Closure_(computer_science)) allocation, helping to maximize the performance of the resulting code even if it makes extensive use of functional programming constructs.

[Xavier Leroy](/source/Xavier_Leroy) has stated that "OCaml delivers at least 50% of the performance of a decent C compiler",<ref name = "LWN">[https://lwn.net/Articles/19378/ Linux Weekly News].</ref> although a direct comparison is impossible. Some functions in the OCaml standard library are implemented with faster algorithms than equivalent functions in the standard libraries of other languages. For example, the implementation of set union in the OCaml standard library in theory is asymptotically faster than the equivalent function in the standard libraries of imperative languages (e.g., C++, Java) because the OCaml implementation can exploit the [immutability](/source/immutability) of sets to reuse parts of input sets in the output (see [persistent data structure](/source/persistent_data_structure)).

== History ==
[[File:Award for OCaml at POPL 2024.jpg|thumb|The OCaml development team receiving an award at [Symposium on Principles of Programming Languages](/source/Symposium_on_Principles_of_Programming_Languages) (POPL) 2024]]
=== Development of ML (Meta Language) ===
Between the 1970s and 1980s, [Robin Milner](/source/Robin_Milner), a British computer scientist and [Turing Award](/source/Turing_Award) winner, worked at the [University of Edinburgh](/source/University_of_Edinburgh)'s [Laboratory for Foundations of Computer Science](/source/Laboratory_for_Foundations_of_Computer_Science).<ref>{{Cite web |title=A J Milner - A.M. Turing Award Laureate |url=https://amturing.acm.org/award_winners/milner_1569367.cfm |access-date=2022-10-06 |website=amturing.acm.org}}</ref><ref name=":0">{{Cite web |last=Clarkson |first=Michael |display-authors=etal |title=1.2. OCaml: Functional Programming in OCaml |url=https://courses.cs.cornell.edu/cs3110/2021sp/textbook/intro/ocaml.html |website=courses.cs.cornell.edu |access-date=2022-10-06}}</ref> Milner and others were working on [theorem provers](/source/Automated_theorem_proving), which were historically developed in languages such as [Lisp](/source/Lisp_(programming_language)). Milner repeatedly ran into the issue that the theorem provers would attempt to claim a [proof](/source/Proof_(truth)) was valid by putting non-proofs together.<ref name=":0"/> As a result, he went on to develop the [meta language](/source/ML_(programming_language)) for his [Logic for Computable Functions](/source/Logic_for_Computable_Functions), a language that would only allow the writer to construct valid proofs with its polymorphic type system.<ref name=":1">{{Cite web |title=Prologue - Real World OCaml |url=https://dev.realworldocaml.org/prologue.html#a-brief-history |access-date=2022-10-06 |website=dev.realworldocaml.org}}</ref> ML was turned into a [compiler](/source/compiler) to simplify using LCF on different machines, and, by the 1980s, was turned into a complete system of its own.<ref name=":1"/> ML would eventually serve as a basis for the creation of OCaml.

In the early 1980s, there were some developments that prompted [INRIA](/source/French_Institute_for_Research_in_Computer_Science_and_Automation)'s Formel team to become interested in the ML language. [Luca Cardelli](/source/Luca_Cardelli), a research professor at [University of Oxford](/source/University_of_Oxford), used his ''functional abstract machine'' to develop a faster implementation of ML, and Robin Milner proposed a new definition of ML to avoid divergence between various implementations. Simultaneously, Pierre-Louis Curien, a senior researcher at [Paris Diderot University](/source/Paris_Diderot_University), developed a calculus of categorical combinators and linked it to [lambda calculus](/source/lambda_calculus), which led to the definition of the ''[categorical abstract machine](/source/categorical_abstract_machine)'' (CAM). Guy Cousineau, a researcher at Paris Diderot University, recognized that this could be applied as a compiling method for ML.<ref name=":2">{{Cite web |title=A History of OCaml – OCaml |url=https://v2.ocaml.org/learn/history.html |access-date=2022-10-07 |website=v2.ocaml.org}}</ref>

=== First implementation ===
[Caml](/source/Caml) was designed and developed first by INRIA's Formel team headed by [Gérard Huet](/source/G%C3%A9rard_Huet). The first implementation of Caml was created in 1987 and was further developed until 1992. Though it was spearheaded by Ascánder Suárez, [Pierre Weis](/source/Pierre_Weis_(computer_scientist)) and [Michel Mauny](/source/Michel_Mauny_(computer_science)) carried on with development after he left in 1988.<ref name=":2"/>

Guy Cousineau is quoted recalling that his experience with programming language implementation was initially very limited, and that there were multiple inadequacies for which he is responsible. Despite this, he believes that "Ascander, Pierre and Michel did quite a nice piece of work.”<ref name=":2"/>

=== Caml Light ===
Between 1990 and 1991, [Xavier Leroy](/source/Xavier_Leroy) designed a new implementation of Caml based on a [bytecode interpreter](/source/bytecode_interpreter) written in [C](/source/C_(programming_language)). In addition to this, [Damien Doligez](/source/Damien_Doligez) wrote a memory management system, also known as a sequential [garbage collector](/source/Garbage_collection_(computer_science)), for this implementation.<ref name=":1"/> This new implementation, known as [Caml Light](/source/Caml_Light), replaced the old Caml implementation and ran on small desktop machines.<ref name=":2"/> In the following years, libraries such as Michel Mauny's syntax manipulation tools appeared and helped promote the use of Caml in educational and research teams.<ref name=":1"/>

=== Caml Special Light ===
In 1995, Xavier Leroy released Caml Special Light, which was an improved version of Caml.<ref name=":2"/> An optimizing [native-code](/source/Native_code) compiler was added to the bytecode compiler, which greatly increased performance to comparable levels with mainstream languages such as [C++](/source/C%2B%2B).<ref name=":1"/><ref name=":2"/> Also, Leroy designed a high-level module system inspired by the module system of Standard ML which provided powerful facilities for abstraction and parameterization and made larger-scale programs easier to build.<ref name=":1"/>

=== Objective Caml ===
Didier Rémy and Jérôme Vouillon designed an expressive [type system](/source/type_system) for objects and classes, which was integrated within Caml Special Light. This led to the emergence of the Objective Caml language, first released in 1996 and subsequently renamed to OCaml in 2011. This object system notably supported many prevalent object-oriented idioms in a statically type-safe way, while those same idioms caused unsoundness or required runtime checks in languages such as C++ or [Java](/source/Java_(programming_language)). In 2000, Jacques Garrigue extended Objective Caml with multiple new features such as polymorphic methods, variants, and labeled and optional arguments.<ref name=":1"/><ref name=":2"/>

=== Ongoing development ===
Language improvements have been incrementally added for the last two decades to support the growing commercial and academic codebases in OCaml.<ref name=":1"/> The OCaml 4.0 release in 2012 added Generalized Algebraic Data Types (GADTs) and first-class modules to increase the flexibility of the language.<ref name=":1"/> The OCaml 5.0.0 release in 2022<ref>{{Cite web |title=Release of OCaml 5.0.0 OCaml Package |url=https://ocaml.org/news/ocaml-5.0 |access-date=2022-12-16 |website=OCaml |language=en |archive-date=26 March 2023 |archive-url=https://web.archive.org/web/20230326022141/https://www.ocaml.org/news/ocaml-5.0 |url-status=dead }}</ref> is a complete rewrite of the language runtime, removing the [global GC lock](/source/Global_interpreter_lock) and adding [effect handlers](/source/Effect_system) via [delimited continuations](/source/delimited_continuations). These changes enable support for [shared-memory parallelism](/source/Parallel_programming_model) and [color-blind concurrency](/source/color-blind_concurrency), respectively.

OCaml's development continued within the Cristal team at INRIA until 2005, when it was succeeded by the Gallium team.<ref>{{Cite web |title=Projet Cristal |url=http://cristal.inria.fr/ |access-date=2022-10-07 |website=cristal.inria.fr}}</ref> Subsequently, Gallium was succeeded by the Cambium team in 2019.<ref>{{Cite web |title=Gallium team - Home |url=http://gallium.inria.fr/ |access-date=2022-10-07 |website=gallium.inria.fr}}</ref><ref>{{Cite web |title=Home |url=http://cambium.inria.fr/ |access-date=2022-10-07 |website=cambium.inria.fr |language=en}}</ref> As of 2023, there are 23 core developers of the compiler distribution from a variety of organizations<ref>{{cite web|url=https://ocaml.org/governance/compiler|title=OCaml compiler governance and membership|year=2023}}</ref> and 41 developers for the broader OCaml tooling and packaging ecosystem.<ref>{{cite web|url=https://ocaml.org/governance|title=OCaml governance and projects|year=2023}}</ref> In 2023, the OCaml compiler was recognised with [ACM SIGPLAN's Programming Languages Software Award](/source/SIGPLAN).

==Features==
OCaml features a [static](/source/Semantic_analysis_(computer_science)) [type system](/source/type_system), [type inference](/source/type_inference), [parametric polymorphism](/source/parametric_polymorphism), [tail recursion](/source/tail_recursion), [pattern matching](/source/pattern_matching), first class lexical [closures](/source/Closure_(computer_science)), [functors (parametric modules)](/source/Function_object), [exception handling](/source/exception_handling), [effect handling](/source/effect_system), and incremental generational [automatic garbage collection](/source/garbage_collection_(computer_science)).

OCaml is notable for extending ML-style type inference to an object system in a general-purpose language. This permits [structural subtyping](/source/structural_subtyping), where object types are compatible if their method signatures are compatible, regardless of their declared [inheritance](/source/Inheritance_(object-oriented_programming)) (an unusual feature in statically typed languages).

A [foreign function interface](/source/foreign_function_interface) for [linking](/source/Linker_(computing)) to [C](/source/C_(programming_language)) primitives is provided, including language support for efficient numerical [arrays](/source/Array_data_structure) in formats compatible with both C and [Fortran](/source/Fortran). OCaml also supports creating libraries of OCaml functions that can be linked to a ''main'' program in C, so that an OCaml library can be distributed to C programmers who have no knowledge or installation of OCaml.

Although OCaml does not have a macro system as an indivisible part of the language ([metaprogramming](/source/metaprogramming)), i.e. built-in support for [preprocessing](/source/Preprocessor), the [https://ocaml.org/docs/metaprogramming OCaml platform does officially support a library for writing such preprocessors]. These can be of two types: one that works at the source code level (as in C), and one that works on the [Abstract Syntax Tree](/source/Abstract_syntax_tree) level. The latter, which is called PPX, acronym for Pre-Processor eXtension, is the recommended one.

The OCaml distribution contains:
* [Lexical analysis](/source/Lexical_analysis) and [parsing](/source/parsing) tools called ''ocamllex'' and ''ocamlyacc''
* [Debugger](/source/Debugger) that supports stepping backwards to investigate errors
* [Documentation generator](/source/Documentation_generator)
* [Profiler](/source/Profiler_(computer_science)) – to measure performance
* Many general-purpose [libraries](/source/Library_(computing))

The native code compiler is available for many platforms, including [Unix](/source/Unix), [Microsoft Windows](/source/Microsoft_Windows), and [Apple](/source/Apple_Inc.) [macOS](/source/macOS). Portability is achieved through native [code generation](/source/code_generation_(compiler)) support for major architectures: 

* [X86-64](/source/X86-64) (AMD64), [RISC-V](/source/RISC-V), and [ARM64](/source/ARM64) (in OCaml 5.0.0 and higher)<ref>{{cite web|url=https://github.com/ocaml/ocaml/tree/trunk/asmcomp|title=ocaml/asmcomp at trunk · ocaml/ocaml · GitHub|work=GitHub|access-date=2 May 2015}}</ref>
* [IBM Z](/source/IBM_Z) (before OCaml 5.0.0, and back in OCaml 5.1.0)
* [Power](/source/Power_ISA) (before OCaml 5.0.0, and due to reappear in OCaml 5.2.0)
* [IA-32](/source/IA-32) and [ARM](/source/ARM_architecture) (before OCaml 5.0.0)
* [SPARC](/source/SPARC) (before OCaml 4.06.0)
* [DEC Alpha](/source/DEC_Alpha), [HPPA](/source/HPPA), [IA64](/source/IA64) and [MIPS](/source/MIPS_architecture) (before OCaml 4.00.0)

The [bytecode](/source/bytecode) [compiler](/source/compiler) supports operation on any 32- or 64-bit architecture when native code generation is not available, requiring only a C compiler.

OCaml bytecode and native code programs can be written in a [multithreaded](/source/Thread_(computer_science)) style, with [preemptive](/source/Preemption_(computing)) context switching. OCaml [threads](/source/Thread_(computing)) in the same domain<ref>A domain is a unit of parallelism in OCaml, a domain usually corresponds to a CPU core</ref> execute by [time sharing](/source/Time-sharing) only. However, an OCaml program can contain several domains.

==Code examples==
{{one source|date=January 2024}}
[Snippets](/source/Snippet_(programming)) of OCaml code are most easily studied by entering them into the ''top-level [REPL](/source/read%E2%80%93eval%E2%80%93print_loop)''. This is an interactive OCaml session that prints the [inferred](/source/Inference) types of resulting or defined expressions.<ref>{{Cite web|title=OCaml - The toplevel system or REPL (ocaml)|url=https://ocaml.org/manual/toplevel.html|access-date=2021-05-17|website=ocaml.org}}</ref> The OCaml top-level is started by simply executing the OCaml program:

<syntaxhighlight lang="console">
$ ocaml
OCaml version 5.4.0
Enter #help;; for help.

#
</syntaxhighlight>
Code can then be entered at the "#" prompt. For example, to calculate 1+2*3:
<syntaxhighlight lang="console">
# 1 + 2 * 3;;
- : int = 7
</syntaxhighlight>

OCaml infers the type of the expression to be "int" (a [machine-precision](/source/Word_(computer_architecture)) [integer](/source/Integer_(computer_science))) and gives the result "7".

===Hello World===
The following program "hello.ml":

<syntaxhighlight lang="OCaml">
print_endline "Hello World!"
</syntaxhighlight>

can be run directly:

 $ ocaml hello.ml

compiled into a [bytecode](/source/bytecode) executable:

 $ ocamlc hello.ml -o hello

or compiled into an optimized [native-code](/source/Machine_code) executable:

 $ ocamlopt hello.ml -o hello

and executed:

<syntaxhighlight lang="console">
$ ./hello
Hello World!
$
</syntaxhighlight>

The first argument to ocamlc, "hello.ml", specifies the source file to compile and the "-o hello" flag specifies the output file.<ref>{{Cite web|url=https://caml.inria.fr/pub/docs/manual-ocaml/comp.html|title = OCaml - Batch compilation (Ocamlc)}}</ref>

=== Option ===
The <code>option</code> type constructor in OCaml, similar to the <code>Maybe</code> type in [Haskell](/source/Haskell), augments a given data type to either return <code>Some</code> value of the given data type, or to return <code>None</code>.<ref>{{Cite web |title=3.7. Options — OCaml Programming: Correct + Efficient + Beautiful |url=https://cs3110.github.io/textbook/chapters/data/options.html |access-date=2022-10-07 |website=cs3110.github.io}}</ref> This is used to express that a value might or might not be present.<syntaxhighlight lang="ocaml">
# Some 42;;
- : int option = Some 42
# None;;
- : 'a option = None
</syntaxhighlight>This is an example of a function that either extracts an int from an option, if there is one inside, and converts it into a [string](/source/String_(computer_science)), or if not, returns an empty string:<syntaxhighlight lang="ocaml">
let extract o =
  match o with
  | Some i -> string_of_int i
  | None -> "";;
</syntaxhighlight><syntaxhighlight lang="ocaml">
# extract (Some 42);;
- : string = "42"
# extract None;;
- : string = ""
</syntaxhighlight>

===Summing a list of integers===
Lists are one of the fundamental datatypes in OCaml. The following code example defines a [recursive](/source/Recursion_(computer_science)) function ''sum'' that accepts one argument, ''integers'', which is supposed to be a list of integers. Note the keyword <code>rec</code> 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](/source/C_(programming_language))'s [switch](/source/Switch_statement) element, though it is far more general.

<syntaxhighlight lang="ocaml">
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 []. *)
</syntaxhighlight>
<syntaxhighlight lang="OCaml">
  # sum [1;2;3;4;5];;
  - : int = 15
</syntaxhighlight>

Another way is to use standard [fold function](/source/fold_function) that works with lists.

<syntaxhighlight lang="ocaml">
let sum integers =
  List.fold_left (fun accumulator x -> accumulator + x) 0 integers;;
</syntaxhighlight>
<syntaxhighlight lang="OCaml">
  # sum [1;2;3;4;5];;
  - : int = 15
</syntaxhighlight>

Since the [anonymous function](/source/anonymous_function) is simply the application of the + operator, this can be shortened to:

<syntaxhighlight lang="ocaml">
let sum integers =
  List.fold_left (+) 0 integers
</syntaxhighlight>

Furthermore, one can omit the list argument by making use of a [partial application](/source/partial_application):

<syntaxhighlight lang="OCaml">
let sum =
  List.fold_left (+) 0
</syntaxhighlight>

===Quicksort===
OCaml lends itself to concisely expressing recursive algorithms. The following code example implements an algorithm similar to [quicksort](/source/quicksort) that sorts a list in increasing order.

<syntaxhighlight lang="OCaml">
 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
</syntaxhighlight>

Or using partial application of the >= operator.

<syntaxhighlight lang="OCaml">
 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
</syntaxhighlight>

===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](/source/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).

<syntaxhighlight lang="OCaml">
let year_size = 365.

let rec birthday_paradox prob people =
  let prob = (year_size -. float people) /. year_size *. prob  in
  if prob < 0.5 then
    Printf.printf "answer = %d\n" (people+1)
  else
    birthday_paradox prob (people+1)
;;

birthday_paradox 1.0 1
</syntaxhighlight>

===Church numerals===
The following code defines a [Church encoding](/source/Church_encoding) of [natural number](/source/natural_number)s, with successor (succ) and addition (add). A Church numeral {{OCaml|n}} is a [higher-order function](/source/higher-order_function) that accepts a function {{OCaml|f}} and a value {{OCaml|x}} and applies {{OCaml|f}} to {{OCaml|x}} exactly {{OCaml|n}} times. To convert a Church numeral from a functional value to a string, we pass it a function that prepends the string {{OCaml|"S"}} to its input and the constant string {{OCaml|"0"}}. The given example outputs the Church numeral for five as “SSSSS0”.

<syntaxhighlight lang="OCaml">
let zero f x = x
let succ n f x = f (n f x)
let one = succ zero
let two = succ (succ zero)
let add n1 n2 f x = n1 f (n2 f x)
let to_string n = n (fun k -> "S" ^ k) "0"
let church_5 = to_string (add (succ two) two)
;;
print_endline church_5;</syntaxhighlight>

===Arbitrary-precision factorial function (libraries)===
A variety of libraries are directly accessible from OCaml. For example, OCaml has a built-in library for [arbitrary-precision arithmetic](/source/arbitrary-precision_arithmetic). As the factorial function grows very rapidly, it quickly overflows machine-precision numbers (typically 32- or 64-bits). Thus, factorial is a suitable candidate for arbitrary-precision arithmetic.

In OCaml, the Num module (now superseded by the ZArith module) provides arbitrary-precision arithmetic and can be loaded into a running top-level using:
<syntaxhighlight lang=ocaml>
# #use "topfind";;
# #require "num";;
# open Num;;
</syntaxhighlight>

The factorial function may then be written using the arbitrary-precision numeric operators {{mono|{{=}}/}}, {{mono|*/}} and {{mono|-/}} :

<syntaxhighlight lang="OCaml">
# let rec fact n =
    if n =/ Int 0 then Int 1 else n */ fact(n -/ Int 1);;
val fact : Num.num -> Num.num = <fun>
</syntaxhighlight>

This function can compute much larger factorials, such as 120!:

<syntaxhighlight lang="OCaml">
# string_of_num (fact (Int 120));;
- : string =
"6689502913449127057588118054090372586752746333138029810295671352301633
55724496298936687416527198498130815763789321409055253440858940812185989
8481114389650005964960521256960000000000000000000000000000"
</syntaxhighlight>

===Triangle (graphics)===
The following program renders a rotating triangle in 2D using [OpenGL](/source/OpenGL):

<syntaxhighlight lang="OCaml">
let () =
  ignore (Glut.init Sys.argv);
  Glut.initDisplayMode ~double_buffer:true ();
  ignore (Glut.createWindow ~title:"OpenGL Demo");
  let angle t = 10. *. t *. t in
  let render () =
    GlClear.clear [ `color ];
    GlMat.load_identity ();
    GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. ();
    GlDraw.begins `triangles;
    List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.];
    GlDraw.ends ();
    Glut.swapBuffers () in
  GlMat.mode `modelview;
  Glut.displayFunc ~cb:render;
  Glut.idleFunc ~cb:(Some Glut.postRedisplay);
  Glut.mainLoop ()
</syntaxhighlight>

The LablGL bindings to OpenGL are required. The program may then be compiled to bytecode with:

 $ ocamlc -I +lablGL lablglut.cma lablgl.cma simple.ml -o simple

or to nativecode with:

 $ ocamlopt -I +lablGL lablglut.cmxa lablgl.cmxa simple.ml -o simple

or, more simply, using the ocamlfind build command
 $ ocamlfind opt simple.ml -package lablgl.glut -linkpkg -o simple

and run:

 $ ./simple

Far more sophisticated, high-performance 2D and 3D graphical programs can be developed in OCaml. Thanks to the use of OpenGL and OCaml, the resulting programs can be cross-platform, compiling without any changes on many major platforms.

===Fibonacci sequence===
The following code calculates the [Fibonacci sequence](/source/Fibonacci_number) of a number ''n'' inputted. It uses [tail recursion](/source/tail_recursion) and pattern matching.
<syntaxhighlight lang = OCaml>
let fib n =
  let rec fib_aux m a b =
    match m with
    | 0 -> a
    | _ -> fib_aux (m - 1) b (a + b)
  in fib_aux n 0 1
</syntaxhighlight>

===Higher-order functions===
Functions may take functions as input and return functions as result. For example, applying ''twice'' to a function ''f'' yields a function that applies ''f'' two times to its argument.
<syntaxhighlight lang = OCaml>
let twice (f : 'a -> 'a) = fun (x : 'a) -> f (f x);;
let inc (x : int) : int = x + 1;;
let add2 = twice inc;;
let inc_str (x : string) : string = x ^ " " ^ x;;
let add_str = twice(inc_str);;
</syntaxhighlight>
<syntaxhighlight lang = OCaml highlight="1,3">
  # add2 98;;
  - : int = 100
  # add_str "Test";;
  - : string = "Test Test Test Test"
</syntaxhighlight>
The function ''twice'' uses a type variable'' 'a'' to indicate that it can be applied to any function ''f'' mapping from a type'' 'a'' to itself, rather than only to ''int->int'' functions. In particular, ''twice'' can even be applied to itself.
<syntaxhighlight lang = OCaml highlight="1,3,5">
  # let fourtimes f = (twice twice) f;;
  val fourtimes : ('a -> 'a) -> 'a -> 'a = <fun>
  # let add4 = fourtimes inc;;
  val add4 : int -> int = <fun>
  # add4 98;;
  - : int = 102
</syntaxhighlight>

==Derived languages==

===MetaOCaml===
MetaOCaml<ref name = "Meta">{{cite web|url=http://okmij.org/ftp/ML/MetaOCaml.html|title=BER MetaOCaml|last=oleg-at-okmij.org|website=okmij.org}}</ref> is a [multi-stage programming](/source/multi-stage_programming) extension of OCaml enabling incremental compiling of new [machine code](/source/machine_code) during runtime. Under some circumstances, significant [speedups](/source/Speedup) are possible using [multistage programming](/source/Multi-stage_programming), because more detailed information about the data to process is available at runtime than at the regular compile time, so the incremental compiler can optimize away many cases of condition checking, etc.

As an example: if at compile time it is known that some [power function](/source/Exponentiation) {{OCaml|x -> x^n}} is needed often, but the value of {{OCaml|n}} is known only at [runtime](/source/Runtime_system), a two-stage power function can be used in MetaOCaml:

<syntaxhighlight lang="OCaml">
let rec power n x =
  if n = 0
  then .<1>.
  else
    if even n
    then sqr (power (n/2) x)
    else .<.~x *. .~(power (n - 1) x)>.
</syntaxhighlight>

As soon as {{OCaml|n}} is known at runtime, a specialized and very fast power function can be created:

<syntaxhighlight lang="OCaml">
.<fun x -> .~(power 5 .<x>.)>.
</syntaxhighlight>

The result is:

<syntaxhighlight lang="OCaml">
fun x_1 -> (x_1 *
    let y_3 = 
        let y_2 = (x_1 * 1)
        in (y_2 * y_2)
    in (y_3 * y_3))
</syntaxhighlight>

The new function is automatically compiled.

===Other derived languages===
* [F#](/source/F_Sharp_(programming_language)) is a [.NET](/source/.NET) framework language based on OCaml.
* [JoCaml](/source/JoCaml) integrates constructions for developing [concurrent](/source/Concurrent_computing) and [distributed programs](/source/Distributed_computing).
* [Reason](/source/Reason_(programming_language)) is an alternative OCaml [syntax](/source/syntax_(programming_languages)) and [toolchain](/source/toolchain) for OCaml created at [Facebook](/source/Facebook), which can compile to both native code and [JavaScript](/source/JavaScript).

==Software written in OCaml==
* Ahrefs, an [SEO](/source/Search_engine_optimization) software product 
* [Alt-Ergo](/source/Alt-Ergo), a [SMT solver](/source/Satisfiability_modulo_theories).
* [Astrée](/source/Astr%C3%A9e_(static_analysis)), a [static analyzer](/source/Static_program_analysis)
* [Be Sport](/source/Be_Sport), a [social network](/source/Social_networking_service)
* [Coccinelle](/source/Coccinelle_(software)), a utility for [transforming](/source/program_transformation) the [source code](/source/source_code) of [C](/source/C_(programming_language)) programs.
* [Rocq](/source/Rocq) (former name: ''Coq''), a [formal proof](/source/formal_proof) [management system](/source/management_system).
* Easycrypt, a [toolset](/source/Programming_tool) for writing [computer-aided proofs](/source/Computer-assisted_proof).<ref>{{Citation |title=EasyCrypt/easycrypt |date=2024-07-05 |url=https://github.com/EasyCrypt/easycrypt |access-date=2024-07-05 |publisher=EasyCrypt}}</ref>
* [F*](/source/F*_(programming_language)), a high-level, multi-paradigm, functional and object-oriented programming language intended for [program verification](/source/Formal_verification).
* [FFTW](/source/Fastest_Fourier_Transform_in_the_West), a [library](/source/Library_(computing)) for computing [discrete Fourier transform](/source/discrete_Fourier_transform)s. Several C routines have been generated by an OCaml program named {{OCaml|genfft}}.
* The web version of [Facebook Messenger](/source/Facebook_Messenger).<ref>{{cite web|title=Messenger.com Now 50% Converted to Reason · Reason|url=https://reasonml.github.io/blog/2017/09/08/messenger-50-reason.html|website=reasonml.github.io|access-date=2018-02-27}}</ref>
* Flow, a [static analyzer](/source/static_program_analysis) created at [Facebook](/source/Facebook) that infers and checks [static types](/source/Type_system) for [JavaScript](/source/JavaScript).<ref>{{cite web|url=https://flow.org/en/|title=Flow: A Static Type Checker for JavaScript|website=Flow|access-date=10 February 2019|archive-date=8 April 2022|archive-url=https://web.archive.org/web/20220408204727/https://flow.org/en/|url-status=dead}}</ref>
* [Frama-C](/source/Frama-C), a framework for analyzing C programs.
* [GeneWeb](/source/GeneWeb), free and open-source multi-platform genealogy software.
* The [Hack](/source/Hack_(programming_language)) programming language compiler, created at Facebook, extending [PHP](/source/PHP) with static types.
* The [Haxe](/source/Haxe) programming language compiler.
* [HOL Light](/source/HOL_Light), a formal proof assistant.
* Infer, a static analyzer created at Facebook for [Java](/source/Java_(programming_language)), C, [C++](/source/C%2B%2B), and [Objective-C](/source/Objective-C), used to detect bugs in [iOS](/source/iOS) and [Android](/source/Android_(operating_system)) apps.<ref>{{cite web|url=https://fbinfer.com/|title=Infer static analyzer|website=Infer}}</ref>
* [Liquidsoap](/source/Liquidsoap), a [scripting language](/source/scripting_language) for generating multimedia streams.
* [MirageOS](/source/MirageOS), a [unikernel](/source/unikernel) programming framework written in pure OCaml.
* [MLdonkey](/source/MLdonkey), a [peer-to-peer file sharing](/source/peer-to-peer_file_sharing) application based on the [EDonkey network](/source/EDonkey_network).
* [Ocsigen](/source/Ocsigen), a [client server](/source/Client%E2%80%93server_model) Web and mobile development [framework](/source/Application_framework)
* [Opa](/source/Opa_(programming_language)), a free and open-source programming language for web development.
* [Owl Scientific Computing](/source/Owl_Scientific_Computing), a dedicated system for scientific and engineering computing.
* [Reason](/source/Reason_(programming_language)), an alternate syntax for OCaml that is more similar to C or JavaScript.
* [ReScript](/source/ReScript), a statically typed programming language that transpiles to JavaScript.
* The [Rust](/source/Rust_(programming_language)) compiler was [initially implemented](/source/Bootstrapping_(compilers)) in OCaml before becoming [self-hosting](/source/Self-hosting_(compilers)).
* [Tezos](/source/Tezos), a self-amending smart contract platform using XTZ as a native currency.
* [Unison](/source/Unison_(software)), a [file synchronization](/source/file_synchronization) program to synchronize files between two directories.
* The reference interpreter for [WebAssembly](/source/WebAssembly), a low-level [bytecode](/source/bytecode) intended for execution inside [web browser](/source/web_browser)s.<ref>{{cite web|url=https://github.com/WebAssembly/spec|title=WebAssembly/spec: WebAssembly specification, reference interpreter, and test suite.|date=5 December 2019|publisher=[World Wide Web Consortium](/source/World_Wide_Web_Consortium)|access-date=2021-05-14|via=GitHub}}</ref>
* [Xen Cloud Platform](/source/Xen_Cloud_Platform) (XCP), a [turnkey](/source/turnkey) [virtualization](/source/virtualization) solution for the [Xen](/source/Xen) [hypervisor](/source/hypervisor).

==Users==
At least several dozen companies use OCaml to some degree.<ref name="ocaml.org-companies">{{Cite web|url=https://ocaml.org/learn/companies.html|title=Companies using OCaml|access-date=2021-05-14|publisher=OCaml.org}}</ref> Notable examples include:
* [Bloomberg L.P.](/source/Bloomberg_L.P.), which created BuckleScript, an OCaml compiler backend targeting JavaScript (that later evolved into [ReScript](/source/ReScript)).<ref>{{cite web|url=https://www.techatbloomberg.com/blog/bucklescript-1-0-release-arrived/|title=BuckleScript: The 1.0 release has arrived! {{!}} Tech at Bloomberg|date=8 September 2016|website=Tech at Bloomberg|ref=12|access-date=21 May 2017}}</ref>
* [Citrix Systems](/source/Citrix_Systems), which uses OCaml in [XenServer](/source/Citrix_Systems) (rebranded as Citrix Hypervisor during 2018).<ref>{{cite conference|url=https://dl.acm.org/doi/10.1145/1863543.1863557|doi=10.1145/1863543.1863557|first1=David|last1=Scott|first2=Richard|last2=Sharp|first3=Thomas|last3=Gazagnaire|first4=Anil|last4=Madhavapeddy|title=Using functional programming within an industrial product group: perspectives and perceptions|publisher=[Association for Computing Machinery](/source/Association_for_Computing_Machinery)|conference=[International Conference on Functional Programming](/source/International_Conference_on_Functional_Programming)|year=2010|url-access=subscription}}</ref>
* [Facebook](/source/Facebook), which developed Flow,<ref>{{cite web|url=https://github.com/facebook/flow|title=Flow on GitHub|website=[GitHub](/source/GitHub) |year=2023}}</ref> Hack, Infer, Pfff, and [ReasonML](/source/Reason_(programming_language)) in OCaml.
* [Jane Street Capital](/source/Jane_Street_Capital), a [proprietary trading](/source/proprietary_trading) firm, which adopted OCaml as its preferred language in its early days<ref>{{cite web|url=http://cacm.acm.org/magazines/2011/11/138203-ocaml-for-the-masses/fulltext|title=OCaml for the Masses|author=Yaron Minsky|date=1 November 2011|access-date=2 May 2015}}</ref> and continues to use it as of 2023.<ref>{{cite web|url=http://cufp.org/2016/yaron-minsky-keynote.html|title= Keynote - Observations of a Functional Programmer|author=Yaron Minsky|publisher=[ACM](/source/Association_for_Computing_Machinery) Commercial Uses of Functional Programming|year=2016}}</ref><ref>{{cite podcast|title=Signals & Threads|year=2023|publisher=[Jane Street Capital](/source/Jane_Street_Capital)|url=https://signalsandthreads.com|host=Yaron Minsky}}</ref> In June 2025 it announced a fork, ''OxCaml''.<ref>[https://www.economist.com/finance-and-economics/2025/06/26/jane-streets-sneaky-retention-tactic Jane Street’s sneaky retention tactic], ''The Economist'', Jun 26, 2025.</ref>
* [Docker](/source/Docker_(software)), which uses OCaml in the desktop editions on [macOS](/source/macOS) and [Windows](/source/Windows).<ref>{{cite web|url=https://www.docker.com/blog/docker-unikernels-open-source/|title=Improving Docker with Unikernels: Introducing HyperKit, VPNKit and DataKit|author=[Anil Madhavapeddy](/source/Anil_Madhavapeddy)|year=2016|publisher=[Docker, Inc.](/source/Docker%2C_Inc.)}}</ref><ref>{{cite web|url=https://github.com/moby/vpnkit|title=VPNKit on GitHub|website=[GitHub](/source/GitHub) |year=2023}}</ref><ref>{{Cite journal |last=Madhavapeddy |first=Anil |author-link=Anil Madhavapeddy |last2=Scott |first2=David J. |last3=Ferris |first3=Patrick |last4=Gibb |first4=Ryan T. |last5=Gazagnaire |first5=Thomas |date=2025-08-05 |title=Functional Networking for Millions of Docker Desktops (Experience Report) |url=https://dl.acm.org/doi/10.1145/3747525 |journal=Proceedings of the ACM on Programming Languages |language=en |volume=9 |issue=ICFP |pages=597–615 |doi=10.1145/3747525 |issn=2475-1421|doi-access=free }}</ref>

In the context of academic teaching and research, OCaml has a remarkable presence in computer science teaching programmes, both in universities and colleges. A list of educational resources and these teaching programmes can be found at [https://ocaml.org/academic-users/institutions ocaml.org].

==References==
{{Reflist}}

==External links==
{{wikibooks|OCaml}}
* {{Official website}}
* [https://v2.ocaml.org/manual/ OCaml manual]
* [https://opam.ocaml.org/ OCaml Package Manager]
* [https://dev.realworldocaml.org/ Real World OCaml]

{{ML programming}}
{{Programming languages}}
{{Authority control}}

Category:High-level programming languages
Category:Cross-platform free software
Category:Compiled programming languages
Category:Extensible syntax programming languages
Category:Free and open source interpreters
Category:Functional languages
Category:Object-oriented programming languages
Category:ML programming language family
Category:OCaml programming language family
Category:Software programmed in OCaml
Category:Pattern matching programming languages
Category:Programming languages created in 1996
Category:Statically typed programming languages
Category:Software using the GNU Lesser General Public License
<!-- Hidden categories below -->
Category:Articles with example OCaml code

---
Adapted from the Wikipedia article [OCaml](https://en.wikipedia.org/wiki/OCaml) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/OCaml?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
