diff --git a/labs/07/exp.ml b/labs/07/exp.ml new file mode 100644 index 0000000..c1ad378 --- /dev/null +++ b/labs/07/exp.ml @@ -0,0 +1,28 @@ +type 'a lazystream = Cons of 'a * 'a lazystream Lazy.t + +let rec from n = Cons (n, lazy (from (n +. 1.))) + +let rec take n (Cons (h, t)) = + if n <= 0 then [] + else h :: take (n - 1) (Lazy.force t) + +let rec map f (Cons (h, t)) = + Cons (f h, lazy (map f (Lazy.force t))) + +let fact n = + let rec fact' acc i = + if i = 0. then acc + else fact' (i *. acc) (i -. 1.) + in + fact' 1. n;; + +let rec fold_left f acc l = + match l with + | [] -> acc + | a :: l' -> fold_left f (f acc a) l';; + +let exp_terms x = map (fun n -> (x**n) /. (fact n)) @@ from 0.;; + +let exp n x = fold_left (+.) 0. (take n @@ exp_terms x);; + +exp 20 1.1;; diff --git a/labs/07/primes.ml b/labs/07/primes.ml new file mode 100644 index 0000000..4bef51f --- /dev/null +++ b/labs/07/primes.ml @@ -0,0 +1,21 @@ +type 'a infstream = Cons of 'a * (unit -> 'a infstream) + +let rec take n (Cons (h, t)) = + if n <= 0 then [] + else h :: take (n - 1) (t ()) + +let rec from n = Cons (n, fun () -> from (n + 1)) + +let rec filter f (Cons (h, t)) = + if f h then Cons (h, fun () -> filter f (t ())) + else filter f (t ()) + +let primes = + let rec sieve (Cons (h, t)) = + Cons (h, fun () -> + sieve (filter (fun x -> x mod h <> 0) (t ())) + ) + in + sieve @@ from 2;; + +take 100 primes;;