Skip to content

Instantly share code, notes, and snippets.

@Kakadu
Created August 24, 2020 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kakadu/41dd42fb318c81d7abbff95d19171f28 to your computer and use it in GitHub Desktop.
Save Kakadu/41dd42fb318c81d7abbff95d19171f28 to your computer and use it in GitHub Desktop.
cps vs non cps
module Tour.Functions
type tree = Leaf | Node of tree * tree
let rec make depth =
if depth <= 0 then Leaf
else
let r = make (depth - 1) in
let l = if depth % 100000 = 0 then r else Leaf in
Node (r, l)
let size root =
let rec helper tree =
match tree with Leaf -> 0 | Node (l, r) -> helper l + helper r + 1
in
helper root
let size_tail root =
let rec helper tree k =
match tree with
| Leaf -> k 0
| Node (l, r) ->
(helper ) l (fun sl ->
(helper ) r (fun sr -> k (sl + sr + 1)))
in
helper root (fun n -> n)
let main =
let n = 100000 in
printf "Tree: depth = %d, size = %d\n" n (size (make n));
(* Gives stack overflow *)
(* Format.printf "Tree: depth = %d, size_tail = %d\n%!" n (size (make n)); *)
(* WTF it gives stack overflow? *)
(* Format.printf "Tree: depth = %d, size_tail = %d\n%!" n (size_tail (make n)); *)
(* let n = 1000000 / 10 in *)
printf "loop\n";
for n = 1 to 1000 do
let i = n * 10_00 in
printf "Tree: depth = %d, size_tail = %d\n" i
(size_tail (make i));
printf "Tree: depth = %d, size = %d\n" i (size (make i))
done;
()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment