Willem Hoek  »  OCaml notes

Mar 07, 2019

Install OCaml

Install on Linux

sudo apt-get update -y && apt-get upgrade -y
sudo apt-get install m4 patch ocaml -y

Install OPAM as per notes https://opam.ocaml.org/doc/Install.html

sudo apt-get install opam

else

wget https://raw.github.com/ocaml/opam/master/shell/opam_installer.sh -O - | sh -s /usr/local/bin

Install rest via opam

opam init
opam update
opam upgrade
opam switch
opam switch list-available
opam switch list-available base
opam switch create 4.10.0

# issue with OCaml on debian -    https://github.com/ocaml/opam/issues/3827
rm -rf ~/.opam
apt install mccs
opam init --solver=mccs
opam switch create 4.10.0 --solver=mccs

This will take a few minutes.

For installed version of OCaml - get required tools/libraries via opam

opam install utop tuareg merlin user-setup 
opam user-setup install

For OCaml on Windows (cygwin) – see https://fdopen.github.io/opam-repository-mingw/

opam install depext depext-cygwinports

Better to use following to install packages – as it take care of dependencies. E.g. to install sqlite3 package

opam depext -i sqlite3

Cheat sheets

https://ocaml.org/docs/cheat_sheets.html

Pattern match

https://ocaml.org/learn/tutorials/data_types_and_matching.html#Pattern-matching-on-datatypes

(*    pair : int * int -> int -> int = <fun>    *)

let pair k p =
  match k, p with
  | (1, _), _ -> 1
  | _, 2 -> 222
  | _, _ -> 0

The next are are the same.

(*    first : int list -> string = <fun>    *)

let first l =
  match l with
  | a :: b :: _ when a = b -> "double"
  | 1 :: _ -> "one"
  | _ -> "other"

let first = function
  | a :: b :: _ when a = b -> "double"
  | 1 :: _ -> "one"
  | _ -> "other"

Lists

https://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html

let a = List.init 5 (fun x -> x);;
val a : int list = [0; 1; 2; 3; 4]

List.map (fun x -> x * 2) a;;

List.iter (fun i x -> print_int x) a;;

List.iteri (fun i x -> print_int x) a;;

Arrays

https://caml.inria.fr/pub/docs/manual-ocaml/libref/Array.html

let create_grid n = Array.init n
                      (fun y -> Array.init n (fun x -> x + y - 1))
 
let print_grid g =
  let n = Array.length g in
  for y = 1 to n-1  do
    for x = 1 to n-1 do
      Printf.printf "%3i%!" g.(x).(y)
    done;
    Printf.printf "\n%!"
  done
  
let a = create_grid 10 

let () = print_grid a  


Edit