(* code samples from lecture 1 *)
(* type #use "lec01.ml";; at the toplevel *)
(* sum squares of numbers from 1 to n *)
(* returns sum_{1<=i<=n} i^2 *)
let rec sumsquares n =
if n <= 0 then 0
else n*n + sumsquares (n - 1)
let example2 = sumsquares 5
(* reverse *)
let rec reverse l = match l with
| [] -> []
| hd::tl -> (reverse tl) @ [hd]
let example5 = reverse [1;2;3;4]
(* or just use the version from the standard library! *)
let reverse = List.rev
(* quicksort *)
(* returns l in sorted in ascending order *)
let rec qsort l = match l with
| [] -> []
| mid::rest ->
let (left, right) = List.partition ((<) mid) rest in
(qsort left) @ [mid] @ (qsort right)
let example_list = [17; 35; 32; 8; -14]
let example6 = qsort example_list
(* a better version that lets the user pass in an
arbitrary comparison to use for sorting: *)
(* returns l sorted according to greater_than *)
let rec qsort greater_than l = match l with
| [] -> []
| mid::rest ->
let left, right = List.partition (greater_than mid) rest in
(qsort greater_than left) @ [mid] @ (qsort greater_than right)
let qsort_increasing = qsort (>)
let qsort_decreasing = qsort (<)
let qsort_abs_sin = qsort (fun x y -> abs_float (sin x) < abs_float (sin y))
let example7 = qsort_increasing example_list
let example8 = qsort_decreasing example_list
(* an even better version, because we don't have to write it ourselves: *)
let qsort = List.sort