|This article relies too much on references to primary sources. (May 2015) (Learn how and when to remove this template message)|
|Paradigm||multi-paradigm: imperative, functional, object-oriented|
|Stable release||4.03.0 / April 25, 2016|
|Typing discipline||static, strong, inferred|
|Implementation language||OCaml and C|
|License||Q Public License (compiler)
|Filename extensions||.ml, .mli|
|F#, JoCaml, MetaOCaml, OcamlP3l|
|Caml Light, Cool, Standard ML|
|ATS, Elm, F#, F*, Haxe, Opa, Rust, Scala|
OCaml (// oh-KAM-əl), originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy, Ascánder Suárez and others in 1996. A member of the ML language family, OCaml extends the core Caml language with object-oriented constructs.
OCaml's toolset includes an interactive top-level interpreter, a bytecode compiler, a reversible debugger, a package manager (OPAM), and an optimizing native code compiler. It has a large standard library that makes it useful for many of the same applications as Python or Perl, as well as robust modular and object-oriented programming constructs that make it applicable for large-scale software engineering. OCaml is the successor to Caml Light. The acronym "CAML" originally stood for Categorical Abstract Machine Language, although OCaml abandons this abstract machine.
- 1 Philosophy
- 2 Features
- 3 Development environment
- 4 Code examples
- 5 Derived languages
- 6 Software written in OCaml
- 7 Commercial users of OCaml
- 8 See also
- 9 References
- 10 External links
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. This means the program author is not required to be overly familiar with the pure functional language paradigm in order to use OCaml.
OCaml's static type system can help eliminate 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 data type of variables and the signature of functions usually do not need to be explicitly declared, as they do in Java). Nonetheless, effective use of OCaml's type system can require some sophistication on the part of the programmer.
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 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 certain 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. In addition to standard loop, register, and instruction optimizations, OCaml's optimizing compiler employs static program analysis techniques 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", but 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 exploits the immutability of sets in order to reuse parts of input sets in the output (persistence).
OCaml features: a static type system, type inference, parametric polymorphism, tail recursion, pattern matching, first class lexical closures, functors (parametric modules), exception handling, and incremental generational automatic garbage collection.
OCaml is particularly 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 the creation of libraries of OCaml functions that can be linked to a "main" program in C, so that one could distribute an OCaml library to C programmers who have no knowledge nor installation of OCaml.
The OCaml distribution contains:
- An extensible parser and macro language named Camlp4, which permits the syntax of OCaml to be extended or even replaced
- Lexer and parser tools called ocamllex and ocamlyacc
- Debugger that supports stepping backwards to investigate errors
- Documentation generator
- Profiler — for measuring performance
- Numerous general-purpose libraries
The native code compiler is available for many platforms, including Unix, Microsoft Windows, and Apple Mac OS X. Portability is achieved through native code generation support for major architectures: IA-32, AMD64, Power, SPARC, ARM, and ARM64.
OCaml bytecode and native code programs can be written in a multithreaded style, with preemptive context switching. However, because the garbage collector of the INRIA OCaml system (which is the only currently available full implementation of the language) is not designed for concurrency, symmetric multiprocessing is not supported. OCaml threads in the same process execute by time sharing only. There are however several libraries for distributed computing such as Functory and ocamlnet/Plasma.
Since 2011, a lot of new tools and libraries have been contributed to the OCaml development environment:
- OPAM, the OCaml Package Manager, developed by OCamlPro, is now an easy way to install OCaml and many of its tools and libraries
- Optimizing compilers for OCaml:
- ocamlcc is a compiler from OCaml to C, to complement the native code compiler for unsupported platforms.
- OCamlJava, developed by Inria, is a compiler from OCaml to the JVM.
- OCaPic, developed by Lip6, is a compiler from OCaml to PIC microcontroller.
- Web sites:
- Development Tools
- TypeRex is a set of open-source tools and libraries for OCaml, developed and maintained by OCamlPro.
- Merlin is an auto-completion tool for editing OCaml code in Emacs and Vim.
|This section does not cite any sources. (May 2013) (Learn how and when to remove this template message)|
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 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
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
$ ./hello Hello World! $
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 xs. (Notice the keyword rec). The function recursively iterates over a given list and provides a sum of integer elements. The match statement has similarities to C's switch element, though it is much more general.
let rec sum xs = match xs with |  -> 0 (* yield 0 if xs has the form  *) | x :: xs' -> x + sum xs';; (* recursive call if xs has the form x::xs' for suitable x and xs' *)
# sum [1;2;3;4;5];; - : int = 15
Another way is to use standard fold function that works with lists.
let sum xs = List.fold_left (fun acc each_xs -> acc + each_xs) 0 xs;;
# sum [1;2;3;4;5];; - : int = 15
OCaml lends itself to the concise expression of 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 @ [pivot] @ qsort right
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 so-called birthday paradox, 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
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
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
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 provides arbitrary-precision arithmetic and can be loaded into a running top-level using:
# #load "nums.cma";; # 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"
The cumbersome syntax for Num operations can be alleviated thanks to the camlp4 syntax extension called Delimited overloading:
# #require "pa_do.num";; # let rec fact n = Num.(if n = 0 then 1 else n * fact(n-1));; val fact : Num.num -> Num.num = <fun> # fact Num.(120);; - : Num.num = <num 668950291344912705758811805409037258675274633313802981029567 135230163355724496298936687416527198498130815763789321409055253440 8589408121859898481114389650005964960521256960000000000000000000000000000>
The following program "simple.ml" 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
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.
The following code calculates the Fibonacci sequence of a number n inputted. It uses tail recursion and pattern matching.
let rec fib_aux n a b = match n with | 0 -> a | _ -> fib_aux (n - 1) b (a+b) let fib n = fib_aux n 0 1
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
MetaOCaml is a multi-stage programming extension of OCaml enabling incremental compiling of new machine code during runtime. Under certain circumstances, significant speedups are possible using multi-stage programming, because more detailed information about the data to process is available at runtime than at the regular compile time, so the incremental compiler can optimize away many cases of condition checking etc.
As an example: if at compile time it is known that a certain power function
x -> x^n is needed very frequently, but the value of
n is known only at runtime, you can use a two-stage power function 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 you know
n at runtime, you can create a specialized and very fast power function:
.<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
- AtomCaml provides a synchronization primitive for atomic (transactional) execution of code.
- Emily is a subset of OCaml that uses a design rule verifier to enforce object-capability [security] principles.
- F# is a Microsoft .NET language based on OCaml.
- Fresh OCaml facilitates the manipulation of names and binders.
- GCaml adds extensional polymorphism to OCaml, thus allowing overloading and type-safe marshalling.
- JoCaml integrates constructions for developing concurrent and distributed programs.
- OCamlDuce extends OCaml with features such as XML expressions and regular-expression types.
- OCamlP3l is a parallel programming system based on OCaml and the P3L language
Software written in OCaml
- MirageOS, a unikernel programming framework written in pure OCaml
- Hack, a new programming language created by Facebook, which is an extension of PHP with static typing. Hack's compiler is written in OCaml.
- Infer, a static analyzer for Java, C and Objective-C created at Facebook, which is used to detect bugs in iOS and Android apps.
- 0Install, a multi-platform package manager
- XCP, The Xen Cloud Platform, an open source toolstack for the Xen Virtual Machine Hypervisor
- FFTW, a software library for computing discrete Fourier transforms. Several C routines have been generated by an OCaml program named
- Unison, a file synchronization program to synchronize files between two directories
- Mldonkey, a peer to peer client based on the EDonkey network
- GeneWeb, free open source multi-platform genealogy software
- The Haxe compiler, a free open source compiler for the Haxe programming language
- Frama-C, a framework for C programs analysis
- Coq, a formal proof management system
- Ocsigen, web development framework
- Opa, an open source programming language for web development
- WebAssembly, an experimental, low-level scripting language for in-browser client-side scripting. Its WIP interpreter and parser in the specification repo on Github is written mostly in OCaml.
Commercial users of OCaml
There are several dozen companies that use OCaml to some degree. Notable examples include:
- Jane Street Capital, a proprietary trading firm, which adopted OCaml as its preferred language in its early days
- Citrix Systems, which uses OCaml in XenServer, a component of one of its products
- Facebook, which developed Hack, Flow, Infer and Pfff
- Caml and Caml Light, languages from which OCaml evolved
- Standard ML, another popular dialect of ML
- Extensible ML, another object-oriented dialect of ML
- O'Haskell, an object-oriented extension to the functional language Haskell
- Reason, a new interface to OCaml initiated by Facebook
- "A History of OCaml". Retrieved 2 May 2015.
- Linux Weekly News.
- "ocaml/asmcomp at trunk · ocaml/ocaml · GitHub". GitHub. Retrieved 2 May 2015.
- "Archives of the Caml mailing list > Message from Xavier Leroy". Retrieved 2 May 2015.
- BER MetaOCaml
- "Companies using OCaml". OCaml.org. Retrieved 17 August 2014.
- Yaron Minsky (1 November 2011). "OCaml for the Masses". Retrieved 2 May 2015.
|Wikibooks has a book on the topic of: OCaml|