type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree let rec map (f:'a -> 'b) (t:'a tree) : 'b tree = match t with Leaf -> Leaf | Node (x, left, right) -> let left' = map f left in let right' = map f right in Node (f x, left', right') ;; let rec parallel_map (f:'a -> 'b) (t:'a tree) : 'b tree = match t with Leaf -> Leaf | Node (x, left, right) -> let left' = Future.future (parallel_map f) left in let right' = parallel_map f right in Node (f x, Future.force left', right') ;; let make_tree (top:int) : int tree = let rec aux (high:int) (low:int) : int tree = if high < low then Leaf else let mid = low + (high-low) / 2 in Node(mid, aux high (mid+1), aux (mid-1) low) in aux top 0 ;; let parallel_make_tree (top:int) : int tree = let rec aux (high:int) (low:int) : int tree = if high < low then Leaf else let mid = low + (high-low) / 2 in let left_f = Future.future (aux high) (mid+1) in let right' = aux (mid-1) low in Node(mid, Future.force left_f, right') in aux top 0 ;; let rec print_tree (t:int tree) : unit = let rec spaces i = if i <= 0 then "" else " " ^ spaces (i-1) in let rec aux (t:int tree) (indent:string) : unit = match t with Leaf -> () | Node (n,left, right) -> print_string indent; print_int n; print_newline(); aux left (" "^indent); aux right (" "^indent) in aux t "" ;; let main () = Printf.printf "\nIt is easy to transform effect-free sequential code\n"; Printf.printf "in to equivalent concurrent code that uses futures.\n"; Printf.printf "You should observe no difference between what the code\n"; Printf.printf "that uses futures computes and what the code\n"; Printf.printf "that does not use futures computes.\n\n"; Printf.printf "Note we are going to print out results of our computation,\n"; Printf.printf "but the printing code is sequential and comes after\n"; Printf.printf "the parallel code has completed so there is no\n"; Printf.printf "non-determinism.\n"; Printf.printf "\nWithout futures:\n\n"; print_tree (map (fun x -> x*2) (make_tree 16)); Printf.printf "\nWith futures:\n\n"; print_tree (parallel_map (fun x -> x*2) (parallel_make_tree 16)) ;; main();;