我试图为树的每个元素分配一个数字。我认为使用refs
会使任务更容易,但我遇到了一个奇怪的行为:分配的数字并不是唯一的,也没有出现明确的模式。我设法修复了这个错误(添加let unboxed = !second_ref in
行),但我不明白发生了什么。
输出控制台中的第一个树只是确保print_tree
函数输出它应该的内容。
但是,第二次打印所需的输出应与第三次打印完全相同。我错过了什么?
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 ;
输出如下:
-----------
| -----------
| | -> 3
| 2
| | -> 4
| -----------
1
| -----------
| | -> 6
| 5
| | -> 7
| -----------
-----------
-----------
| -----------
| | -> 7
| 7
| | -> 6
| -----------
7
| -----------
| | -> 4
| 4
| | -> 3
| -----------
-----------
-----------
| -----------
| | -> 7
| 5
| | -> 6
| -----------
1
| -----------
| | -> 4
| 2
| | -> 3
| -----------
-----------
答案 0 :(得分:6)
在bug
函数中,出现了这个有问题的表达式:
Node(!first_ref, bug l, bug r)
它的行为取决于参数的评估顺序:bug l
和bug r
增量first_ref
,因此传递的值可能不是您想要的。
您可以通过以下方式强制执行订单:
let v = !first ref in
let new_l = bug l in
let new_r = bug r in
Node (v, new_l, new_r)