Skip to content

Ocaml

Overview

  • Created by Xavier Leroy (and more) in 1996
  • Garbage collection
  • First-class functions
  • Static type checking
  • Parametric polymorphism
  • Support for immutable programming
  • Type inference
  • Algebraic Data Types and pattern matching
  • Use ocaml to open the REPL
  • Compile with ocamlc <filename>.ml
  • You can use the -i flag to print all names and type signatures, i.e ocaml -i <filename>.ml

Basic Syntax

(* Comments are enclosed in (* and *). It's fine to nest comments. *)

(* There are no single-line comments. *)

(* Variable and function declarations use "let" keyword. *)
let x = 10 ;;

(* OCaml allows single quote characters in identifiers. *)
let foo = 1 ;;
let foo' = foo * 2 ;;

(* We don't need to declare type signatures due to type inference. *)
let inc_int (x: int) : int = x + 1 ;;

(* You need to mark recursive function definitions as such with "rec" keyword. *)
let rec factorial n =
    if n = 0 then 1
    else n * factorial (n-1)
;;

(* Function application usually doesn't need parentheses around arguments *)
let fact_5 = factorial 5 ;;

(* Every function must have at least one argument.
   Since some functions naturally don't take any arguments, there's
   "unit" type for it that has the only one value written as "()" *)
let print_hello () = print_endline "hello world" ;;

(* Note that you must specify "()" as argument when calling it. *)
print_hello () ;;

let rec
  is_even = function
  | 0 -> true
  | n -> is_odd (n-1)
and
  is_odd = function
  | 0 -> false
  | n -> is_even (n-1)
;;

(* Anonymous functions *)
let my_lambda = fun x -> x * x ;;

(* Lists are enclosed in square brackets, items are separated by
   semicolons. *)
let my_list = [1; 2; 3] ;;

(** Matching type constructors **)

type animal = Dog of string | Cat of string ;;

let say x =
    match x with
    | Dog x -> x ^ " says woof"
    | Cat x -> x ^ " says meow"
;;

say (Cat "Fluffy") ;;

References


Last update: November 23, 2020