Revision as of 11:23, 9 April 2007 editJdh30 (talk | contribs)194 edits Set performance← Previous edit | Latest revision as of 07:13, 8 January 2025 edit undoJJMC89 bot III (talk | contribs)Bots, Administrators3,696,315 editsm Moving Category:Software using the LGPL license to Category:Software using the GNU Lesser General Public License per Misplaced Pages:Categories for discussion/Speedy | ||
(689 intermediate revisions by more than 100 users not shown) | |||
Line 1: | Line 1: | ||
{{ |
{{Short description|Programming language}} | ||
{{Distinguish|occam (programming language)}} | |||
name = Objective Caml | | |||
{{Use dmy dates|date=November 2022}} | |||
logo = ] | | |||
{{Infobox programming language | |||
paradigm = ]: ], ], ] | | |||
| name = OCaml | |||
developer = ] | | |||
| logo = OCaml Logo.svg | |||
latest_release_version = 3.09.3 | | |||
| logo caption = | |||
latest_release_date = ], ] | | |||
| screenshot = | |||
operating_system = ] | | |||
| screenshot caption = | |||
genre = ] | | |||
| paradigms = ]: ], ], ],<ref>{{cite web|title=Modules|url=https://ocaml.org/learn/tutorials/modules.html|access-date=22 February 2020}}</ref> ] | |||
influenced_by = ], ] | | |||
|
| family = ]: ] | ||
| scope = | |||
license = ] (compiler)<br>] (library) | | |||
| 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> | |||
website = | | |||
| designers = ], Jérôme Vouillon, ], Didier Rémy, Ascánder Suárez | |||
| developer = ] | |||
| 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 = ], ], ], ] | |||
| programming language = OCaml, ] | |||
| platform = ], ], ], ], ], ] | |||
| operating system = ]: ], ], ], ] | |||
| license = ] | |||
| file ext = .ml, .mli | |||
| implementations = | |||
| influenced by = ], ], ], ], ] | |||
| influenced = ], ], ], ], ], ], ], ],<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> ] | |||
| wikibooks = Objective Caml | |||
}} | }} | ||
'''OCaml''' ({{IPAc-en|oʊ|ˈ|k|æ|m|əl}} {{respell|oh|KAM|əl}}, formerly '''Objective Caml''') is a ], ], ] ] which extends the ] dialect of ] with ] features. OCaml was created in 1996 by ], 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> ], 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 ] includes an interactive top-level ], a ] ], an optimizing ] compiler, a reversible ], and a ] () together with a composable build system for OCaml (). OCaml was initially developed in the context of ], and is used in ] and ] software. Beyond these areas, it has found use in ], ], and specific financial utilities, among other application domains. | |||
'''Objective Caml''' ('''OCaml''') is the main implementation of the ] ], created by ], ], ], ] and others in 1996. OCaml is an ] project managed and principally maintained by ]. | |||
The acronym ''CAML'' originally stood for ''Categorical Abstract Machine Language'', but OCaml omits this ].<ref>{{cite web|url= http://ocaml.org/learn/history.html|title= A History of OCaml|access-date= 24 December 2016}}</ref> OCaml is a ] project managed and principally maintained by the ] (Inria). In the early 2000s, elements from OCaml were adopted by many languages, notably ] and ]. | |||
OCaml extends the core Caml language with ] constructs. | |||
==Philosophy== | |||
OCaml's toolset includes an interactive toplevel ], a ] ], and an optimizing ] compiler. It has a large standard library that makes it useful for many of the same applications as ] or ], as well as robust modular and object-oriented programming constructs that make it applicable for large-scale software engineering. | |||
]-derived languages are best known for their static ]s and ] compilers. OCaml unifies ], ], and ] 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 ], OCaml eliminates many of the type-related ] problems associated with ] 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 ]s of variables and the ]s of functions usually need not be declared explicitly, as they do in languages like ] and ], 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 the successor to ]. The acronym CAML originally stood for ''Categorical Abstract Machine Language'', although OCaml abandons this abstract machine. | |||
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 ] is turned off or when some type-unsafe features like ] are used. These are rare enough that avoiding them is quite possible in practice. | |||
==Philosophy== | |||
]-derived languages are best known for their static ]s and ] compilers. OCaml unifies functional, imperative, and object-oriented programming under an ML-like type system. | |||
Aside from type-checking overhead, ] languages are, in general, challenging to compile to efficient machine language code, due to issues such as the ]. Along with standard loop, register, and instruction optimizations, OCaml's ] employs ] methods to optimize value ] and ] allocation, helping to maximize the performance of the resulting code even if it makes extensive use of functional programming constructs. | |||
] has stated that "OCaml delivers at least 50% of the performance of a decent C compiler",<ref name = "LWN">.</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 ] of sets to reuse parts of input sets in the output (see ]). | |||
== History == | |||
] (POPL) 2024]] | |||
=== Development of ML (Meta Language) === | |||
Between the 1970s and 1980s, ], a British computer scientist and ] winner, worked at the ]'s ].<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 ], which were historically developed in languages such as ]. Milner repeatedly ran into the issue that the theorem provers would attempt to claim a ] was valid by putting non-proofs together.<ref name=":0"/> As a result, he went on to develop the ] for his ], 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 ] 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 ]'s Formel team to become interested in the ML language. ], a research professor at ], 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 ], developed a calculus of categorical combinators and linked it to ], which led to the definition of the '']'' (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 === | |||
] was initially designed and developed by INRIA's Formel team headed by ]. The first implementation of Caml was created in 1987 and was further developed until 1992. Though it was spearheaded by Ascánder Suárez, ] and ] 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, ] designed a new implementation of Caml based on a ] written in ]. In addition to this, ] wrote a memory management system, also known as a sequential ], for this implementation.<ref name=":1"/> This new implementation, known as ], 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 === | |||
OCaml's static type system eliminates a large class of programmer errors that may cause problems at runtime. However, it also forces the programmer to conform to the constraints of the type system, which can require careful thought and close attention. A type-inferring compiler greatly reduces the need for manual type annotations (for example, the ] of variables and the signature of functions usually do not need to be expressly declared, as they do in ]). Nonetheless, effective use of OCaml's type system can require some sophistication on the part of the programmer. | |||
In 1995, Xavier Leroy released Caml Special Light, which was an improved version of Caml.<ref name=":2"/> An optimizing ] compiler was added to the bytecode compiler, which greatly increased performance to comparable levels with mainstream languages such as ].<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 === | |||
OCaml is perhaps most distinguished from other languages with origins in academia by its emphasis on performance. Firstly, its static type system renders runtime type mismatches impossible, and thus obviates the need for runtime type and safety checks that burden the performance of dynamically typed languages, while still guaranteeing runtime safety. | |||
Didier Rémy and Jérôme Vouillon designed an expressive ] 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 ]. 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 === | |||
Aside from type-checking overhead, ] languages are, in general, challenging to compile to efficient machine language code, due to issues such as the ]. In addition to standard loop, register, and instruction ], OCaml's optimizing compiler employs ] techniques to optimize value ] and ] allocation, helping to maximize the performance of the resulting code even if it makes extensive use of functional programming constructs. | |||
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}}</ref> is a complete rewrite of the language runtime, removing the ] and adding ] via ]. These changes enable support for ] and ], 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 ]. | |||
Xavier Leroy has cautiously stated that "OCaml delivers at least 50% of the performance of a decent C compiler"<ref name = "LWN">.</ref>, and ] have shown that this is generally the case<ref name = "Debian">.</ref>. In some cases, OCaml is much faster than other languages. For example, the implementation of set union in the OCaml standard library is asymptotically faster than the equivalent function in the standard libraries of imperative languages"<ref name = "Harrop">''OCaml for Scientists'' by Jon Harrop</ref> (e.g. C++, Java) because the OCaml implementation exploits the immutability of sets in order to reuse parts of input sets in the output (persistence). | |||
==Features== | ==Features== | ||
OCaml features a ] ], ], ], ], ], first class lexical ], ], ], ], and incremental generational ]. | |||
OCaml features: a ] | |||
], ], | |||
], ], | |||
], | |||
], | |||
], ], and | |||
incremental generational ]. | |||
OCaml is |
OCaml is notable for extending ML-style type inference to an object system in a general-purpose language. This permits ], where object types are compatible if their method signatures are compatible, regardless of their declared inheritance (an unusual feature in statically typed languages). | ||
A ] for ] |
A ] for ] to ] primitives is provided, including language support for efficient numerical ] in formats compatible with both C and ]. 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 . These can be of two types: one that works at the source code level (as in C), and one that works on the ] level. The latter, which is called PPX, acronym for Pre-Processor eXtension, is the recommended one. | |||
The OCaml distribution contains: | The OCaml distribution contains: | ||
* ] and ] tools called ''ocamllex'' and ''ocamlyacc'' | |||
*An extensible parser and ] named ], which permits the syntax of OCaml to be extended or even replaced | |||
* ] that supports stepping backwards to investigate errors | |||
*Lexer and parser tools called ocamllex and ocamlyacc | |||
* ] | |||
*] which supports stepping backwards to investigate errors | |||
* ] – to measure performance | |||
*] | |||
* Many general-purpose ] | |||
*] — for measuring performance | |||
*Numerous general purpose ] | |||
The native code compiler is available for many platforms, including ], ], and ] ]. |
The native code compiler is available for many platforms, including ], ], and ] ]. Portability is achieved through native ] support for major architectures: | ||
* ] (AMD64), ], and ] (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> | |||
OCaml bytecode and native code programs can be written in a ] style. However, because the garbage collector is not designed for concurrency, multiple OCaml threads in the same process cannot run concurrently<ref name = "INRIA">.</ref>. | |||
* ] (before OCaml 5.0.0, and back in OCaml 5.1.0) | |||
* ] (before OCaml 5.0.0, and due to reappear in OCaml 5.2.0) | |||
* ] and ] (before OCaml 5.0.0) | |||
* ] (before OCaml 4.06.0) | |||
* ], ], ] and ] (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. | |||
==Code examples== | |||
Snippets of OCaml code are most easily studied by entering them into the "top-level". 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 bytecode and native code programs can be written in a ] style, with preemptive context switching. OCaml threads 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 only. However, an OCaml program can contain several domains. | |||
$ ocaml | |||
Objective Caml version 3.09.0 | |||
==Code examples== | |||
{{one source|date=January 2024}} | |||
# | |||
Snippets of OCaml code are most easily studied by entering them into the ''top-level ]''. This is an interactive OCaml session that prints the inferred 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 | |||
Objective Caml version 3.09.0 | |||
# | |||
</syntaxhighlight> | |||
Code can then be entered at the "#" prompt. For example, to calculate 1+2*3: | 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 ] ]) and gives the result "7". | |||
# 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=== | ===Hello World=== | ||
The following program "hello.ml": | The following program "hello.ml": | ||
<syntaxhighlight lang="OCaml"> | |||
print_endline "Hello world!";; | |||
print_endline "Hello World!" | |||
</syntaxhighlight> | |||
can be compiled |
can be compiled into a bytecode executable: | ||
$ ocamlc hello.ml -o hello | $ ocamlc hello.ml -o hello | ||
or compiled into an optimized native-code executable: | |||
$ ocamlopt hello.ml -o hello | |||
and executed: | and executed: | ||
<syntaxhighlight lang="console"> | |||
$ ./hello | |||
$ ./hello | |||
Hello world! | |||
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> | |||
===Birthday paradox=== | |||
OCaml may be used as a ], as the following script calculates the smallest number of people in a room for whom the probability of completely unique birthdays is less than 50% (the so-called ], where for 1 person the probability is obviously 100%, for 2 it is 364/365, etc.) (answer = 23). | |||
=== Option === | |||
On a ] operating system, save it to a file, ] to ] (<code>chmod 0755 birthday.ml</code>) and run it from the ] (<code>./birthday.ml</code>). | |||
The <code>option</code> type constructor in OCaml, similar to the <code>Maybe</code> type in ], 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 ], 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=== | |||
#!/usr/bin/ocamlrun ocaml | |||
Lists are one of the fundamental datatypes in OCaml. The following code example defines a ] 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 ]'s ] element, though it is far more general. | |||
let year_size = float(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 lang="ocaml"> | |||
===Arbitrary-precision factorial function (libraries)=== | |||
let rec sum integers = (* Keyword rec means 'recursive'. *) | |||
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. | |||
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 ;; | |||
- : int = 15 | |||
</syntaxhighlight> | |||
Another way is to use standard ] that works with lists. | |||
In OCaml, the Num module provides arbitrary-precision arithmetic and can be loaded into a running top-level using: | |||
<syntaxhighlight lang="ocaml"> | |||
# #load "nums.cma";; | |||
let sum integers = | |||
# open Num;; | |||
List.fold_left (fun accumulator x -> accumulator + x) 0 integers;; | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="OCaml"> | |||
# sum ;; | |||
- : int = 15 | |||
</syntaxhighlight> | |||
Since the ] is simply the application of the + operator, this can be shortened to: | |||
The factorial function may then be written using the arbitrary-precision numbers operators =/, */ and -/ : | |||
<syntaxhighlight lang="ocaml"> | |||
# let rec fact n = | |||
let sum integers = | |||
if n =/ Int 0 then Int 1 else n */ fact(n -/ Int 1);; | |||
List.fold_left (+) 0 integers | |||
val fact : Num.num -> Num.num = <fun> | |||
</syntaxhighlight> | |||
Furthermore, one can omit the list argument by making use of a ]: | |||
<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 ] 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 @ @ 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 @ @ 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 ], 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 ] of ]s, with successor (succ) and addition (add). A Church numeral {{OCaml|n}} is a ] 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"}}. | |||
<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 _ = to_string (add (succ two) two) | |||
</syntaxhighlight> | |||
===Arbitrary-precision factorial function (libraries)=== | |||
A variety of libraries are directly accessible from OCaml. For example, OCaml has a built-in library for ]. 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!: | This function can compute much larger factorials, such as 120!: | ||
<syntaxhighlight lang="OCaml"> | |||
# string_of_num (fact (Int 120));; | |||
# string_of_num (fact (Int 120));; | |||
- : string = | |||
- : string = | |||
"6689502913449127057588118054090372586752746333138029810295671352301633 | |||
"6689502913449127057588118054090372586752746333138029810295671352301633 | |||
55724496298936687416527198498130815763789321409055253440858940812185989 | |||
55724496298936687416527198498130815763789321409055253440858940812185989 | |||
8481114389650005964960521256960000000000000000000000000000" | |||
8481114389650005964960521256960000000000000000000000000000" | |||
</syntaxhighlight> | |||
===Triangle (graphics)=== | ===Triangle (graphics)=== | ||
The following program |
The following program renders a rotating triangle in 2D using ]: | ||
<syntaxhighlight lang="OCaml"> | |||
let _ = | |||
let () = | |||
ignore( Glut.init Sys.argv ); | |||
Glut.initDisplayMode ~double_buffer:true (); | ignore (Glut.init Sys.argv); | ||
Glut.initDisplayMode ~double_buffer:true (); | |||
ignore (Glut.createWindow ~title:"OpenGL Demo"); | |||
|
let angle t = 10. *. t *. t in | ||
GlClear.clear ; | let render () = | ||
GlClear.clear ; | |||
GlMat.load_identity (); | |||
GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. (); | |||
GlDraw.begins `triangles; | |||
List.iter GlDraw.vertex2 ; | GlDraw.begins `triangles; | ||
List.iter GlDraw.vertex2 ; | |||
GlDraw.ends (); | |||
Glut.swapBuffers () in | |||
Glut.displayFunc ~cb:render; | 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: | 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: | 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: | and run: | ||
$ ./simple | |||
Far more sophisticated, high-performance 2D and 3D graphical programs |
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 ] of a number ''n'' inputted. It uses ] 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== | ==Derived languages== | ||
===MetaOCaml=== | ===MetaOCaml=== | ||
MetaOCaml<ref name = "Meta"> |
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 ] extension of OCaml enabling incremental compiling of new ] 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 |
As an example: if at compile time it is known that some ] {{OCaml|x -> x^n}} is needed often, but the value of {{OCaml|n}} is known only at runtime, a two-stage power function can be used in MetaOCaml: | ||
<syntaxhighlight lang="OCaml"> | |||
let rec power n x = | |||
|
let rec power n x = | ||
|
if n = 0 | ||
|
then .<1>. | ||
if even n | else | ||
if even n | |||
then sqr (power (n/2) x) | |||
else .<.~x *. .~(power (n - 1) x)>. | |||
</syntaxhighlight> | |||
As soon as |
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>.)>.;; | |||
.<fun x -> .~(power 5 .<x>.)>. | |||
</syntaxhighlight> | |||
The result is: | The result is: | ||
<syntaxhighlight lang="OCaml"> | |||
fun x_1 -> (x_1 * | |||
fun x_1 -> (x_1 * | |||
let y_3 = | |||
let y_2 = (x_1 * 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. | The new function is automatically compiled. | ||
===Other derived languages=== | ===Other derived languages=== | ||
* ] is a ] framework language based on OCaml. | |||
* a .NET language from Microsoft Research that adds concurrency, active patterns (views), nominally typed OOP, operator overloading, arbitrary-sized arrays, easy FFI, quotations, type-safe marshalling and many other features to OCaml. F# is free and runs under Mono as well as .NET. | |||
* ] integrates constructions for developing concurrent and distributed programs. | |||
* adds quotations and run-time code generation via staged compilation to OCaml. | |||
* ] is an alternative OCaml ] and ] for OCaml created at ], which can compile to both native code and JavaScript. | |||
* which facilitate the manipulation of names and binders, | |||
*] which integrates constructions for developing concurrent and distributed programs, | |||
* adding extensional polymorphism to OCaml, thus allowing overloading and type-safe marshalling, | |||
*, a hardware design and verification language, | |||
* provides a synchronization primitive for atomic (transactional) execution of code. | |||
* extends OCaml with features such as XML expressions and regular-expression types. | |||
==Software written in OCaml== | |||
==See also== | |||
* Ahrefs, an SEO software product | |||
*], the language that preceded OCaml | |||
*], a |
* ], a SMT solver. | ||
* ], a static analyzer | |||
*], an OCaml-like language for ] | |||
* ], a social network | |||
*], a different kind of object-oriented extension to ML | |||
* ], a utility for ] the ] of ] programs. | |||
*] an object-oriented extension to ], a different functional language | |||
* ], a ] management system. | |||
* Easycrypt, a toolset for writing computer-aided proofs.<ref>{{Citation |title=EasyCrypt/easycrypt |date=2024-07-05 |url=https://github.com/EasyCrypt/easycrypt |access-date=2024-07-05 |publisher=EasyCrypt}}</ref> | |||
* ], a high-level, multi-paradigm, functional and object-oriented programming language intended for program verification. | |||
* ], a ] for computing ]s. Several C routines have been generated by an OCaml program named {{OCaml|genfft}}. | |||
* The web version of ].<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 ] created at ] that infers and checks ] for ].<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> | |||
* ], a client server Web and mobile development framework | |||
* ], a dedicated system for scientific and engineering computing. | |||
* ], a framework for analyzing C programs. | |||
* ], free and open-source multi-platform genealogy software. | |||
* The ] programming language compiler, created at Facebook, extending ] with static types. | |||
* The ] programming language compiler. | |||
* ], a formal proof assistant. | |||
* Infer, a static analyzer created at Facebook for ], C, ], and ], used to detect bugs in ] and ] apps.<ref>{{cite web|url=https://fbinfer.com/|title=Infer static analyzer|website=Infer}}</ref> | |||
* ], a ] for generating multimedia streams. | |||
* ], a ] programming framework written in pure OCaml. | |||
* ], a ] application based on the ]. | |||
* ], a free and open-source programming language for web development. | |||
* ], a general-purpose, high-level, multi-paradigm, functional and object-oriented programming language. | |||
* The ] compiler was ] in OCaml before becoming ]. | |||
* ], a self-amending smart contract platform using XTZ as a native currency. | |||
* ], a ] program to synchronize files between two directories. | |||
* The reference interpreter for ], a low-level ] intended for execution inside ]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=]|access-date=2021-05-14|via=GitHub}}</ref> | |||
* ] (XCP), a ] ] solution for the ] ]. | |||
== |
==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: | |||
* | |||
* ], which created , an OCaml compiler backend targeting JavaScript.<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> | |||
** | |||
* ], which uses OCaml in ] (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=]|conference=]|year=2010}}</ref> | |||
** | |||
* ], which developed Flow,<ref>{{cite web|url=https://github.com/facebook/flow|title=Flow on GitHub|website=] |year=2023}}</ref> Hack, Infer, Pfff, and ] in OCaml. | |||
* | |||
* ], a ] 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=] Commercial Uses of Functional Programming|year=2016}}</ref><ref>{{cite podcast|title=Signals & Threads|year=2023|publisher=]|url=https://signalsandthreads.com|host=Yaron Minsky}}</ref> | |||
* | |||
* ], which uses OCaml in the desktop editions on ] and ].<ref>{{cite web|url=https://www.docker.com/blog/docker-unikernels-open-source/|title=Improving Docker with Unikernels: Introducing HyperKit, VPNKit and DataKit|author=]|year=2016|publisher=]}}</ref><ref>{{cite web|url=https://github.com/moby/vpnkit|title=VPNKit on GitHub|website=] |year=2023}}</ref> | |||
*, an OCaml compiler for ] | |||
* including Ocaml | |||
* ]+ bindings (LablGL) and ] bindings (LablGTK) | |||
* | |||
* | |||
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 . | |||
===Books=== | |||
* by Xavier Leroy (with Damien Doligez, Jacques Garrigue, Didier Rémy and Jérôme Vouillon). | |||
*''OCaml for Scientists'' by Jon Harrop | |||
* by Emmanuel Chailloux, Pascal Manoury and Bruno Pagano. | |||
* by Jason Hickey. | |||
* by Joshua Smith. | |||
* from the F# home page. | |||
==References== | |||
{{Reflist}} | |||
<references /> | |||
==External links== | |||
] | |||
{{wikibooks|OCaml}} | |||
* {{Official website}} | |||
* | |||
* | |||
* | |||
{{ML programming}} | |||
{{Programming languages}} | |||
{{Authority control}} | |||
] | |||
] | |||
] | |||
] | |||
] | ] | ||
] | ] | ||
] | |||
] | |||
] | |||
] | |||
] | |||
] | |||
] | |||
] | |||
] | |||
] | |||
] | |||
] | |||
] | |||
<!-- Hidden categories below --> | |||
] | |||
] | ] | ||
] | |||
] | |||
] | |||
] | |||
] | |||
] |
Latest revision as of 07:13, 8 January 2025
Programming language Not to be confused with occam (programming language).
Paradigms | Multi-paradigm: functional, imperative, modular, object-oriented |
---|---|
Family | ML: Caml |
Designed by | Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy, Ascánder Suárez |
Developer | Inria |
First appeared | 1996; 29 years ago (1996) |
Stable release | 5.3.0 / 8 January 2025; 2 days ago (8 January 2025) |
Typing discipline | Inferred, static, strong, structural |
Implementation language | OCaml, C |
Platform | IA-32, x86-64, Power, SPARC, ARM 32-64, RISC-V |
OS | Cross-platform: Linux, Unix, macOS, Windows |
License | LGPLv2.1 |
Filename extensions | .ml, .mli |
Website | ocaml |
Influenced by | |
C, Caml, Modula-3, Pascal, Standard ML | |
Influenced | |
ATS, Coq, Elm, F#, F*, Haxe, Opa, Rust, Scala | |
|
OCaml (/oʊˈkæməl/ oh-KAM-əl, 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) together with a composable build system for OCaml (Dune). 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).
History
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. In 2023, the OCaml compiler was recognised with ACM SIGPLAN's Programming Languages Software Award.
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.
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 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
This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources. Find sources: "OCaml" – news · newspapers · books · scholar · JSTOR (January 2024) |
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 Objective Caml version 3.09.0 #
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 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:
$ ./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.
Option
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 ;; - : 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 ;; - : 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 @ @ 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 @ @ 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 < 0.5 then Printf.printf "answer = %d\n" (people+1) else birthday_paradox prob (people+1) ;; birthday_paradox 1.0 1
Church numerals
The following code defines a Church encoding of natural numbers, with successor (succ) and addition (add). A Church numeral n
is a higher-order function that accepts a function f
and a value x
and applies f
to x
exactly n
times. To convert a Church numeral from a functional value to a string, we pass it a function that prepends the string "S"
to its input and the constant string "0"
.
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 _ = to_string (add (succ two) two)
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 = <fun>
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 ; GlMat.load_identity (); GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. (); GlDraw.begins `triangles; List.iter GlDraw.vertex2 ; 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 = <fun> # let add4 = fourtimes inc;; val add4 : int -> int = <fun> # 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 x -> x^n
is needed often, but the value of n
is known only at runtime, a two-stage power function can be used in MetaOCaml:
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)>.
As soon as n
is known at runtime, a specialized and very fast power function can be created:
.<fun x -> .~(power 5 .<x>.)>.
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 native code and JavaScript.
Software written in OCaml
- Ahrefs, an SEO software product
- 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.
- 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
genfft
. - 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.
- Reason / ReScript, a general-purpose, high-level, multi-paradigm, functional and object-oriented programming language.
- 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.
- 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.
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 ocaml.org.
References
- "Modules". Retrieved 22 February 2020.
- Leroy, Xavier (1996). "Objective Caml 1.00". caml-list mailing list.
- https://ocaml.org/releases/5.3.0. Retrieved 9 January 2025.
{{cite web}}
: Missing or empty|title=
(help) - "Influences - The Rust Reference". The Rust Reference. Retrieved 31 December 2023.
- "Jérôme Vouillon". www.irif.fr. Retrieved 14 June 2024.
- "Didier Remy". pauillac.inria.fr. Retrieved 14 June 2024.
- "A History of OCaml". Retrieved 24 December 2016.
- Linux Weekly News.
- "A J Milner - A.M. Turing Award Laureate". amturing.acm.org. Retrieved 6 October 2022.
- ^ Clarkson, Michael; et al. "1.2. OCaml: Functional Programming in OCaml". courses.cs.cornell.edu. Retrieved 6 October 2022.
- ^ "Prologue - Real World OCaml". dev.realworldocaml.org. Retrieved 6 October 2022.
- ^ "A History of OCaml – OCaml". v2.ocaml.org. Retrieved 7 October 2022.
- "Release of OCaml 5.0.0 OCaml Package". OCaml. Retrieved 16 December 2022.
- "Projet Cristal". cristal.inria.fr. Retrieved 7 October 2022.
- "Gallium team - Home". gallium.inria.fr. Retrieved 7 October 2022.
- "Home". cambium.inria.fr. Retrieved 7 October 2022.
- "OCaml compiler governance and membership". 2023.
- "OCaml governance and projects". 2023.
- "ocaml/asmcomp at trunk · ocaml/ocaml · GitHub". GitHub. Retrieved 2 May 2015.
- A domain is a unit of parallelism in OCaml, a domain usually corresponds to a CPU core
- "OCaml - The toplevel system or REPL (ocaml)". ocaml.org. Retrieved 17 May 2021.
- "OCaml - Batch compilation (Ocamlc)".
- "3.7. Options — OCaml Programming: Correct + Efficient + Beautiful". cs3110.github.io. Retrieved 7 October 2022.
- oleg-at-okmij.org. "BER MetaOCaml". okmij.org.
- EasyCrypt/easycrypt, EasyCrypt, 5 July 2024, retrieved 5 July 2024
- "Messenger.com Now 50% Converted to Reason · Reason". reasonml.github.io. Retrieved 27 February 2018.
- "Flow: A Static Type Checker for JavaScript". Flow. Archived from the original on 8 April 2022. Retrieved 10 February 2019.
- "Infer static analyzer". Infer.
- "WebAssembly/spec: WebAssembly specification, reference interpreter, and test suite". World Wide Web Consortium. 5 December 2019. Retrieved 14 May 2021 – via GitHub.
- "Companies using OCaml". OCaml.org. Retrieved 14 May 2021.
- "BuckleScript: The 1.0 release has arrived! | Tech at Bloomberg". Tech at Bloomberg. 8 September 2016. Retrieved 21 May 2017.
- Scott, David; Sharp, Richard; Gazagnaire, Thomas; Madhavapeddy, Anil (2010). Using functional programming within an industrial product group: perspectives and perceptions. International Conference on Functional Programming. Association for Computing Machinery. doi:10.1145/1863543.1863557.
- "Flow on GitHub". GitHub. 2023.
- Yaron Minsky (1 November 2011). "OCaml for the Masses". Retrieved 2 May 2015.
- Yaron Minsky (2016). "Keynote - Observations of a Functional Programmer". ACM Commercial Uses of Functional Programming.
- Yaron Minsky (2023). "Signals & Threads" (Podcast). Jane Street Capital.
- Anil Madhavapeddy (2016). "Improving Docker with Unikernels: Introducing HyperKit, VPNKit and DataKit". Docker, Inc.
- "VPNKit on GitHub". GitHub. 2023.
External links
ML programming | |||
---|---|---|---|
Software | |||
Community |
| ||
Book Category:Family:ML Category:Family:OCaml Category:Software:OCaml |
Programming languages | |
---|---|
- High-level programming languages
- Cross-platform free software
- Extensible syntax programming languages
- Free and open source interpreters
- Functional languages
- Object-oriented programming languages
- ML programming language family
- OCaml programming language family
- OCaml software
- Pattern matching programming languages
- Programming languages created in 1996
- Statically typed programming languages
- Software using the GNU Lesser General Public License