letto define variables and non-recursive functions, remember that recursive functions are defined using
(* 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 [] *) z @ y;; (* illegal: can't put together 5 and  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];;
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.