The correct way to build a Binary Search Tree in OCaml

女生的网名这么多〃 提交于 2019-12-08 21:05:36

Look at the accepted answer to the linked question. To be specific this line here:

let tree_of_list l = List.fold_right insert l Leaf

Work out the chain of what is happening. Take the list 1,2,3.

First we have no tree and the result of insert 1 Leaf.

call this T1

Next is the tree generated by insert 2 T1

call this T2

Then the tree generated by insert 3 T2

This is what is returned as the result of Tree_of_list.

If we call the result T3 then somewhere else in code call insert 4 T3 there is no difference in the result returned from insert than in calling Tree_of_list with the list 1,2,3,4.

I'll try to answer the sharing part of your question. The short answer is yes, the two parts of the two trees will be identical. The reason immutable data works so well is that there are no limitations on the possible sharing. That's why FP works so well.

Here's a session that does what you describe:

# let t1 = Node (10, Leaf, Leaf);;
val t1 : int bstree = Node (10, Leaf, Leaf)
# let t2 = insert 5 t1;;
val t2 : int bstree = Node (10, Node (5, Leaf, Leaf), Leaf)
# let t3 = insert 12 t2;;
val t3 : int bstree = Node (10, Node (5, Leaf, Leaf), Node (12, Leaf, Leaf))
# let Node (_, c1, _) = t2;;
val c1 : int bstree = Node (5, Leaf, Leaf)
# let Node (_, c2, _) = t3;;
val c2 : int bstree = Node (5, Leaf, Leaf)
# c1 == c2;;
- : bool = true

The long answer is that there's no guarantee that the two parts will be identical. If the compiler and/or runtime can see a reason to copy a subtree, it's also free to do that. There are cases (as in distributed processing) where that would be a better choice. Again the great thing about FP is that there are no limitations on sharing, which means that sharing is neither required nor forbidden in such cases.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!