I was trying to assign a number to each element of a tree. I thought using refs
would make the task easier, but I encountered a strange behavior : the numbers assigned were not unique and no clear pattern emerged. I managed to fix the bug (adding the let unboxed = !second_ref in
line) but I do not understand what happened.
The first tree in the output console just makes sure the print_tree
function outputs what it should.
However, the output expected for the second print should be exactly the same one as the third tree. What am I missing ?
type ('a, 'b) tree =
| Node of 'a * ('a, 'b) tree * ('a, 'b) tree
| Leaf of 'b
let print_tree tree string_of_node string_of_leaf =
let rec print indent tree =
match tree with
| Leaf (l) -> print_string (indent^" -> "^string_of_leaf(l)^"\n")
| Node (n, left, right) ->
Printf.printf "%s-----------\n" indent;
print (indent ^ "| ") left;
Printf.printf "%s%s\n" indent (string_of_node(n));
print (indent ^ "| ") right;
Printf.printf "%s-----------\n" indent
in print "" tree
let myTree = Node(1,Node(2,Leaf(3),Leaf(4)),Node(5,Leaf(6),Leaf(7))) ;;
let first_ref = ref 0 ;;
let rec bug tree =
first_ref := !first_ref+ 1;
match tree with
|Leaf(a) -> Leaf(!first_ref)
|Node(n,l,r) -> Node(!first_ref, bug l, bug r) ;;
let second_ref = ref 0 ;;
let rec bug_fixed tree =
second_ref := !second_ref + 1;
let unboxed = !second_ref in
match tree with
|Leaf(a) -> Leaf(unboxed)
|Node(n,l,r) -> Node(unboxed, bug_fixed l, bug_fixed r) ;;
let bug_tree = bug myTree ;;
let bug_fixed_tree = bug_fixed myTree ;;
print_tree myTree string_of_int string_of_int ;
print_tree bug_tree string_of_int string_of_int ;
print_tree bug_fixed_tree string_of_int string_of_int ;
The output is the following :
-----------
| -----------
| | -> 3
| 2
| | -> 4
| -----------
1
| -----------
| | -> 6
| 5
| | -> 7
| -----------
-----------
-----------
| -----------
| | -> 7
| 7
| | -> 6
| -----------
7
| -----------
| | -> 4
| 4
| | -> 3
| -----------
-----------
-----------
| -----------
| | -> 7
| 5
| | -> 6
| -----------
1
| -----------
| | -> 4
| 2
| | -> 3
| -----------
-----------
In your bug
function, there's this problematic expression:
Node(!first_ref, bug l, bug r)
Its behaviour depends on the order of evaluation of the arguments: bug l
and bug r
increment first_ref
, so the value that is passed may not be what you want.
You can force the order by doing for example:
let v = !first ref in
let new_l = bug l in
let new_r = bug r in
Node (v, new_l, new_r)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.