OCaml Session Basics
Value declarations
A let binding gives a name to a value:
let pi = 3.14159265358979
(* val pi : float = 3.14159265358979 *)
This is a value declaration. The name pi is an identifier. OCaml echoes the name, type (float), and value. Unlike variables in imperative languages, pi cannot be reassigned — its meaning persists even if a new let pi = ... is issued later.
Function declarations
A function encapsulates a computation so the formula does not need to be remembered:
let area r = pi *. r *. r
(* val area : float -> float = <fun> *)
area takes a float r and returns a float. The arrow -> in the type indicates a function. Calling a function does not require brackets:
area 2.0
(* - : float = 12.56637061435916 *)
Operators
Multiplication of floats uses *. (not *, which is for integers). This is an infix operator — written between its two operands. Integer multiplication uses *, integer addition uses +, float addition uses +..
Conditional expressions
OCaml uses if-then-else expressions, due to John McCarthy:
if true then x else y = x
if false then x else y = y
Evaluation: OCaml first evaluates the condition (of type bool). If the result is true, it evaluates the then branch; if false, the else branch. Crucially, only one branch is evaluated. If both were evaluated, recursive functions would run forever.
The condition is an expression of type bool, whose two values are true and false.
Relational operators
Tests between values use standard operators:
| Operator | Meaning |
|---|---|
= | Equality |
<> | Inequality |
< | Less than |
<= | Less than or equal |
> | Greater than |
>= | Greater than or equal |
Equality testing with = is allowed provided both operands have the same type and equality is defined for that type.
Boolean operators
Boolean expressions can be combined:
| Operator | Meaning |
|---|---|
not | Negation |
&& | Conjunction (and) |
|| | Disjunction (or) |
New properties can be declared as functions:
let even n = n mod 2 = 0
(* val even : int -> bool = <fun> *)
Here mod computes the remainder of integer division.