Code Examples

OCaml possesses an interactive system,
called “toploop”, that lets you type OCaml code and have it evaluated
immediately. It is a great way to learn the language and to quickly
experiment with ideas. Below, we demonstrate the use of the toploop to
illustrate basic capabilities of the language.

Some indications for the code below. The prompt at which you type is
“#”. The code must end with “;;” (this is only an indication to the
interactive system that the input has to be evaluated and is not really
part of the OCaml code). The output of the system is displayed in
this color.

Elementary functions

Let us define the square function and the recursive factorial function.
Then, let us apply these functions to sample values. Unlike the majority
of languages, OCaml uses parentheses for grouping but not for the
arguments of a function.

Higher-order functions

There is no restriction on functions, which may thus be passed as
arguments to other functions. Let us define a function sigma that
returns the sum of the results of applying a given function f to each
element of a list:

Pattern matching eases the definition of functions operating on symbolic
data, by giving function definitions and type declarations similar
shapes. Indeed, note the close resemblance between the definition of the
eval function and that of the expression type.