Skip to content
LumenaryAcademy
Foundations 45 min

First steps in OCaml

Where OCaml came from, what it is good at, and your first programs with opam, the toplevel and dune.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Why OCaml?

Suppose you want a language in which the compiler catches most of your mistakes before the program runs, but which does not make you write types everywhere; which encourages immutable data and small functions, but lets you use a mutable array or a for loop when that is simply the clearest way; which compiles to fast native code with a garbage collector whose pauses are short and predictable; and whose module system lets a large team divide a big program into pieces with precise, checked interfaces. That combination is OCaml.

It is a practical functional language. Practical, because it is strict (expressions are evaluated when they are reached, as in Python or Java, so performance is easy to predict) and because it allows side effects anywhere, without ceremony. Functional, because functions are values, data is immutable unless you ask otherwise, and the core way to work with data is pattern matching over carefully designed types.

People who write OCaml for a living tend to say two things about it. First, that refactoring is unusually safe: change a type, and the compiler lists every place that must change with it. Second, that the language is small enough to keep in your head: most of what experts use daily is in the first half of this course.

History & global context

From ML to OCaml 5

OCaml belongs to the ML family, which began in the early 1970s at the University of Edinburgh. Robin Milner and colleagues were building LCF, a program for checking mathematical proofs, and needed a "meta language" (ML) in which to write proof tactics safely. ML introduced ideas that are now everywhere: type inference (you write let f x = x + 1 and the compiler deduces that f takes and returns an integer), polymorphic types, and algebraic data types with pattern matching.

In France, researchers at Inria developed their own dialect, Caml, from 1985. In 1990 Xavier Leroy and Damien Doligez wrote Caml Light, a small, fast bytecode implementation that became popular in teaching. A native-code compiler and a powerful module system followed, and in 1996 an object system was added, giving the language its name, Objective Caml, shortened officially to OCaml in 2011.

The 2010s brought an industrial community. The trading firm Jane Street adopted OCaml for nearly all of its software and became one of its largest supporters; opam, the package manager, appeared in 2013; the dune build system, begun at Jane Street, became the standard; and the OCaml Software Foundation was set up in 2018 to support the ecosystem. Through all of this, the language kept a strong compatibility record: code written fifteen years ago usually still compiles.

The biggest change came with OCaml 5.0 in December 2022, after years of work by the "Multicore OCaml" project: a new runtime that runs OCaml code in parallel on several cores (domains), and effect handlers, a new way to write concurrent programs. OCaml 5.3 (2025) added dedicated syntax for handling effects. You will use both in lesson 8. The programs in this course were run with OCaml 5.4.

DefinitionsH

The toolchain

Definition— opam

opam is OCaml's package manager. It installs compilers and libraries, and keeps them in switches: independent environments, each with its own compiler version and packages, either global or local to one project.

Definition— The compilers and the toplevel

ocamlc compiles to portable bytecode, run by the ocamlrun virtual machine; ocamlopt compiles to native machine code, typically several times faster. ocaml is the toplevel, OCaml's interactive environment: type an expression, end it with ;;, and it prints the value and its type. ocaml file.ml runs a whole file as a script. utop is an improved toplevel with history, completion and colour, installed with opam install utop.

Definition— dune

dune is the build system almost every OCaml project uses. A small dune file in each directory says what it contains (a library, an executable, tests), and dune build, dune exec and dune test do the rest, calling the compilers with the right flags.

Follow the instructions at ocaml.org/install. On Linux and macOS you install opam from your system's package manager or with the official script, then run opam init, which creates a first switch with the latest compiler. On Windows, the instructions describe the current recommended route. Then:

bash
opam switch list          # which switches exist, and which is active
ocaml -version            # the compiler version
opam install dune utop    # the build system and the better toplevel

If you would rather not install anything yet, the OCaml Playground runs programs in the browser.

Worked examplesH

Your first programs

Hello, world

Save this as hello.ml and run it with ocaml hello.ml:

ocaml
let () =
  print_endline "Hello, world!";
  print_endline "Kia ora te ao! Hola, mundo! Jambo, dunia!"
text
Hello, world!
Kia ora te ao! Hola, mundo! Jambo, dunia!

