OCaml

OCaml (, formerly Objective Caml) is a general-purpose, high-level, multi-paradigm programming language which extends the Caml dialect of ML with object-oriented features. OCaml was created in 1996 by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy, Ascánder Suárez, and others.

The OCaml toolchain includes an interactive top-level interpreter, a bytecode compiler, an optimizing native code compiler, a reversible debugger, and a package manager (OPAM). OCaml was initially developed in the context of automated theorem proving, and is used in static analysis and formal methods software. Beyond these areas, it has found use in systems programming, 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. OCaml is a free and open-source software project managed and principally maintained by the French Institute for Research in Computer Science and Automation (Inria). In the early 2000s, elements from OCaml were adopted by many languages, notably F# and Scala.

Philosophy
ML-derived languages are best known for their static type systems and type-inferring compilers. OCaml unifies functional, imperative, and object-oriented programming under an ML-like type system. Thus, programmers need not be highly familiar with the pure functional language paradigm to use OCaml.

By requiring the programmer to work within the constraints of its static type system, OCaml eliminates many of the type-related runtime problems associated with dynamically typed 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 types of variables and the signatures of functions usually need not be declared explicitly, as they do in languages like Java and C#, because they can be inferred 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 is turned off or when some type-unsafe features like serialization are used. These are rare enough that avoiding them is quite possible in practice.

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

Xavier Leroy has stated that "OCaml delivers at least 50% of the performance of a decent C compiler", 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 of sets to reuse parts of input sets in the output (see persistent data structure).

Development of ML (Meta Language)
Between the 1970s and 1980s, Robin Milner, a British computer scientist and Turing Award winner, worked at the University of Edinburgh's Laboratory for Foundations of Computer Science. Milner and others were working on theorem provers, which were historically developed in languages such as Lisp. Milner repeatedly ran into the issue that the theorem provers would attempt to claim a proof was valid by putting non-proofs together. As a result, he went on to develop the meta language for his Logic for Computable Functions, a language that would only allow the writer to construct valid proofs with its polymorphic type system. ML was turned into a compiler to simplify using LCF on different machines, and, by the 1980s, was turned into a complete system of its own. ML would eventually serve as a basis for the creation of OCaml.

In the early 1980s, there were some developments that prompted INRIA's Formel team to become interested in the ML language. Luca Cardelli, a research professor at 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, developed a calculus of categorical combinators and linked it to lambda calculus, which led to the definition of the categorical abstract machine (CAM). Guy Cousineau, a researcher at Paris Diderot University, recognized that this could be applied as a compiling method for ML.

First implementation
Caml was initially designed and developed by INRIA's Formel team headed by Gérard 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 and Michel Mauny carried on with development after he left in 1988.

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.”

Caml Light
Between 1990 and 1991, Xavier Leroy designed a new implementation of Caml based on a bytecode interpreter written in C. In addition to this, Damien Doligez wrote a memory management system, also known as a sequential garbage collector, for this implementation. This new implementation, known as Caml Light, replaced the old Caml implementation and ran on small desktop machines. 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.

Caml Special Light
In 1995, Xavier Leroy released Caml Special Light, which was an improved version of Caml. An optimizing native-code compiler was added to the bytecode compiler, which greatly increased performance to comparable levels with mainstream languages such as C++. 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.

Objective Caml
Didier Rémy and Jérôme Vouillon designed an expressive 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. In 2000, Jacques Garrigue extended Objective Caml with multiple new features such as polymorphic methods, variants, and labeled and optional arguments.

Ongoing development
Language improvements have been incrementally added for the last two decades to support the growing commercial and academic codebases in OCaml. The OCaml 4.0 release in 2012 added Generalized Algebraic Data Types (GADTs) and first-class modules to increase the flexibility of the language. The OCaml 5.0.0 release in 2022 is a complete rewrite of the language runtime, removing the global GC lock and adding effect handlers via delimited continuations. These changes enable support for shared-memory parallelism and color-blind concurrency, respectively.

OCaml's development continued within the Cristal team at INRIA until 2005, when it was succeeded by the Gallium team. Subsequently, Gallium was succeeded by the Cambium team in 2019. As of 2023, there are 23 core developers of the compiler distribution from a variety of organizations and 41 developers for the broader OCaml tooling and packaging ecosystem.

Features
OCaml features a static type system, type inference, parametric polymorphism, tail recursion, pattern matching, first class lexical closures, functors (parametric modules), exception handling, effect handling, and incremental generational automatic garbage collection.

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

A foreign function interface for linking to C primitives is provided, including language support for efficient numerical arrays in formats compatible with both C and 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.

The OCaml distribution contains:
 * Lexical analysis and parsing tools called ocamllex and ocamlyacc
 * Debugger that supports stepping backwards to investigate errors
 * Documentation generator
 * Profiler – to measure performance
 * Many general-purpose libraries

