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

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