There is no main function in OCaml. A source file is a sequence of top-level definitions, evaluated from top to bottom, and the side effects happen as they are reached. let () = ... is the idiomatic way to write "the program's entry point": it evaluates the expression on the right, which must produce (), the unit value that stands for "nothing interesting". Matching it against the pattern () makes the compiler check that you did not accidentally compute something and throw it away.

print_endline prints a string and a newline. The single semicolon between the two calls means "do this, then that": e1; e2 evaluates e1 (which should be of type unit) and then e2. Function application needs no parentheses: print_endline "hi".

Definitions and formatted output

ocaml
(* Convert a temperature from degrees Celsius to degrees Fahrenheit. *)
let to_fahrenheit c = (c *. 9. /. 5.) +. 32.

let report (city, c) =
  Printf.printf "%s: %.1f C is %.1f F\n" city c (to_fahrenheit c)

let () = List.iter report [ ("Nairobi", 24.); ("Oslo", -3.); ("Lima", 19.5) ]
text
Nairobi: 24.0 C is 75.2 F
Oslo: -3.0 C is 26.6 F
Lima: 19.5 C is 67.1 F

Some things to notice, each explained fully in the next lessons:

  • Comments are written (* like this *), and they nest.
  • OCaml has separate operators for floating-point numbers: +., -., *., /.. The literal 9. is a float; 9 would be an int, and mixing them is a type error. This looks fussy at first, but it is the reason OCaml can infer types without any annotations: c *. 9. can only mean that c is a float.
  • report takes a pair and names its parts with the pattern (city, c).
  • Printf.printf is the printf function from the Printf module of the standard library. Its format string is checked at compile time against the arguments: %s must receive a string, %.1f a float with one decimal.
  • Lists are written with semicolons between elements: [a; b; c]. List.iter f xs calls f on each element, in order.

Recursion and integers

ocaml
let rec factorial n = if n = 0 then 1 else n * factorial (n - 1)

let () =
  for i = 0 to 5 do
    Printf.printf "%d! = %d\n" i (factorial i)
  done;
  Printf.printf "20! = %d\n" (factorial 20);
  Printf.printf "max_int = %d\n" max_int
text
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
20! = 2432902008176640000
max_int = 4611686018427387903

A function that calls itself must be declared with let rec. Equality on values is = (a single sign; == exists but tests physical identity, which you rarely want). And yes, OCaml has a for loop: an imperative feature used freely where it reads best.

The last line shows something specific to OCaml. Its int has 63 bits, not 64: the runtime uses the lowest bit of every word to tell integers apart from pointers, which is part of what makes its garbage collector fast. The largest int is therefore 2⁶² − 1. For full 64-bit or arbitrary-precision integers there are the Int64 module and the zarith library.

ComputationC

The toplevel, compilers and errors

Exploring in the toplevel

Start ocaml (or utop) and type expressions, each ending with ;;. A real session, with the toplevel's answers:

text
# 1 + 2 * 3;;
- : int = 7
# let square x = x * x;;
val square : int -> int = <fun>
# square 12;;
- : int = 144
# String.length "Ouagadougou";;
- : int = 11
# 3.0 +. 1.5;;
- : float = 4.5
# List.map;;
- : ('a -> 'b) -> 'a list -> 'b list = <fun>

Each answer gives a name (- for an anonymous expression, val square for a definition), a type after the colon, and a value. Functions are shown as <fun>. Read int -> int as "takes an int, returns an int". The type of List.map contains type variables, 'a and 'b (pronounced "alpha" and "beta"): it works for lists of any type. The ;; is only needed in the toplevel, to say "I have finished typing; evaluate now". In source files you leave it out.

Compiling

CommandProducesUse
ocaml hello.mlnothing; runs the file in the toplevelquick scripts, the programs in these lessons
ocamlc -o hello hello.mlbytecode executableportable, fast to compile
ocamlopt -o hello hello.mlnative executablespeed; what you ship
dune exec ./hello.exebuilds with dune, then runsreal projects (lesson 9)

Reading a type error

Save this as main.ml:

ocaml
let age = 31
let () = print_endline ("Age: " ^ age)

^ joins two strings, and ocaml main.ml refuses to run the program:

text
File "./main.ml", line 2, characters 34-37:
2 | let () = print_endline ("Age: " ^ age)
                                      ^^^
Error: The value age has type int but an expression was expected of type
         string

