我試圖給一棵樹的每個元素分配一個數字。我認爲使用refs
會使任務更容易,但是我遇到了一個奇怪的行爲:分配的數字不是唯一的,並且沒有出現清晰的模式。我設法修復了這個bug(添加了let unboxed = !second_ref in
行),但我不明白髮生了什麼。OCaml,與refs和樹的意外行爲
輸出控制檯中的第一棵樹只是確保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
| -----------
-----------
這可能是題外話這裏,但你tree'讓我爲難的類型'的定義。葉子可能與節點有不同的類型? – RichouHunter