Skip to content
Tutorials Center
My learning

Topics

OCaml Tutorial

Learn OCaml step by step: 40 lessons in 9 chapters with examples, quizzes, diagrams and projects.

Start learning →

of lessons completed

Getting Started

  1. 1 What is OCaml? Meet OCaml: a fast, statically typed functional language with type inference, pattern matching and a powerful module system. Learn where it comes from and why people use it.
  2. 2 Installing OCaml with opam Install OCaml the standard way: set up opam, create a switch, add dune, utop and the language server, and check that everything works on Linux, macOS and Windows.
  3. 3 Your First OCaml Program with dune Create, build and run your first OCaml project with dune: project layout, the dune-project and dune files, dune build, dune exec and a tour of a small program.
  4. 4 The OCaml Toplevel (utop) Learn to experiment with OCaml interactively: using utop and the ocaml toplevel, the double semicolon, reading val answers, directives such as #use, #require and #show.

Language Basics

  1. 5 Values and let Bindings Understand OCaml's let: naming values, local bindings with let ... in, scope, shadowing, immutability, and why OCaml has no assignment operator for ordinary names.
  2. 6 Basic Types: int, float, bool, char, string A tour of OCaml's built-in types: integers, floats, booleans, characters, strings and unit, with literal syntax, ranges, escapes, string functions and common pitfalls.
  3. 7 Operators and Type Conversions in OCaml Learn why OCaml has separate integer and float operators, how to convert between types explicitly, operator precedence, the pipe operator and custom operators.
  4. 8 Tuples and Unit in OCaml Group values of different types with OCaml tuples, take them apart with patterns, use fst and snd, return several results from a function, and understand the unit type.
  5. 9 Conditionals and Comparison in OCaml Use if, then, else as an expression in OCaml, chain conditions, combine booleans, understand why both branches share a type, and compare values safely.
  6. 10 Type Inference and Polymorphism in OCaml See how OCaml infers types without annotations, read type signatures, use 'a type variables for polymorphism, add annotations when useful and decode common type errors.

Functions and Recursion

  1. 11 Defining Functions in OCaml Learn to define and call OCaml functions: let syntax, multiple parameters, anonymous fun, the function keyword with patterns, local helpers, closures and the unit argument.
  2. 12 Currying and Partial Application Understand why OCaml function types have chains of arrows, how every function takes one argument, how to apply some arguments early, and how operators become functions.
  3. 13 Higher-Order Functions in OCaml Write and use functions that take or return functions in OCaml: map, filter, function composition, returning functions, callbacks, and building your own higher-order helpers.
  4. 14 Recursion in OCaml: let rec Learn recursion the OCaml way: let rec, base cases and recursive cases, thinking inductively, recursion on numbers and lists, mutual recursion with and, and common mistakes.
  5. 15 Tail Recursion and the Stack in OCaml Learn what a tail call is, why OCaml turns it into a loop, how to rewrite recursion with accumulators, and when stack overflow still matters for List functions.
  6. 16 Labeled and Optional Arguments in OCaml Make OCaml function calls self-documenting with labeled arguments, give parameters default values with optional arguments, and learn how labels interact with partial application.

Lists, Arrays and Records

  1. 17 Lists in OCaml Master OCaml's immutable singly linked lists: list literals, the :: and @ operators, pattern matching on lists, recursion over lists and the cost of common operations.
  2. 18 The OCaml List Module A practical tour of the Stdlib List module: length, nth, rev, map, filter, find, exists, for_all, partition, concat, init, iter and sort, with types, examples and pitfalls.
  3. 19 Folding Lists: fold_left and fold_right Understand folds, the universal list reducers in OCaml: fold_left versus fold_right, accumulators, building sum, max, reverse, map and filter, and choosing the right fold.
  4. 20 Sorting and Association Lists in OCaml Sort lists with List.sort and custom comparison functions, sort by several keys, deduplicate, and use association lists as simple key-value tables with assoc and remove_assoc.
  5. 21 Arrays in OCaml Use OCaml's fixed-size mutable arrays: literals, indexing, Array.make and init, updating with <-, the Array module, 2D arrays, aliasing pitfalls and when to choose arrays over lists.
  6. 22 Records in OCaml Define your own record types with named fields, create and read records, copy with the with syntax, match on records, use field punning, mutable fields and records with type parameters.

