TExcelTAD
Home › OCaml › OCaml Intro

OCaml Intro

OCaml is a general-purpose programming language that combines functional programming with practical imperative and object-oriented features. It has a strong static type system with type inference: the compiler checks every type before the program runs, yet you rarely have to write a type down yourself.

OCaml grew out of the ML ("Meta Language") family at INRIA in France. The first version of Caml appeared in the 1980s, and "Objective Caml", today simply OCaml, arrived in 1996. OCaml 5 (2022) added two big features: effect handlers and domains for running code in parallel on several CPU cores.

Here is a complete OCaml program:

ocaml · try it yourself
let greeting name = "Hello, " ^ name ^ "!"

let () =
  print_endline (greeting "OCaml");
  print_endline (greeting "learner")
Hello, OCaml!
Hello, learner!

greeting is a function that joins three strings with the ^ operator. The let () = ... part is the program's entry point by convention: it runs the code that prints.

Why learn OCaml?

Strength What it means for you
Type inference Strong safety without type annotations everywhere
Pattern matching Take data apart clearly; the compiler warns about cases you forgot
Variants (algebraic data types) Model "one of these shapes" data precisely
Fast native code ocamlopt produces machine code that is usually close to C++ or Java speed
A powerful module system Signatures and functors organise large programs
Garbage collection No manual memory management

OCaml is used in compilers and language tools (the first Rust compiler was written in OCaml, and so are Flow, Hack, Coq/Rocq and the Haxe compiler), in finance (Jane Street runs most of its trading systems on it), in static analysers and in systems like the MirageOS unikernel.

A taste of the style

OCaml programs are built from expressions. Even if and match produce values. Data is usually immutable, and functions are ordinary values you can pass around:

ocaml · try it yourself
type shape =
  | Circle of float
  | Rectangle of float * float

let area s =
  match s with
  | Circle r -> 3.14159 *. r *. r
  | Rectangle (w, h) -> w *. h

let () =
  let shapes = [ Circle 1.0; Rectangle (2.0, 3.0); Circle 0.5 ] in
  List.iter (fun s -> Printf.printf "area = %.2f\n" (area s)) shapes;
  let total = List.fold_left (fun acc s -> acc +. area s) 0.0 shapes in
  Printf.printf "total = %.2f\n" total
area = 3.14
area = 6.00
area = 0.79
total = 9.93

Don't worry about every detail yet. type shape declares a variant type, match picks the right formula for each shape, and List.fold_left adds up the areas. Each of these gets its own lesson.

Note: Notice *. instead of *. OCaml uses separate operators for floating-point numbers (+., -., *., /.). This looks odd at first, but it is what lets the compiler infer types without guessing.

How the examples in this course run

Every ocaml run playground is a complete program compiled with the native-code compiler ocamlopt (OCaml 5.4) and executed. Only the standard library is available (no opam packages). Press ▶ Run, change the code, and run it again.

Some lessons also show sessions from the interactive toplevel (utop or ocaml), where each phrase ends with ;; and the toplevel replies with its type:

ocaml
# 1 + 2;;
- : int = 3
# let double x = x * 2;;
val double : int -> int = <fun>

Those sessions are illustrations and are not run. The toplevel is the best way to explore types on your own machine.

What you will learn

  1. The basics: values, types, operators, let, if
  2. Functions: currying, labeled arguments, recursion, pipelines
  3. Data: lists, pattern matching, tuples, records, variants, options, results
  4. Modules, signatures, functors, Map and Set
  5. Imperative features: exceptions, references, arrays, loops, hashtables, sequences
  6. Advanced topics: GADTs, objects, effect handlers and domains
  7. Exercises and a mini project: an expression evaluator

Test yourself

What does OCaml's type inference mean?

  1. Types are checked only at run time
  2. The compiler works out most types without annotations
  3. Every variable must be annotated
  4. Types are optional and ignored

Which operator multiplies two floats in OCaml?

  1. *
  2. **
  3. *.
  4. .*

What did OCaml 5 add to the language?

  1. Classes
  2. Garbage collection
  3. Effect handlers and parallel domains
  4. Type inference