Skip to content

Switches, dune, and utop

15 November 2024 ยท OCaml 5.2

OCaml's package manager is opam, and its unit of isolation is a switch: a compiler version together with the packages compiled against it. Installed globally or per directory, two projects never fight over library versions.

opam init
opam switch create 5.2.0
eval $(opam env)
opam install dune utop ocaml-lsp-server

utop is the interactive toplevel with completion and history, and a single file runs straight through ocaml hello.ml without a build file:

let greet name = Printf.sprintf "Hello, %s!" name

let () =
  assert (greet "OCaml" = "Hello, OCaml!");
  print_endline (greet "OCaml")

Notice there are no type annotations. Printf.sprintf reads the "%s" format literal as a structured type rather than a plain string, so greet is inferred as string -> string, and passing an int fails to compile.

For anything past a single file, Dune sets up and builds the project:

dune init proj hello
cd hello
dune build
dune exec hello

That gives dune-project at the root, lib/ for the library, bin/main.ml for the executable, and test/ for tests. dune build -w watches the tree and recompiles on save, which alongside ocaml-lsp-server keeps feedback nearly instant.