Introduction to OCaml Jupyter

ocaml-jupyter is an OCaml kernel for Jupyter. This provides a rich OCaml REPL interface on Jupyter: markdown/HTML documentation, LaTeX formula by MathJax, and embedding images like figures and charts.

You can interactively execute OCaml programs in a cell (a textbox to input code):


In [1]:
let x = List.map (fun x -> x * 2) [1; 3; 5; 7; 9]


Out[1]:
val x : int list = [2; 6; 10; 14; 18]

jupyter.notebook

jupyter.notebook provides a way to control Jupyter from OCaml REPL in a notebook. For example, you can dynamically generate HTML, markdown, and images.


In [2]:
#require "jupyter.notebook" ;;

In [3]:
Jupyter_notebook.display "text/html" "<b>Hello, World!</b>"


Hello, World!
Out[3]:
- : Jupyter_notebook.display_id = <abstr>

In [4]:
Jupyter_notebook.display_file ~base64:true "image/png" "datasets/lenna.png"


Out[4]:
- : Jupyter_notebook.display_id = <abstr>

In [5]:
Jupyter_notebook.printf "<table><tr><th>Name</th><th>Age</th></tr>" ;
[
  "David", 29;
  "Smith", 35;
  "Rovert", 62;
]
|> List.iter (fun (name, age) -> Jupyter_notebook.printf "<tr><td>%s</td><td>%d</td></tr>" name age) ;
Jupyter_notebook.printf "</table>" ;
Jupyter_notebook.display_formatter "text/html"


NameAge
David29
Smith35
Rovert62
Out[5]:
- : Jupyter_notebook.display_id = <abstr>

jupyter.archimedes

Archimedes is an easy-to-use 2D plotting library. OCaml Jupyter supports Archimedes charts in jupyter.archimedes sub-package. It can be installed by

$ opam install -y cairo2 archimedes jupyter

In [6]:
#require "jupyter-archimedes"


Module Archimedes loaded and aliased as A.

This figure shows $y = sin(x)$ where $x \in [0, 10]$.


In [7]:
let vp = A.init ~w:560. ~h:260. ["jupyter"] in
A.Axes.box vp ;
A.set_color vp A.Color.red ;
A.fx vp sin 0.0 10.0 ;
A.close vp


Out[7]:
- : unit = ()

We show a little complex example "random walk".


In [8]:
let rec walk acc p i =
  if i = 0 then List.rev acc else begin
    let q = if Random.bool () then succ p else pred p in
    walk (q :: acc) q (pred i)
  end in
let vp = A.init ~w:560. ~h:260. ["jupyter"] in
A.Axes.box vp ;
A.set_color vp A.Color.red ;
A.List.y vp ~style:`Lines (List.map float @@ walk [] 0 1000) ; (* Plot a random walk of 1000 points. *)
A.close vp


Out[8]:
- : unit = ()