Skip to content

Instantly share code, notes, and snippets.

@JoranHonig
Created November 27, 2018 22:58
Show Gist options
  • Save JoranHonig/4923fefd3a1e8c8342b1b75007f8a3ef to your computer and use it in GitHub Desktop.
Save JoranHonig/4923fefd3a1e8c8342b1b75007f8a3ef to your computer and use it in GitHub Desktop.
let print_list f l =
print_char '[';
begin
match l with
[] -> ()
| hd :: tl ->
print_string (f hd);
List.iter (fun x -> print_string (", " ^ (f x))) tl
end;
print_char ']';;
let print_int_list l = print_list (string_of_int) l;;
type 'a stream =
Cons of 'a * (unit -> 'a stream);;
let rec from n = Cons (n, fun () -> from (n+1));;
let hd (Cons (h, _)) = h
let tl (Cons (_, tf)) = tf ()
let rec filter f (Cons (h, tf)) =
if (f h) then Cons(h, fun () -> filter f (tf ()))
else filter (f) (tf ())
;;
let rec take n s =
if n=0 then []
else hd s :: take (n-1) (tl s);;
let rec sum (Cons(h1, tf1)) (Cons(h2, tf2)) =
Cons(h1 + h2, fun () -> sum (tf1()) (tf2()));;
let rec square (Cons(h, tf)) = Cons(h*h, fun () -> square (tf ()));;
let rec primes sum xs =
let x = hd xs in
if sum > 4000000 then []
else x ::
(
primes (sum + x) (filter (fun p -> (p mod x) <> 0) (tl xs))
)
let rec fibs =
Cons(1, fun () ->
Cons(1, fun () ->
sum fibs (tl fibs)))
let () = print_int_list (primes 0 (from 2)); print_newline ();;
let () = print_int_list (take 10 fibs); print_newline ();;
let () = print_int_list
(take 10
(
filter (fun x -> (x mod 3) = 0) (from 1)
)
);;
let () = print_newline ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment