Lesson 4 of 40 ยท Getting Started
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.
The toplevel is an interactive OCaml session: you type an expression, press Enter, and OCaml shows its type and value. It is the best way to learn, because every idea in this tutorial can be tried in seconds. The default toplevel is called ocaml; utop is a nicer one with history, completion and syntax coloring. Start it with:
utop
The toplevel runs on your machine, not on this site. The sessions below are read-only examples of what you will see. The lines you type start with #; the answers start with - or val.
Your first session
# 1 + 2;; - : int = 3
You type 1 + 2;;. The two semicolons ;; tell the toplevel "I am done, evaluate". The answer has three parts: - (an anonymous result with no name), : int (the type) and = 3 (the value).
Give the result a name with let:
# let radius = 4;; val radius : int = 4 # let area = 3.14159 *. float_of_int radius *. float_of_int radius;; val area : float = 50.26544
When you bind a name, the answer starts with val, then the name, its type and its value. Do not worry about *. and float_of_int yet; they come in Operators and conversions.
Functions show up as <fun>
# let square x = x * x;; val square : int -> int = <fun> # square 9;; - : int = 81
The type int -> int reads "a function from int to int". The value is shown as <fun> because a function has no printable form. This quick view of types is exactly why the toplevel is a great learning tool: you can check what the compiler infers about any expression.
Multi-line input
You can spread an expression over several lines. The toplevel waits until it sees ;;:
# let describe n =
if n < 0 then "negative"
else if n = 0 then "zero"
else "positive";;
val describe : int -> string = <fun>
In a source file you never need ;;. It is a toplevel-only habit. Inside utop, newer versions can also run a phrase when the line looks complete, but writing ;; is always correct.
Directives: commands for the toplevel itself
Lines that begin with # are directives, not OCaml code. The most useful:
| Directive | Meaning |
|---|---|
#help;; |
List all directives |
#use "file.ml";; |
Run a source file as if you typed it |
#require "str";; |
Load a library found by findlib (in utop and the ocaml toplevel with #use "topfind") |
#show List;; |
Print the signature of a module |
#show_type option;; |
Print a type definition |
#quit;; |
Leave the toplevel (or press Ctrl+D) |
#show is a wonderful way to explore the standard library without leaving the terminal:
# #show List.length;; val length : 'a list -> int
The 'a is a type variable meaning "any type", so List.length works on a list of anything. This is polymorphism, which you will meet in the next chapters.
Errors in the toplevel
Mistakes produce a message with the exact location:
# 1 + "two";; Error: The constant "two" has type string but an expression was expected of type int
The wording of messages differs a little between compiler versions. Read type errors from the top: OCaml says which expression is wrong and what it expected. The toplevel is perfect for reproducing and understanding such messages.
Unhandled exceptions are printed too, and the toplevel stays alive:
# 10 / 0;; Exception: Division_by_zero.
Working with files
Large experiments belong in a file, not in the REPL. A common workflow:
- Write code in
notes.ml. - In utop, run
#use "notes.ml";;to load all its definitions. - Try functions interactively, edit the file,
#useagain.
Inside a dune project, dune utop starts utop with your project's libraries already loaded, so you can call your own modules directly:
dune utop
Tips for productive sessions
- Press the up arrow for history; Tab for completion (in utop).
_stands for "ignore":let _ = 5;;binds nothing.- Shadowing is allowed: running
let x = 1;;and thenlet x = "now a string";;just creates a new binding. - In a clean session type
#use "topfind";;first if#requireis unavailable in plainocaml.
A stand-in: reading answers
The toplevel prints val name : type = value. This stand-in builds the same format so you can see how the three parts fit together.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Check your understanding
Quick check ยท 4 questions
of 4 answered You scored / 4 ยท perfect!
-
1. What do the two semicolons
;;mean in the toplevel?;;marks the end of a toplevel phrase. It is not needed in source files. -
2. What does the answer
val x : int = 5tell you?valanswers show the name, the type and the value of a binding. -
3. Which directive loads a source file into the toplevel?
#use "file.ml";;evaluates a file as if you had typed its contents. -
4. How do you start utop with your dune project's modules available?
dune utopbuilds the libraries and starts utop with them loaded.
Summary
- The toplevel evaluates phrases ending in
;;and shows type and value. - Answers look like
- : int = 3orval x : int = 4; functions appear as<fun>. - Directives (
#use,#require,#show,#quit) control the toplevel itself. - Use
dune utopto experiment with your own project code.
Next: Values and let bindings
Track your progress
Create a free account to tick off lessons and pick up where you left off on any device.
of OCaml lessons completed