Previous Contents Next
Chapter 1 The core language

This part of the manual is a tutorial introduction to the Objective Caml language. A good familiarity with programming in a conventional languages (say, Pascal or C) is assumed, but no prior exposure to functional languages is required. The present chapter introduces the core language. Chapter 3 deals with the object-oriented features, and chapter 2 with the module system.

1.1 Basics

For this overview of Caml, we use the interactive system, which is started by running ocaml from the Unix shell, or by launching the OCamlwin.exe application under Windows. This tutorial is presented as the transcript of a session with the interactive system: lines starting with # represent user input; the system responses are printed below, without a leading #.

Under the interactive system, the user types Caml phrases, terminated by ;;, in response to the # prompt, and the system compiles them on the fly, executes them, and prints the outcome of evaluation. Phrases are either simple expressions, or let definitions of identifiers (either values or functions).
#1+2*3;;
- : int = 7
 
#let pi = 4.0 *. atan 1.0;;
val pi : float = 3.14159265359
 
#let square x = x *. x;;
val square : float -> float = <fun>
 
#square(sin pi) +. square(cos pi);;
- : float = 1
The Caml system computes both the value and the type for each phrase. Even function parameters need no explicit type declaration: the system infers their types from their usage in the function. Notice also that integers and floating-point numbers are distinct types, with distinct operators: + and * operate on integers, but +. and *. operate on floats.
#1.0 * 2;;
This expression has type float but is here used with type int
Recursive functions are defined with the let rec binding:
#let rec fib n =
   if n < 2 then 1 else fib(n-1) + fib(n-2);;
val fib : int -> int = <fun>
 
#fib 10;;
- : int = 89
1.2 Data types