Names for values, not boxes
In OCaml, almost everything is an expression: something with a value and a type. An if is an expression; a match is an expression; even a sequence of print statements is an expression, whose value is (). And a name is not a box you put things in and take them out of again: let x = 5 binds the name x to the value 5, and it stays bound to 5 for as long as it is in scope.
That may sound restrictive, but it is what makes programs easy to reason about: when you see x in a line, you can find its meaning in exactly one place above. When you need a different value, you bind a new name (or, as you will see, the same name again, shadowing the old one). The occasional genuinely mutable variable exists too; it has its own type, ref, and lesson 6 covers it.
This lesson builds the everyday vocabulary: values and operators, let-bindings, and above all functions, the main tool of the language.
Types, bindings and functions
| Type | Example values | Operators and functions |
|---|---|---|
int | 42, -7, 1_000_000, 0xff | + - * / mod, abs, max_int |
float | 3.14, 2., 1e-9 | +. -. *. /. **, sqrt, Float.round |
bool | true, false | && || not |
char | 'a', '\n' | Char.code, Char.uppercase_ascii |
string | "Accra" | ^ (concatenation), String.length, s.[i] |
unit | () | the value of expressions run for their effects |
int * string | (3, "three") | tuples of any size; fst, snd for pairs |
Comparison works on values of any type, structurally: = and <> for equality and inequality, <, <=, >, >=, and compare, which returns a negative number, zero or a positive number.
Definition— let-binding and scope
let name = expr at the top of a file binds name for the rest of the file. let name = expr1 in expr2 binds name only inside expr2. Binding a name that already exists shadows it: the new binding hides the old one from then on, and nothing is modified.
Definition— Function
let f x y = body defines a function of two arguments; fun x y -> body is the same function without a name. Functions are curried: f takes x and returns a function that takes y. Its type is written t1 -> t2 -> t3, which means t1 -> (t2 -> t3). Applying it to fewer arguments than it takes, partial application, gives a new function.
Definition— Labelled and optional arguments
An argument written ~name is labelled: callers pass it as ~name:value, in any order. An argument written ?(name = default) is optional: callers may omit it. A function with optional arguments usually ends with a positional argument, often (), so the compiler knows when the call is complete.
Definition— Polymorphic type
A type containing type variables such as 'a works for any type: fun x -> x has type 'a -> 'a. OCaml infers the most general type of every definition.
Values, functions and recursion
Values and operators
let () =
(* Integers: / and mod truncate towards zero. *)
Printf.printf "%d %d %d %d\n" (17 / 5) (17 mod 5) (-17 / 5) (-17 mod 5);
(* Floats have their own operators, and ** for powers. *)
Printf.printf "%f %.3f %g\n" (17. /. 5.) (2. ** 0.5) (0.1 +. 0.2);
(* No implicit conversions: say what you mean. *)
let items = 7 in
let total = 52.5 in
Printf.printf "average %.2f, rounded %d\n" (total /. float_of_int items)
(int_of_float (Float.round (total /. float_of_int items)));
(* Strings and characters. *)
let city = "Valparaíso" in
Printf.printf "%s has %d bytes; first char %c; upper %s\n" city
(String.length city) city.[0] (String.uppercase_ascii "lagos");
print_endline ("con" ^ "cat" ^ "enation");
(* Booleans and structural comparison, which works on any type. *)
Printf.printf "%b %b %b %d\n" (3 < 5 && not (2 = 3)) ("apple" < "banana")
((1, "b") > (1, "a")) (compare [ 1; 2 ] [ 1; 3 ])3 2 -3 -2
3.400000 1.414 0.3
average 7.50, rounded 8
Valparaíso has 11 bytes; first char V; upper LAGOS
concatenation
true true true -1Points worth remembering:
- Integer
/andmodtruncate towards zero, as in C and Java, so-17 mod 5is-2. Negative literals passed as arguments need parentheses:abs (-3). %fprints six decimals,%.3fthree, and%gchooses a short form. The0.3for0.1 +. 0.2is the formatting rounding the usual floating-point error away; the value itself is still not exactly 0.3.- Conversions are always explicit:
float_of_int,int_of_float(which truncates),Float.round,string_of_int,int_of_string. - A
stringis a sequence of bytes. "Valparaíso" has ten letters but eleven bytes, because í takes two bytes in UTF-8.String.lengthcounts bytes, andcity.[0]is the first byte. Most programs simply pass UTF-8 text through; when you need to count or slice by character, the standard library has UTF-8 decoding functions and libraries such asuutfgo further. - Comparison is structural: it looks inside tuples, lists and strings, comparing element by element.
compare [1; 2] [1; 3]is negative because 2 is less than 3.
Functions, partial application and pipelines
(* Every function takes one argument at a time. *)
let add_percent pct price = price +. (price *. pct /. 100.)
let with_vat = add_percent 16. (* partial application: a new function *)
(* Labelled and optional arguments. *)
let greet ?(greeting = "Hello") ~name () = Printf.sprintf "%s, %s!" greeting name
let () =
Printf.printf "%.2f %.2f\n" (with_vat 80.) (add_percent 10. 35.);
print_endline (greet ~name:"Zainab" ());
print_endline (greet ~greeting:"Salaam" ~name:"Omar" ());
print_endline (greet () ~name:"Kenji");
(* Anonymous functions, and the pipeline operator |> *)
let squares = List.map (fun x -> x * x) [ 1; 2; 3; 4 ] in
List.iter (fun n -> Printf.printf "%d " n) squares;
print_newline ();
[ 1; 2; 3; 4; 5; 6; 7; 8; 9; 10 ]
|> List.filter (fun x -> x mod 2 = 1)
|> List.map (fun x -> x * x)
|> List.fold_left ( + ) 0
|> Printf.printf "sum of odd squares: %d\n";
let shout = Fun.compose String.uppercase_ascii String.trim in
print_endline (shout " quiet please ")92.80 38.50
Hello, Zainab!
Salaam, Omar!
Hello, Kenji!
1 4 9 16
sum of odd squares: 165
QUIET PLEASEadd_percent has type float -> float -> float. Because the rate comes first, add_percent 16. is a useful function on its own, and we name it with_vat. OCaml programmers order parameters with partial application in mind: the most "configuration-like" first, the data last.
greet shows labels at work. ~name must be given by name, which makes calls self-documenting and lets arguments come in any order (the last call passes () first). ?(greeting = "Hello") is optional, with a default. The final () matters: without it, OCaml could not tell whether greet ~name:"Kenji" is a complete call or a partial application still waiting for the optional argument.
The pipeline operator x |> f means f x. Chaining it reads top to bottom, like a recipe: take the numbers, keep the odd ones, square them, add them up, print the result. ( + ) in parentheses is the addition operator used as an ordinary two-argument function. Fun.compose f g (available since OCaml 5.2) is the function that applies g and then f.
Recursion
(* Recursion with an accumulator: a tail call, so it runs in constant stack. *)
let collatz_steps n =
let rec go steps n =
if n = 1 then steps
else if n mod 2 = 0 then go (steps + 1) (n / 2)
else go (steps + 1) ((3 * n) + 1)
in
go 0 n
(* Mutually recursive functions are defined together with let rec ... and *)
let rec is_even n = n = 0 || is_odd (n - 1)
and is_odd n = n <> 0 && is_even (n - 1)
(* if is an expression, so both branches must have the same type. *)
let describe n =
let size = if n < 10 then "small" else if n < 100 then "medium" else "large" in
let parity = if is_even n then "even" else "odd" in
Printf.sprintf "%d is %s and %s" n size parity
let () =
List.iter (fun n -> Printf.printf "%d -> %d steps\n" n (collatz_steps n)) [ 6; 7; 27 ];
List.iter (fun n -> print_endline (describe n)) [ 7; 42; 1000 ];
(* Shadowing: a new x hides the old one; nothing is modified. *)
let x = 10 in
let x = x * 2 in
Printf.printf "x = %d\n" x6 -> 8 steps
7 -> 16 steps
27 -> 111 steps
7 is small and odd
42 is medium and even
1000 is large and even
x = 20collatz_steps hides a recursive helper, conventionally named go or loop, inside a let ... in. The helper carries the count so far as an extra argument, an accumulator. Its recursive calls are tail calls, the last thing the function does, and OCaml guarantees that tail calls do not grow the stack: go runs as a loop, however many steps it takes. A non-tail-recursive function on a very long input can overflow the stack, which is why the accumulator style matters in OCaml in a way it does not in lazy languages.
is_even and is_odd call each other, so they are defined together with let rec ... and .... (They are a teaching example; n mod 2 = 0 is the sensible way to test evenness.) Note that || and && evaluate their right side only when needed, which is what stops the recursion.
How OCaml infers types
OCaml's type checker reads a definition and collects clues. Ask the toplevel about a few:
# let add x y = x + y;;
val add : int -> int -> int = <fun>
# add 3;;
- : int -> int = <fun>
# let pair x y = (x, y);;
val pair : 'a -> 'b -> 'a * 'b = <fun>
# ( |> );;
- : 'a -> ('a -> 'b) -> 'b = <fun>
# let greet ?(greeting = "Hello") ~name () = greeting ^ ", " ^ name;;
val greet : ?greeting:string -> name:string -> unit -> string = <fun>In add, + works only on ints, so x, y and the result are ints. In pair, nothing constrains x or y, so their types stay as variables 'a and 'b: the function is polymorphic. The type of |> explains the operator completely: give it an 'a and a function from 'a to 'b, and you get a 'b. Labels and optional arguments appear in types too, so they are checked like everything else.
This is the Hindley–Milner type inference that OCaml inherited from ML. It is the reason for the separate float operators: because + means only integer addition, every expression has exactly one most general type, found without a single annotation. You may annotate, with (x : int) or let f (x : float) : string = ..., and professionals do so in interface files (lesson 5) and wherever it helps a reader, but the compiler does not need it.
How experienced OCaml programmers write functions
A few conventions you will see in almost every OCaml codebase, and the reasons behind them:
- Names. Values, functions and types are written in
snake_case(add_percent,collatz_steps); modules and constructors start with a capital letter (Printf,Some). A trailing apostrophe is allowed in names (x'), handy for "the next version of x". - Argument order for pipelines. Put the data a function transforms last, so that
xs |> List.filter keep |> List.map freads naturally. The standard library follows this rule almost everywhere. - Labels when arguments could be confused. If a function takes two arguments of the same type, such as
String.sub s start lenor a transfer from one account to another, labels (~src,~dst) make calls self-documenting and let the compiler catch swapped arguments. Jane Street's Core library labels arguments far more than the standard library does. - Destructuring with
let. A tuple can be taken apart directly:let (quotient, remainder) = (17 / 5, 17 mod 5) in .... The parentheses are optional, and the same works for records, as the next lessons show. - Defining operators. Any sequence of symbol characters can be defined as an operator:
let ( +% ) a b = (a + b) mod 7defines addition modulo 7, used as5 +% 4. Libraries use this sparingly, usually inside a module you open locally, so the meaning stays visible. Printf.sprintfover long chains of^. Formatting with a checked format string is easier to read and to change than gluing many pieces together.- Small functions, inferred types, but documented interfaces. Inside a file, programmers rarely annotate; the type checker and the editor (which shows every inferred type on hover) do that work. At module boundaries, types are written out in interface files, as lesson 5 explains.
None of this is enforced by the compiler, but following it makes your code look like everyone else's, which is most of what "idiomatic" means.
Common misconceptions
Misconception
"= and == are the same, as in many languages." In OCaml, = is structural equality (same contents) and == is physical equality (the very same object in memory). "abc" = "abc" is true, but two separately built strings need not be ==. Use = (and <> for "not equal") unless you specifically mean identity; the physical inequality != is a trap for programmers coming from C.
Misconception
"let x = 5 in x = 6 sets x to 6." After in, x = 6 is a comparison, which here is false. There is no assignment to let-bound names. To compute a new value, bind a new name, or shadow the old one with let x = 6 in ....
Misconception
"; ends a statement, like in C." A single ; separates two expressions to be evaluated in sequence; the first should be unit. A trailing ; before in or at the end of a function is a common source of confusing syntax errors. The double ;; is only for the toplevel.
Misconception
"let f (x, y) = ... is how you write a two-argument function." That defines a function of one argument, a pair, which you must call as f (3, 4). It works, and occasionally a tuple is the natural input, but it gives up partial application and labels. The idiomatic two-argument function is curried: let f x y = ..., called as f 3 4. Mixing the two styles is a common source of type errors for programmers coming from C-like languages.
Misconception
"f -1 passes minus one to f." It is parsed as f - 1, a subtraction, and the compiler complains that f is not an int. Write f (-1), and for floats f (-1.) or f (-. x).
Exercises
1. Expressions, types and functions
Warm-upComputationalWhat does this program print?
let () = Printf.printf "%d\n" ((-7 / 2) + (7 mod -3))
2. Expressions, types and functions
CoreComputationalWhat does this program print?
let scale ~factor x = x * factor
let () =
let triple = scale ~factor:3 in
Printf.printf "%d %d\n" (triple 5) (scale 2 ~factor:10)
3. Expressions, types and functions
CoreComputationalWhat does this program print?
let () =
[ 3; 8; 1; 6 ]
|> List.map (fun x -> x * 2)
|> List.filter (fun x -> x > 5)
|> List.length
|> Printf.printf "%d\n"
4. Expressions, types and functions
CoreHumanWhat type does OCaml infer for fun f x -> f (f x)?
5. Expressions, types and functions
StretchComputationalWhat does this program print?
let () =
let x = 3 in
let f y = x + y in
let x = 100 in
Printf.printf "%d\n" (f 1 + x)
6. Expressions, types and functions
Warm-upHumanYou want to check whether two lists have the same elements in the same order. Which operator do you use?
7. Expressions, types and functions
CoreHumanWhich definition runs in constant stack space for any n?
Further reading and resources
- The OCaml Manual: The core languageThe manual's own tour of expressions, functions and data types.
- Stdlib module documentationThe operators and functions available in every OCaml program without opening anything.
- The Printf moduleEvery conversion directive, such as %d, %s, %.2f, %b and %c.
- OCaml Programming: Correct + Efficient + Beautiful, chapter 2 · Michael R. Clarkson and othersCornell's free textbook covers the same ground with many exercises.