The message gives the file, line and character range, underlines the culprit, and states the mismatch: age is an int, but ^ needs a string there. The fix is to convert: "Age: " ^ string_of_int age, or more idiomatically Printf.sprintf "Age: %d" age. OCaml never converts between types implicitly, not even from int to float (float_of_int does that).

IntuitionH

How an OCaml program runs

It helps to have a picture of what happens between saving a file and seeing its output, because several of OCaml's habits follow from it.

First, the whole file is type-checked. Even ocaml hello.ml, which feels like running a script, checks every definition before evaluating anything. A type error on the last line stops the program before the first line runs. After checking, the types are erased: at run time there is no type information attached to values, which is part of why OCaml programs are compact and fast, and why a compiled program cannot simply "print any value" the way the toplevel does.

Then the definitions are evaluated, in order, strictly. OCaml is a strict (or eager) language: the arguments of a function are evaluated before the function is called, and let x = expensive () computes expensive () right there. This makes the cost of a program easy to predict, unlike Haskell's lazy evaluation; when you want laziness, you ask for it explicitly (lesson 7 shows Seq). One detail surprises everyone once: the order in which a function's arguments are evaluated is not specified by the language, and the current compilers evaluate them right to left. f (print_string "a"; 1) (print_string "b"; 2) prints ba. Never rely on side effects inside arguments; bind them with let first, in the order you want.

Values live in memory managed by a garbage collector. Small integers, characters, booleans and constant constructors are stored directly in a machine word. Everything else (strings, lists, records, closures) is a block on the heap. OCaml's collector is generational: new values are allocated in a small minor heap by simply bumping a pointer, which is about as cheap as allocation can be, and the many values that die young are reclaimed almost for free. Survivors move to the major heap, which is collected incrementally in small slices, so pauses stay short. That is why idiomatic OCaml can create many small immutable values without worrying: the runtime was designed for exactly that style.

Common misconceptionsH

Common misconceptions

Misconception

"OCaml is an object-oriented language; the O says so." OCaml has an object system, and it is occasionally useful, but idiomatic OCaml code is built from functions, records, variants and modules. Many experienced OCaml programmers rarely write a class at all.

Misconception

"Functional means no loops, no mutation, no printing." OCaml has for and while loops, mutable references and arrays, and side effects anywhere. What it offers is a default: immutable data and expressions with values, which you leave deliberately and locally when that is clearer or faster.

Misconception

"Separate float operators mean OCaml is primitive." They are a deliberate trade: in exchange for writing +., you get complete type inference with no overloading puzzles, and code where the meaning of every operator is visible at a glance. Libraries can still offer overloaded-looking notation through local module opens, as later lessons show.

Misconception

"OCaml is only used in universities." It is taught at many universities, from Cornell to Paris, and it is also used in industry, for trading systems, compilers, static analysers, blockchains and infrastructure. Lesson 9 surveys where, honestly: it is a smaller ecosystem than Java's or Python's.

Exercises

Exercises

Try anything you are unsure of in the toplevel or in the OCaml Playground.

1. First steps in OCaml

Warm-upHuman

Your project needs an older OCaml compiler than the one you use for everything else. What lets you keep both, cleanly separated?

Choose one

2. First steps in OCaml

Warm-upHuman

Why do OCaml programs usually start their main code with let () = ...?

Choose one

3. First steps in OCaml

CoreComputational

What does this program print? Write the lines separated by single spaces.

let () =
  print_string "Ka";
  print_string "ra";
  print_endline "chi";
  Printf.printf "%d-%s\n" (6 * 7) "go"

4. First steps in OCaml

CoreComputational

What does this program print?

let rec total n = if n = 0 then 0 else n + total (n - 1)

let () = Printf.printf "%d\n" (total 10 - total 4)

5. First steps in OCaml

CoreHuman

In the toplevel you type let triple x = 3 * x;;. What does the toplevel answer? Write the whole line.

6. First steps in OCaml

Warm-upHuman

Which command produces the fastest-running executable from crunch.ml?

Choose one

7. First steps in OCaml

CoreComputational

let n = 12 and then print_endline ("Total: " ^ n) is rejected: n has type int but a string was expected. Which replacements print Total: 12? Choose all that apply.

Choose all that apply

Further reading and resources