(* we started with some basic variable definitions and a simple function *) let x = 3 let y = x * 7 + 2 let f(n) = 2 * n (* we don't generally specify types because OCaml does type inferencing *) let sqr(n) = n * n (* int version because of * *) let sqr(n) = n *. n (* float version because of *. *) (* I pointed out that sometimes OCaml doesn't know the specific type *) let switch(a, b) = (a, b) (* You can specify a specific type in lots of different ways *) let switch((a : int), (b : int)) = (b, a) let switch(a, b) : int * int = (b, a) let switch(a, b) = ((b, a) : int * int) (* we wrote a min function using an if/else expression *) let min(x, y) = if x < y then x else y (* Then we defined a recursive function which required "let rec" *) let rec factorial(n) = if n < 0 then invalid_arg("negative factorial") else if n = 0 then 1 else n * factorial(n - 1) (* example of building up a list with the :: operator known as "cons" *) let lst = 45::2::5::7::[] (* recursive function to produce a new list with each value incremented *) let rec inc_all(lst) = if lst = [] then [] else (List.hd(lst) + 1)::inc_all(List.tl(lst)) (* recursive function to return the last value in a nonempty list *) let rec last(lst) = if lst = [] then invalid_arg("empty list") else if List.length(lst) = 1 then List.hd(lst) else last(List.tl(lst)) (* data in the form of tuples with last name and first name *) let test = [("Clinton", "Hillary"); ("Obama", "Barak"); ("Biden", "Joe")] (* helper function to convert a tuple to a name in first/last format *) let combine(last, first) = first ^ " " ^ last (* recursive function to return new list with string tuples converted *) let rec convert(lst) = if lst = [] then [] else combine(List.hd(lst))::convert(List.tl(lst))