(** Basic pattern matching *) let f1 x = match x with | true -> 0 | false -> 1 let f2 s = match s with | "aa" -> 1 | "bb" -> 2 | "cc" -> 3 | _ -> 0 (* Calc, curried *) let calc x y op = match (y, op) with | (_, "add") -> x + y | (_, "sub") -> x - y | (_, "mul") -> x * y | (0, "div") -> failwith "Division by zero." | (_, "div") -> x / y | _ -> failwith "Unknown operator." (** Exercise : Basic pattern-matching *) let xor a b = match (a,b) with | false, false -> false | true, true -> false | false, true -> true | true, false -> true type operation = Add | Sub | Mul | Div let calc x y op = match (y, op) with | (_, Add) -> x + y | (_, Sub) -> x - y | (_, Mul) -> x * y | (0, Div) -> failwith "Division by zero." | (_, Div) -> x / y let test = calc 4 5 Mul (** Exercise : Sequence *) let show f v = Printf.printf "Function called with value %d\n%!" v ; f v let pshow cv f v = Printf.printf "Function called with value %s\n%!" (cv v) ; f v (** Exercise : Inner let *) (* All five functions are equivalent. *) let get_triple arg = match arg with | (a, p) -> begin match p with | (b,c) -> [ a ; b ; c ] end let get_triple (a, (b, c)) = [ a ; b ; c ] (** Exercise : Expressions *) let fancy1 x = begin if x = 0 then (fun a b -> a + b ) else (fun a b -> x) end (x-1) (x+1) let fancy2 a b c = "Hello " ^ let f = if a then match c with | [] -> (fun x -> string_of_int x) | _ -> (function 4 -> "FOUR" | _ -> "NOT FOUR") else (fun _ -> "ZERO") in f b