OCaml is an object-oriented version of ML. The interesting features of ML include its strict type system and pattern-matching.
let
to define variables and non-recursive functions, remember that recursive
functions are defined using let rec
.
(* C:\Documents and Settings\Default\Desktop\4651\examples\functions.ml *)
(* *. is float multiplication *)
let mult (x, y) = x *. y;;
(* :: is like cons, [] is an empty list *)
let list x = x :: [];; (* make a list out of an element *)
list 5;;
let y = list 5;;
let z = list y;;
List.hd z;; (* Head of the list, like car *)
List.tl z;; (* Tail of the list, like cdr *)
List.length z;;
List.nth z 0;; (* Taking the n-th element of the list *)
(* appending two lists *)
z @ z;; (* the result is [[5][5]] *)
z @ y;; (* illegal: can't put together 5 and [5] in a list *)
let oddeven x = if x mod 2 = 0 then "even" else "odd";;
oddeven 5;;
(* a pair of an int and a char *)
let x = (8, 'A');;
(snd x, fst x);;
let swap (x, y) = (y, x);;
swap (6, 7);;
(* pattern-matching *)
let (xx, yy) = (8, 5);;
xx;;
yy;;
(* define functions using pattern-matching *)
let find5 = function
(5, x) -> "five first"
|(y, 5) -> "five second"
|(x, y) -> " no fives";;
(* an alternative syntax for defining this function *)
(* need this syntax when a function has multiple parameters *)
let find5 x = match x with
(5, _) -> "five first"
|(_, 5) -> "five second"
|(_, _) -> "no fives";;
find5 (6, 5);;
find5 (5, 5);;
find5 (8, 9);;
(* wildcards in pattern-matching *)
let find5 = function
(5, _) -> "five first"
|(_, 5) -> "five second"
|(_, _) -> "no fives";;
(* a recursive function *)
let rec count = function
[] -> 0
| x:: xs -> 1 + count(xs);;
(* anonymous functions *)
(function x -> x + 1) 3;;
(* passing functions to functions*)
let applypair x f = (f (fst x), f (snd x));;
applypair (0, 1) (function x -> if x = 1 then "yes" else "no");;
let rec duplicate = function
[] -> []
| x :: xs -> x :: (x :: duplicate xs);;
duplicate [2; 3; 5];;