OCaml
≈ 15 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
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 machine code compiler, a reversible debugger, and a package manager (OPAM) together with a composable build system for OCaml (Dune). OCaml was developed first 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.
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 machine code compiler, a reversible debugger, and a package manager (OPAM) together with a composable build system for OCaml (Dune). OCaml was developed first 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.
Features
OCaml features a static type system, type inference, parametric polymorphism, tail call (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. Although OCaml does not have a macro system as an indivisible part of the language (metaprogramming), i.e. built-in support for preprocessing, the 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 level. The latter, which is called PPX, acronym for Pre-Processor eXtension, is the recommended one. 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 machine 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 machine code generation is not available, requiring only a C compiler. OCaml bytecode and machine 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: $ ocaml OCaml version 5.4.0 Enter #help;; for help. Code can then be entered at the "#" prompt. For example, to calculate 1+2*3: 1 + 2 * 3;; - : int = 7 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": print_endline "Hello World!" can be run directly: $ ocaml hello.ml compiled into a bytecode executable: $ ocamlc hello.ml -o hello or compiled into an optimized machine-code executable: $ ocamlopt hello.ml -o hello and executed: $ ./hello Hello World! $ The first argument to ocamlc, "hello.ml", specifies the source file to compile and the "-o hello" flag specifies the output file. The option type constructor in OCaml, similar to the Maybe type in Haskell, augments a given data type to either return Some value of the given data type, or to return None . This is used to express that a value might or might not be present. Some 42;; - : int option = Some 42 None;; - : 'a option = None 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: let extract o = match o with | Some i -> string_of_int i | None -> "";; extract (Some 42);; - : string = "42" extract None;; - : 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 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 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 = 365. let rec birthday_paradox prob people = let prob = (year_size -. float people) /. year_size *. prob in if prob
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 . The given example outputs the Church numeral for five as “SSSSS0”. 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;
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: #use "topfind";; #require "num";; open Num;; The factorial function may then be written using the arbitrary-precision numeric operators , and : let rec fact n = if n =/ Int 0 then Int 1 else n */ fact(n -/ Int 1);; val fact : Num.num -> Num.num = This function can compute much larger factorials, such as 120!: string_of_num (fact (Int 120));; - : string = "6689502913449127057588118054090372586752746333138029810295671352301633 55724496298936687416527198498130815763789321409055253440858940812185989 8481114389650005964960521256960000000000000000000000000000"
Triangle (graphics)
The following program renders a rotating triangle in 2D using OpenGL: 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 () 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. 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
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. 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);; # add2 98;; - : int = 100 # add_str "Test";; - : string = "Test Test Test Test" 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. # let fourtimes f = (twice twice) f;; val fourtimes : ('a -> 'a) -> 'a -> 'a = # let add4 = fourtimes inc;; val add4 : int -> int = # add4 98;; - : int = 102
Derived languages
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: let rec power n x = if n = 0 then . . else if even n then sqr (power (n/2) x) else . . As soon as is known at runtime, a specialized and very fast power function can be created: . .~(power 5 . .)>. The result is: fun x_1 -> (x_1 * let y_3 = let y_2 = (x_1 * 1) in (y_2 * y_2) in (y_3 * y_3)) 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 machine code and JavaScript.
Software written in OCaml
Alt-Ergo, a SMT solver. Astrée, a static analyzer Coccinelle, a utility for transforming the source code of C programs. Rocq (former name: Coq), a formal proof management system. F*, a high-level, multi-paradigm, functional and object-oriented programming language intended for program verification. 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. 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. 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. Owl Scientific Computing, a dedicated system for scientific and engineering computing. Reason, an alternate syntax for OCaml that is more similar to C or JavaScript. ReScript, a statically typed programming language that transpiles to JavaScript. The Rust compiler was initially implemented in OCaml before becoming self-hosting. 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 (that later evolved into ReScript). 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. In June 2025 it announced a fork, OxCaml. Docker, which uses OCaml in the desktop editions on macOS and Windows. OCaml is used in the classroom at many computer science universities and colleges; a list of courses using OCaml (and their associated educational resources) is maintained by the OCaml website at ocaml.org.
References
External links
OCaml manual OCaml Package Manager Real World OCaml
Text derived from https://en.wikipedia.org/w/index.php?oldid=1377268957 under CC BY-SA 4.0; modifications have been made.