OCaml (Objective Caml)

From Bauman National Library
This page was last modified on 1 June 2016, at 17:01.
Developer INRIA
First appeared 1996
Stable release 4.03.0 / April 25 2016
Typing discipline strong, static inferred
License Q Public License
Website http://ocaml.org
F#, JoCaml, MetaOCaml, OcamlP3l
Influenced by
Standard ML, Caml Light

OCaml (Objective Caml) - object-oriented language for functional programming, which has been designed with the safety and reliability of performance programs. The language supports functional, imperative and object-oriented programming paradigm. The most common in practice dialect of ML language. OCaml's toolset includes an interactive top level interpreter, a bytecode compiler, and an optimizing native code compiler, comparable in efficiency with Java and only slightly inferior in performance C and C++. Language use automatic garbage collector, and most of the types of data supplied to the frame, which means to prevent buffer overflows at runtime. In addition, static typing and compile-time checking makes impossible some other error classes, such as casting errors, due to the lack of automatic type conversions. Moreover, the code can be verified formally. There is evidence of the utility of automatic sample code correctness, superior to most programming languages. OCaml as well as other dialects of ML language, used for research problems and verification problems, where base code is written in some programming language and then formally verified and analyzed by program on OCaml language.


Among the features of the language can be identified:

  1. The static type checking
  2. Parametric polymorphism
  3. Algebraic data types and pattern matching
  4. Support for programming with immutable data structures
  5. Automatic garbage collection
  6. An efficient compiler to native code without using JIT-compile


Model caclulations of OCaml as a functional programming language is built on three main structures lambda calculus: variables, certain of functions and functions of the application to the arguments. Variable - id value is associated with a certain value. Variale names begin with a lowcase letter, or an underscore. Building is performed using the keyword "let".

 let count = 0;;
 let size = 5;;

The variables are scoped. Variable, defined in a module, can be used after definition in this module. Variable binding can be carried out in the scope of "let-in":

 let area radius = let pi = 3.14 in radius *. radius *. pi ;;


Functions can be defined using the keyword "function". The expression for the function is as follows:

 function x -> x + 1

In this case, the function is anonymous, and it can be used as parameter for other functions or can be applied to some argument:

 (function x -> x + 1) 5

This function has type int -> int. Function can take several arguments:

 function (x, y) -> x - y

In this function types are int*int -> int, i.e function takes 2 parameters of int type and returns int. There is another approach the representation of functions of several arguments - conversion of function with N parameters to N functions with 1 parameter.

 function x -> function y -> x * y

Named functions are available by connecting a variable with a function. Defining a named function as frequent operation, which has a separate support syntax:

 let prod = function x -> function y -> x * y ;;
 val prod : int -> int -> int = <fun>


Ocaml language has several primitive types: numerinc types, symbolic, symbolic strings, boolean.

  1. Numeric type represents numbers from the interval [-230, 230-1] and [-262, 262-1] for 32 and 64-bit architectures respectively. In released results of the allowable range case no error occurs, the result is calculated by the unit interval limits.
  2. Floating number consists of 53-bit mantissa and order in the interval [−1022, 1023]. In operations, numbers with floating point should not be confused with integers. In addition, operations on floating point numbers are syntax different from integer operations: +., -., *., /.. Also included the operation of power: **. For casing integer numbers to numbers with floating point and back "float_of_int" and "int_of_float" functions are available.
  3. Symbolic type - char - defined in interval from 0 to 255 (first 128 match with ASCII code). String type - string - sequence of symbols.
  4. Boolean type has 2 available values: "true" and "false". Operations on boolean type: unary not, binary: && (and), || (or). Boolean values are obtained by comparing: = (structural equations), == (identity), <> (denial of structural equalities), != (denial of identity), <, >, <=, >=. For primitive types except for strings and floating-point structural equality and identity match, for others are considered identity, located at the same address in memory, and the structural comparison values are checked by components.

Objects in OCaml


OCaml is object-oriented language. The class "point" below defines one instance variable x and two methods "get_x" and "move". The initial value of the instance variable is "init_x". The variable x is declared mutable, so the method "move" can change its value.

 class point init_x=
       val mutable x = init_x
       method get_x = x
       method move d = x <- x + d

Creation of a new instance of the point class looks like:

 let p = new point 5;;

Simbol # used to call a method.

 p#move 3


Illustration of inheritance by defining a class of colored points (colored_point) that inherits from the class of points is shown below. This class has all instance variables and all methods of class point, plus a new instance variable c and a new method color.

 class colored_point x (c : string) =
       inherit point x
       val c = c
       method color = c
 let p’ = new colored_point 5 "red";;

A point and a colored point have incompatible types, since a point has no method "color". However, the function get_x below is a generic function applying method get_x to any object p that has this method.


Let-bindings within class definitions are evaluated before the object is constructed. It is also possible to evaluate an expression immediately after the object has been built. Such code is written as an anonymous hidden method called an initializer. Therefore, it can access self and the instance variables.

 class printable_point x_init =
    let origin = (x_init / 10) * 10 in
    object (self)
       val mutable x = origin
       method get_x = x
       method move d = x <- x + d
       method print = print_int self#get_x
       initializer print_string "new point at "; self#print; print_newline()

In this example "origin" is a hidden initializer.

Multiple inheritance

Multiple inheritance is allowed. Only the last definition of a method is kept: the redefinition in a subclass of a method that was visible in the parent class overrides the definition in the parent class. Below, "super" is bound to the ancestor "printable_point". The name "super" is a pseudo value identifier that can only be used to invoke a super-class method, as in super#print.

 class printable_colored_point y c =
    object (self)
       val c = c
       method color = c
       inherit printable_point y as super
       method print =
          print_string "(";
          print_string ", ";
          print_string (self#color);
          print_string ")"

Program examples


There are "for" and "while" cyples in OCaml.

 for <start value> to <end value> do

Unlike other languages, in the language of OCaml cycle parameter takes on the last iteration of a value equal to the final value. For example:

 for i = 0 to 5 do 
     Printf.printf "%d" i

В результате получится:


The syntax of the while loop is shown below:

 while <condition> do

As a condition, you can specify any expression that accepts a boolean value. For example:

 let i = 0;;
 while i < 5 do


To start the OCaml language interpreter type the following command in command prompt:


Code can then be entered at the prompt. The following program prints message on the screen:

 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:



  1. OCaml for the Masses
  2. OCaml official site
  3. Xavier Leroy, Documentation and manual
  4. OCaml