open Mp4common open List (* from MP3 *) let odd_sum_base = 0;; let odd_sum_rec x a = if abs(x mod 2) = 1 then (a + x) else a;; let count_element_base = 0;; let count_element_rec m a x = if (x = m) then (a + 1) else a;; let pair_sums_map l = List.map (fun (x, y) -> x + y) l;; let rec apply_even_odd l f g = match l with [] -> [] | x::xs -> (f x)::(apply_even_odd xs g f);; let notk b k = k (not b);; let inck i k = k (i + 1);; let print_intk i k = k (print_int i);; let neqk x y k = k (x <> y);; (* Problem 1 *) let divk n m k = k (n / m);; let modk n m k = k (n mod m);; let float_subk a b k = k (a -. b);; let float_mulk a b k = k (a *. b);; let catk str1 str2 k = k (str1 ^ str2) let consk e l k = k (e :: l);; let leqk x y k = k (x <= y);; let eqk x y k = k (x = y);; (* Problem 2 *) let addk n m k = k (n + m);; let poly x k = mulk x x (fun t1 -> mulk t1 t1 (fun t2 -> addk x 1 (fun t3 -> addk t3 t2 k)));; (* Problem 3 *) let distributek f g x y k = f x (fun t1 -> (f y) (fun t2 -> (g t1 t2) (fun t3 -> k t3)));; let negatek i k = k (-i);; let deck i k = k (i - 1);; let addk n m k = k (n + m);; (* Problem 4 *) let rec alternate_series n = if n <= 0 then 0 else (let n' = if n mod 2 <> 0 then -n else n in n' + alternate_series (n - 1));; let rec alternate_series' n = if n <= 0 then 0 else (let rec_res = alternate_series (n - 1) in let n' = if n mod 2 <> 0 then -n else n in n' + rec_res);; let rec alternate_series'' n = if n <= 0 then 0 else (if n mod 2 <> 0 then alternate_series (n - 1) - n else alternate_series (n - 1) + n);; let rec alternate_seriesk n k = leqk n 0 (fun t1 -> if t1 then k 0 else (modk n 2) (fun t2 -> neqk t2 0 (fun t3 -> if t3 then (negatek n) (fun t4 -> deck n (fun t5 -> alternate_seriesk t5 (fun t6 -> (addk t4 t6 k)))) else deck n (fun t8 -> alternate_seriesk t8 (fun t9 -> (addk n t9 k))))));; let rec alternate_seriesk' n k = leqk n 0 (fun t1 -> if t1 then (k 0) else (deck n) (fun t2 -> (alternate_seriesk' t2) (fun t3 -> (modk n 2) (fun t4 -> (neqk t4 0) (fun t5 -> if t5 then (negatek n) (fun t6 -> addk t6 t3 k) else (addk n t3 k))))));; (* Problem 5 *) let seqk a b k = k (a ; b);; let rec rev_iter f l = match l with | [] -> () | hd :: tl -> (rev_iter f tl); (f hd);; let rec rev_iterk f l k = match l with | [] -> k () | hd :: tl -> (rev_iterk f tl) (fun t1 -> (f hd) (fun t2 -> seqk t1 t2 k));; (* Problem 6 *) let rec filter l p = match l with | [] -> [] | hd :: tl -> let res = (filter tl p) in if (p hd) then hd :: res else res;; let rec filterk l p k = match l with | [] -> k [] | hd :: tl -> (filterk tl p) (fun t1 -> (p hd) (fun t2 -> if t2 then consk hd t1 k else k t1));; (* Problem 7 *) let eqk n m k = k (n = m);; let rec assock l p normalk exceptionk = match l with | [] -> exceptionk () | (fst, snd) :: tl -> (p fst) (fun t1 -> if t1 then (normalk snd) else (assock tl p normalk exceptionk)) ;; (* Problem 8 *) let rec appk l x k = match l with | [] -> k x | hd :: tl -> appk tl x (fun t -> hd t k) ;;