Appendix A — OCaml Setup and Tooling

This appendix covers everything needed to run the code in this book, from a fresh Linux/macOS installation to a productive VS Code development environment.


A.1 Installing OCaml with opam

opam is the OCaml package manager. Install it first:

# Linux (Debian/Ubuntu)
sudo apt-get install -y opam

# macOS (Homebrew)
brew install opam

# Initialise
opam init --auto-setup
eval $(opam env)

Install OCaml 5.2

opam switch create 5.2.0
eval $(opam env)
ocaml --version   # should print 5.2.0

A.2 Installing Book Dependencies

opam install \
  core base dune \
  owl owl-plplot \
  zarith \
  yojson ppx_jane \
  ppx_sexp_conv ppx_compare \
  menhir \
  alcotest qcheck

For OxCaml / Jane Street extensions (requires Jane Street opam repository):

opam repo add janestreet-bleeding \
  https://ocaml.janestreet.com/opam-repository
opam install jane-street-headers mode_string

A.3 Dune Project Template

Every chapter's exercise code uses this layout:

my_project/
  dune-project       ← project root
  lib/
    dune             ← library target
    black_scholes.ml
    numerics.ml
    ...
  bin/
    dune             ← executable target
    main.ml
  test/
    dune             ← test target
    test_bs.ml

dune-project

(lang dune 3.12)
(using menhir 2.1)

lib/dune

(library
 (name quant)
 (libraries core base owl zarith yojson)
 (preprocess (pps ppx_jane)))

bin/dune

(executable
 (name main)
 (libraries quant core)
 (preprocess (pps ppx_jane)))

test/dune

(test
 (name test_bs)
 (libraries quant alcotest))

Build and run:

dune build
dune exec bin/main.exe
dune test

A.4 VS Code Setup

Install the OCaml Platform extension (ID: ocamllabs.ocaml-platform).

Install ocaml-lsp-server and ocamlformat:

opam install ocaml-lsp-server ocamlformat

Recommended .vscode/settings.json:

{
  "editor.formatOnSave": true,
  "ocaml.server.path": "ocamllsp",
  "[ocaml]": {
    "editor.defaultFormatter": "ocamllabs.ocaml-platform"
  }
}

A.5 utop — Interactive REPL

opam install utop
utop

Inside utop:

#require "core";;           (* load library *)
open Core;;
List.map ~f:(fun x -> x * 2) [1;2;3];;

Load a module file directly:

#use "black_scholes.ml";;
Black_scholes.call ~spot:100. ~strike:100. ~rate:0.05 ~vol:0.2 ~tau:1.0;;

A.6 Common Commands Reference

TaskCommand
Build alldune build
Run executabledune exec bin/main.exe
Run testsdune test
Clean builddune clean
Format codedune fmt
Check typesdune build @check
List installed packagesopam list
Switch OCaml versionopam switch 4.14.0
Update opamopam update && opam upgrade

A.7 Troubleshooting

"Unbound module Core": Run opam install core and rebuild.

"ocamllsp not found": Run opam install ocaml-lsp-server then restart VS Code.

Dune build error "multiple rules": Ensure each .ml file appears in only one (library) or (executable) stanza.

opam env not loaded: Add eval $(opam env) to your ~/.bashrc or ~/.zshrc.