From 228c86f52331b1fd0a68f511dd2f96e88460b2b8 Mon Sep 17 00:00:00 2001 From: Score_Under Date: Tue, 25 Apr 2023 01:47:35 +0100 Subject: [PATCH 1/2] Remove superfluous flush of stdout --- bench/algorithm/binarytrees/1.ml | 1 - 1 file changed, 1 deletion(-) diff --git a/bench/algorithm/binarytrees/1.ml b/bench/algorithm/binarytrees/1.ml index c11c42801..2357d75ee 100644 --- a/bench/algorithm/binarytrees/1.ml +++ b/bench/algorithm/binarytrees/1.ml @@ -42,7 +42,6 @@ let loop_depths d = done let () = - flush stdout; loop_depths min_depth; Printf.printf "long lived tree of depth %i\t check: %i\n" max_depth long_lived_tree#check From a38b9f87b93f71510e10fc3ec1ac42840c9a7881 Mon Sep 17 00:00:00 2001 From: Score_Under Date: Tue, 25 Apr 2023 03:09:58 +0100 Subject: [PATCH 2/2] Use a module instead of a class for node structure This is a little more idiomatic as far as I can tell, and greatly speeds the code up. --- bench/algorithm/binarytrees/1.ml | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/bench/algorithm/binarytrees/1.ml b/bench/algorithm/binarytrees/1.ml index 2357d75ee..604416a37 100644 --- a/bench/algorithm/binarytrees/1.ml +++ b/bench/algorithm/binarytrees/1.ml @@ -1,20 +1,19 @@ -class node left' right' = - object - val left : node option = left' +module Node = struct + type t = { left : t option; right : t option } - val right : node option = right' + let create left right = { left; right } - method check = - 1 - + (match left with None -> 0 | Some l -> l#check) - + match right with None -> 0 | Some r -> r#check - end + let rec check node = + 1 + + (match node.left with None -> 0 | Some l -> check l) + + match node.right with None -> 0 | Some r -> check r +end let rec make d = - if d = 0 then new node None None + if d = 0 then Node.create None None else let d = d - 1 in - new node (Some (make d)) (Some (make d)) + Node.create (Some (make d)) (Some (make d)) let min_depth = 4 @@ -25,7 +24,7 @@ let max_depth = let stretch_depth = max_depth + 1 let () = - let c = (make stretch_depth)#check in + let c = Node.check @@ make stretch_depth in Printf.printf "stretch tree of depth %i\t check: %i\n" stretch_depth c let long_lived_tree = make max_depth @@ -36,7 +35,7 @@ let loop_depths d = let niter = 1 lsl (max_depth - d + min_depth) in let c = ref 0 in for _ = 1 to niter do - c := !c + (make d)#check + c := !c + Node.check (make d) done; Printf.printf "%i\t trees of depth %i\t check: %i\n" niter d !c done @@ -44,4 +43,4 @@ let loop_depths d = let () = loop_depths min_depth; Printf.printf "long lived tree of depth %i\t check: %i\n" max_depth - long_lived_tree#check + (Node.check long_lived_tree)