Objective Caml (OCaml) is a general-purpose programming language descended from the ML family, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996. OCaml is an open source project managed and principally maintained by INRIA.
OCaml shares the functional and imperative programming features of ML, but adds object-oriented constructs and has minor syntax differences. Like all descendants of ML, OCaml is compiled, statically typed, strictly evaluated, and uses automatic memory management.
OCaml's toolset includes an interactive toplevel, a bytecode compiler, 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 a successor to Caml Light. The acronym CAML originally stood for Categorical Abstract Machine Language, although OCaml abandons this abstract machine.
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. The type-inferring compiler greatly reduces the need for manual type annotation (for example, the data type of variables and the signature of functions usually do not need to be expressly 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 the need for runtime type and safety checks that burden the performance of dynamically typed languages, while still guaranteeing runtime safety.
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 cautiously stated that "OCaml delivers at least 50% of the performance of a decent C compiler" and benchmarks have shown that this is generally the case [http://shootout.alioth.debian.org/.
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 with C primitives is provided, including language support for efficient numerical arrays in formats compatible with both C and FORTRAN.
The OCaml distribution contains:
The native code compiler is available for many platforms, including Unix, Microsoft Windows, and Apple Mac OS X. Excellent portability is ensured through native code generation support for major architectures: IA32, AMD64, PowerPC, Sparc, IA64, Alpha, HP/PA, MIPS, and StrongARM.
$ 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".
print_endline "Hello world!";;
can be compiled to bytecode:
$ ocamlc hello.ml -o hello
and executed:
$ ./hello Hello world! $
On a
unix-like machine, save it to a file, chmod to
executable (chmod 0755 birthday.ml) and run it
from the command line (./birthday.ml).
#!/usr/bin/ocamlrun ocaml let size = 365 ;; let rec loop p i = let p' = float(size - i) *. p /. float(size) in if p' < 0.5 then Printf.printf "answer = %d\n" (i+1) else loop p' (i+1) ;; loop 1.0 1
# let rec fact n = if n=0 then 1 else n * fact(n-1);;
val fact : int -> int =
The function can be written equivalently using pattern matching:
# let rec fact = function | 0 -> 1 | n -> n * fact(n-1);;
This latter form is the mathematical definition of factorial as a recurrence relation.
Note that the compiler inferred the type of this function to be "int -> int", meaning that this function maps ints onto ints. For example, 12! is:
# fact 12;; - : int = 479001600
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 numbers 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"
# let d delta f x =
(f (x +. delta) -. f (x -. delta)) /. (2. *. delta);;
val d : float -> (float -> float) -> float -> float =
This function requires a small value "delta". A good choice for delta is the square root of the machine epsilon.
The type of the function "d" indicates that it maps a "float" onto another function with the type "(float -> float) -> float -> float". This allows us to partially apply arguments. This functional style is known as currying. In this case, it is useful to partially apply the first argument "delta" to "d", to obtain a more specialised function:
# let d = d (sqrt epsilon_float);;
val d : (float -> float) -> float -> float =
Note that the inferred type indicates that the replacement "d" is expecting a function with the type "float -> float" as its first argument. We can compute a numerical approximation to the derivative of x^3-x-1 at x=3 with:
# d (fun x -> x *. x *. x -. x -. 1.) 3.;; - : float = 26.
The correct answer is f'(x) = 3x^2-1 => f'(3) = 27-1 = 26.
The function "d" is called a "higher-order function" because it accepts another function ("f") as an argument.
The concepts of curried and higher-order functions are clearly useful in mathematical programs. In fact, these concepts are equally applicable to most other forms of programming and can be used to factor code much more aggressively, resulting in shorter programs and fewer bugs.
# let haar l =
let rec aux l s d = match l, s, d with
[, d -> s :: d
| s, d -> aux s [ d
| h1 :: h2 :: t, s, d -> aux t (h1 + h2 :: s) (h1 - h2 :: d)
| _ -> invalid_arg "haar" in
aux l [;;
val haar : int list -> int list =
For example:
# haar 2; 3; 4; -4; -3; -2; -1;; - : int list = 20; 4; 4; -1; -1; -1; -1
Pattern matching is an incredibly useful construct that allows complicated transformations to be represented clearly and succinctly. Moreover, the OCaml compiler turns pattern matches into very efficient code, resulting in programs that are not only much shorter but also much faster.
let _ = ignore( Glut.init Sys.argv ); Glut.initDisplayMode ~double_buffer:true (); ignore (Glut.createWindow ~title:"OpenGL Demo"); let render () = GlClear.clear `color ; GlMat.rotate ~angle:(Sys.time() *. 0.01) ~z:1. (); GlDraw.begins `triangles; List.iter GlDraw.vertex2 -1.; 0., 1.; 1., -1.; GlDraw.ends (); Glut.swapBuffers () in 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 unix.cma lablglut.cma lablgl.cma simple.ml -o simple
or to nativecode with:
$ ocamlopt -I +lablGL unix.cmxa lablglut.cmxa lablgl.cmxa simple.ml -o simple
and run:
$ ./simple
Far more sophisticated, high-performance 2D and 3D graphical programs are easily developed in OCaml. Thanks to the use of OpenGL, the resulting programs are not only succinct and efficient but also cross-platform, compiling without any changes on all major platforms.
OCaml is also used to teach Computer Science (mainly algorithms and complexity theories) in the French Classes Préparatoires (Preparation Courses), for students studying Computer Science (almost replacing Pascal). At the University of Illinois at Urbana-Champaign, OCaml is often used to teach design, parsing, and interpretation of programming languages in the Department of Computer Science's CS421 ("Programming Languages and Compilers") course.
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:
.
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.
ML programming language family | Functional languages | Object-oriented programming languages
Objective CAML | Ocaml | Objective Caml | Objective Caml | OCaml | OCaml | Ocaml | OCaml | OCaml | Ocaml | Ocaml