(** Uncurried functions * Exercise *) let addp (x,y) = x + y let choose (a,b,c) = a < b + c let t1 = choose (1,1,1) let t2 = choose (2,1,1) let t3 = choose (3,1,1) (** Curried functions * Exercise *) let choose a b c = a < b + c let pmul1 a b = (a+b, a*b) let pmul2 (a,b) = (a+b, a*b) let (u,v) = pmul1 30 40 (** Lambdas *) let f = (fun (x,y,z) -> x - y * z) let (mul2, mul3) = ((fun x -> x * 2), (fun x -> x * 3)) (** Polymorphism *) let mk_list a b = [ a ; b ] (* mk_list is less polymorphic than mk_pair because all elements of a list must have the same type. *) (** Exercise : Recursive functions *) let rec count_ones = function | [] -> 0 | x :: rest -> (if x = 1 then 1 else 0) + count_ones rest (* With an accumulator *) let rec count_onesaq cnt = function | [] -> cnt | x :: rest -> count_onesaq (if x = 1 then cnt + 1 else cnt) rest let rec sum = function | [] -> 0 | x :: rest -> x + sum rest let rec perms = function | [] -> [] | (x,y) :: rest -> (y,x) :: perms rest (* With an accumulator *) let rec sumaq acu = function | [] -> acu | x :: rest -> sumaq (acu + x) rest (** Exercise : Test tail-recursion *) let rec mk_list n = if n <= 0 then [] else n :: mk_list (n-1) let rec mk_aculist acu n = if n <= 0 then acu else mk_aculist (n :: acu) (n-1) (** Exercise : Higher-order functions *) let rec fsumlist f = function | [] -> 0 | x :: rest -> f x + fsumlist f rest (* With an accumulator *) let rec fsumlist' acu f = function | [] -> acu | x :: rest -> fsumlist' (acu + f x) f rest let test1 = fsumlist int_of_string [ "10" ; "20" ; "30" ] let test2 = fsumlist' 0 int_of_string [ "10" ; "20" ; "30" ] let test3 = fsumlist int_of_float [ 1.1 ; 2.1 ; 3.2 ] let test4 = fsumlist' 0 int_of_float [ 1.1 ; 2.1 ; 3.2 ] (** Exercise : Classical higher-order, polymorphic functions *) let rec map f = function | [] -> [] | x :: rest -> f x :: map f rest let rec find f = function | [] -> raise Not_found | x :: rest -> if f x then x else find f rest let omap f = function | None -> None | Some x -> Some (f x)