Variants and Pattern Matching

  1. 23 Variant Types: Modelling Choices with Constructors Learn OCaml variant types. Define types with several constructors, attach data to them, build recursive and parameterized types, and model real problems precisely.
  2. 24 Pattern Matching in Depth: match, Guards, Or-Patterns and More Master OCaml pattern matching. Destructure tuples, lists, records and variants, use guards, or-patterns, as-bindings and exhaustiveness checks, and avoid common traps.
  3. 25 Option and Result: Handling Absence and Errors as Values Replace null and error codes with OCaml's option and result types. Learn Option and Result modules, map, bind, let-operators and when to choose each over exceptions.
  4. 26 Polymorphic Variants and GADTs: Advanced Variant Types Go beyond ordinary variants. Learn OCaml polymorphic variants with backtick tags, open and closed types, and GADTs that let the type checker track what each expression returns.

Modules and Functors

  1. 27 Modules and Signatures: Structuring OCaml Programs Organize OCaml code with modules. Learn structures, signatures, abstract types, .ml and .mli files, open, include, nested modules and how to hide implementation details.
  2. 28 Functors: Functions from Modules to Modules Understand OCaml functors step by step. Build modules parameterized by other modules, use Map.Make and Set.Make, share types with constraints, and know when functors pay off.
  3. 29 First-Class Modules, Recursive Modules and Module Types Use OCaml modules as values. Learn first-class modules with pack and unpack, module type of, include with constraints, recursive modules and when each technique is appropriate.
  4. 30 Standard Library Containers: Map, Set, Hashtbl, Queue and Stack A practical tour of the OCaml standard library containers. Immutable Map and Set, mutable Hashtbl, Queue, Stack, Buffer and Seq, with complexity notes and guidance on which to choose.

Imperative Features and Exceptions

  1. 31 References, Mutable Fields and Loops: Imperative OCaml OCaml is functional first, but it has first-class imperative features. Learn refs, mutable record fields, arrays, for and while loops, sequencing and when mutation is the right tool.
  2. 32 Exceptions: raise, try, Custom Exceptions and Cleanup Learn how OCaml exceptions work. Raise and catch them, define your own with data, use match with exception, clean up with Fun.protect, and decide when exceptions beat result types.
  3. 33 Input, Output and Formatting: Printf, Scanf and Files Read and write data in OCaml. Print with Printf and Format, read stdin and files with channels, parse with Scanf, handle command-line arguments and format values safely at compile time.

Tooling and Libraries

  1. 34 Dune and opam: Building and Managing OCaml Projects Set up real OCaml projects. Install opam, create switches, scaffold with dune init, write dune files for executables and libraries, add dependencies, use the REPL, utop and ocamlformat.
  2. 35 Testing and Debugging OCaml: Alcotest, Expect Tests and Tools Test OCaml code with dune test, Alcotest unit tests, ppx_expect snapshot tests and QCheck properties, then debug with Printf, backtraces, the type checker, ocamldebug and warnings.
  3. 36 Libraries: Stdlib, Base and Core, Lwt, Eio, ppx and More Tour the OCaml ecosystem. Compare Stdlib with Base and Core, learn concurrency with Domains, Lwt and Eio, use Yojson, Cmdliner, ppx deriving, and decide which library fits each job.

Projects and Practice

  1. 37 Project: Build an Expression Parser, Evaluator and Simplifier Build a calculator in OCaml from scratch. Tokenize text, parse it with recursive descent into a variant type, evaluate with variables, simplify symbolically and take derivatives, with a runnable Python mirror.
  2. 38 Project: A JSON Parser and Pretty Printer from Scratch Write a complete JSON parser in OCaml with no libraries. Model JSON as a variant, parse with a position reference, report errors with offsets, print compact and indented output, and query values.
  3. 39 Project: A State Machine that Makes Illegal States Impossible Model an order workflow in OCaml with variant types and a transition function. Make invalid states unrepresentable, return result errors, replay event logs with folds and add an abstract account module.
  4. 40 OCaml Practice Problems with Solutions and Hints Sharpen your OCaml with eight exercises on lists, strings, maps, recursion, trees, graphs and backtracking. Each has a statement, a solution, tested results and a runnable Python version.