Starting an OCaml app project using Dune

On configuring the blazingly-fast, state-of-the-art OCaml build system to get your app running.

Seascape. [source]

Requirements

$ opam --version
1.2.2

Editor setup

Screenshot of example OCaml code in VSCode with vscode-reasonml extension.

Initial setup

$ mkdir todolist
$ cd todolist
$ opam switch todolist --alias-of 4.06.1
$ eval $(opam config env)
$ opam install merlin ocp-indent dune utop

Dune basics

Executables

Contents of todolist/dune file.
Contents of todolist/main.ml file.
$ dune build main.exe
$ dune exec ./main.exe
Hello, world!
$ mkdir bin
$ mv dune main.ml bin/
$ dune clean
$ dune exec bin/main.exe
Hello, world!

Libraries

$ mkdir lib
Contents of lib/dune file.
Contents of lib/math.ml file.
Modified contents of bin/dune file.
$ dune build bin/main.exe
Modified contents of bin/main.ml file.
$ dune exec bin/main.exe
5
2

Interface files

Contents of lib/math.mli file.
$ dune exec bin/main.exe
(...some output...)
File "bin/main.ml", line 6, characters 15-23:
Error: Unbound value Math.sub
(...some output...)
File "lib/math.ml", line 3, characters 4-7:
Error (warning 32): unused value sub.
Modified contents of lib/math.mli file.

Trying out libraries interactively via utop

A colorful utop session.
utop # open Lib;;utop # #show Math.add;;              (* 1 *)
val add : int -> int -> int
utop # Math.add 1 2;; (* 2 *)
- : int = 3
utop # let add2 = Math.add 2;; (* 3 *)
val add2 : int -> int = <fun>
utop # add2 5;; (* 4 *)
- : int = 7

That’s it for now!

Software Engineer. Functional programming and distributed systems enthusiast. Java, JavaScript, Elixir, OCaml, Haskell.