### OCaml examples.

A few things to keep in mind:
• OCaml is strictly typed, don't mix different types. Note that there is no automatic conversion between int and float
• Statements end with ;;
• List elements are separated by ; as in [3; 6; 9]
• Use `let` to define variables and non-recursive functions, remember that recursive functions are defined using `let rec`.
• Functions can be defined in two different ways:
• Without pattern matching. In this case you need to specify the parameter (or parameters) on the left-hand side. See swap below as an examples.
• With pattern-matching. In this case you don't have parameter on the left-hand side; you need a keyword 'function' on the right-hand side (see find5 below).

``````
(* 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";;

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 *)
(fun x -> x + 1) 3;;

(* passing functions to functions*)

let applypair x f = (f (fst x), f (snd x));;

applypair (0, 1) (fun x -> if x = 1 then "yes" else "no");;

let rec duplicate = function
[] -> []
| x :: xs -> x :: (x :: duplicate xs);;

duplicate [2; 3; 5];;
``````

This is an example from CSci 4651 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.