The native code compiler is available for many platforms, including Unix, Microsoft Windows, and Apple macOS. Portability is achieved through native code generation support for major architectures:


 * X86-64 (AMD64), RISC-V, and ARM64 (in OCaml 5.0.0 and higher)
 * IBM Z (before OCaml 5.0.0, and back in OCaml 5.1.0)
 * Power (before OCaml 5.0.0, and due to reappear in OCaml 5.2.0)
 * IA-32 and ARM (before OCaml 5.0.0)
 * SPARC (before OCaml 4.06.0)
 * DEC Alpha, HPPA, IA64 and MIPS (before OCaml 4.00.0)

The bytecode 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 style, with preemptive context switching. OCaml threads in the same domain execute by time sharing only. However, an OCaml program can contain several domains.

Code examples
Snippets of OCaml code are most easily studied by entering them into the top-level REPL. This is an interactive OCaml session that prints the inferred types of resulting or defined expressions. The OCaml top-level is started by simply executing the OCaml program:

Code can then be entered at the "#" prompt. For example, to calculate 1+2*3:

OCaml infers the type of the expression to be "int" (a machine-precision integer) and gives the result "7".

Hello World
The following program "hello.ml":

can be compiled into a bytecode executable:

$ ocamlc hello.ml -o hello

or compiled into an optimized native-code executable:

$ ocamlopt hello.ml -o hello

and executed:

The first argument to ocamlc, "hello.ml", specifies the source file to compile and the "-o hello" flag specifies the output file.

Option
The  type constructor in OCaml, similar to the   type in Haskell, augments a given data type to either return   value of the given data type, or to return. This is used to express that a value might or might not be present. 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, or if not, returns an empty string:

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  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.

Another way is to use standard fold function that works with lists.

Since the anonymous function is simply the application of the + operator, this can be shortened to:

Furthermore, one can omit the list argument by making use of a partial application:

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.

Or using partial application of the >= operator.

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).

Church numerals
The following code defines a Church encoding of natural numbers, with successor (succ) and addition (add). A Church numeral is a higher-order function that accepts a function  and a value  and applies  to  exactly  times. To convert a Church numeral from a functional value to a string, we pass it a function that prepends the string to its input and the constant string.

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. 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:

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

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

Triangle (graphics)
The following program renders a rotating triangle in 2D using OpenGL:

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 of a number n inputted. It uses tail recursion and pattern matching.

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. 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.

MetaOCaml
MetaOCaml is a multi-stage programming extension of OCaml enabling incremental compiling of new machine code during runtime. Under some circumstances, significant speedups are possible using multistage 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 is needed often, but the value of  is known only at runtime, a two-stage power function can be used in MetaOCaml:

As soon as is known at runtime, a specialized and very fast power function can be created:

The result is:

The new function is automatically compiled.

Other derived languages

 * F# is a .NET framework language based on OCaml.
 * JoCaml integrates constructions for developing concurrent and distributed programs.
 * Reason is an alternative OCaml syntax and toolchain for OCaml created at Facebook, which can compile to both native code and JavaScript.

Software written in OCaml

 * Alt-Ergo, a SMT solver.
 * Astrée, a static analyzer
 * Be Sport, a social network
 * Coccinelle, a utility for transforming the source code of C programs.
 * Coq, a formal proof management system.
 * Easycrypt, a toolset for writing computer-aided proofs.
 * FFTW, a library for computing discrete Fourier transforms. Several C routines have been generated by an OCaml program named.
 * The web version of Facebook Messenger.
 * Flow, a static analyzer created at Facebook that infers and checks static types for JavaScript.
 * Ocsigen, a client server Web and mobile development framework
 * Owl Scientific Computing, a dedicated system for scientific and engineering computing.
 * Frama-C, a framework for analyzing C programs.
 * GeneWeb, free and open-source multi-platform genealogy software.
 * The Hack programming language compiler, created at Facebook, extending PHP with static types.
 * The Haxe programming language compiler.
 * HOL Light, a formal proof assistant.
 * Infer, a static analyzer created at Facebook for Java, C, C++, and Objective-C, used to detect bugs in iOS and Android apps.
 * Liquidsoap, a scripting language for generating multimedia streams.
 * MirageOS, a unikernel programming framework written in pure OCaml.
 * MLdonkey, a peer-to-peer file sharing application based on the EDonkey network.
 * Opa, a free and open-source programming language for web development.
 * Tezos, a self-amending smart contract platform using XTZ as a native currency.
 * Unison, a file synchronization program to synchronize files between two directories.
 * The reference interpreter for WebAssembly, a low-level bytecode intended for execution inside web browsers.
 * Xen Cloud Platform (XCP), a turnkey virtualization solution for the Xen hypervisor.

Users
At least several dozen companies use OCaml to some degree. Notable examples include:
 * Bloomberg L.P., which created BuckleScript, an OCaml compiler backend targeting JavaScript.
 * Citrix Systems, which uses OCaml in XenServer (rebranded as Citrix Hypervisor during 2018).
 * Facebook, which developed Flow, Hack, Infer, Pfff, and ReasonML in OCaml.
 * Jane Street Capital, a proprietary trading firm, which adopted OCaml as its preferred language in its early days and continues to use it as of 2023.
 * Docker, which uses OCaml in the desktop editions on macOS and Windows.