OCaml Graphics on the Macintosh

I have Xcode 6.0.1 installed—4.5.0 presumably required. I am running OS X 10.9.4 on a MacBook. I got OCaml 4.01.0 from here. This download installs many files in “/usr/local/bin” including “ocaml” which provides a shell command ocaml which with no argument gives you a read-eval-print-loop (REPL). (Directory /usr/local/lib/ocaml is also provided and populated.)

Since OS X 10.8 it is necessary to install X11. With version OS X 10.9.2 and perhaps other nearby versions, this information is required. Today (2014 Sept 21) with OCaml 4.01 and OS 10.9.4 that is not needed.

To use OCaml graphics you need an alternative to /usr/local/bin/ocaml and it can be made with the command:

ocamlmktop -o mytop graphics.cma
which makes file mytop in your directory. The command ./mytop then gets you the REPL that can do graphics. In OCaml REPL:
open Graphics;;
open_graph "";;
for i = 0 to 100 do plot 20 i done;;
There will be a pause while the XQuartz code is loaded. Then perhaps
set_window_title "Demo";;
resize_window 700 400;;
Voila! See this for more graphics primitives.

To run a program with graphics from an OCaml source file do:

./mytop source.ml

When you are done: In Dock quit X11; In shell delete mytop or subsequently omit the ocamlmktop command.

A trivial exploration of graphics events:

open Graphics;;
open Printf;;
open_graph "";;
while 0<1 do
  let e = wait_next_event [Button_down; Key_pressed] in
  printf "x=%d y=%d %s %s %c %02x\n" e.mouse_x e.mouse_y
    (if e.button then "down" else "up")
    (if e.keypressed then "char" else "nochar")
    e.key (int_of_char e.key); flush stdout;         

Here is an OCaml graphics app described at the bottom here.