[英]Ocaml Tree simple functions
我創造了一棵樹
type 'a tree = {
mutable cont: 'a;
mutable left: 'a bin_tree;
mutable right: 'a bin_tree
}
and 'a bin_tree =
Empty
| Node of 'a tree;;
我正在努力處理一些簡單的功能,例如
我用谷歌搜索了我的問題,但我不斷出錯。 例如:
let rec insert x tree =
match tree with
Empty -> Node(x, Empty, Empty)
| Node(y, left, right) ->
if x <= y then Node(y, insert x left, right)
else Node(y, left, insert x right)
或者,如果我嘗試:
let rec insert x = function
Empty -> Node(Empty, x, Empty)
| Node(lb, r, rb) -> if x < r then Node(insert x lb, r, rb)
else Node{lb; r; insert x rb} ;;
我不斷收到語法錯誤。
為什么為樹使用可變記錄? OCaml程序員更喜歡使用不可變的數據結構。 在這里,樹的可變性不會提高復雜性,但會引入錯誤。
以下是以持久方式實現樹的方法:
type 'a tree =
| Empty
| Node of 'a * 'a tree * 'a tree
實際上,您在代碼中為member
和insert
使用的就是這種類型。
您的匹配模式應包含{
和}
以匹配記錄,因此代碼
match tree with
Empty -> false
| Node { cont=x; left=l; right=r } -> (*something here .... *)
實際上,當模式變量具有與字段相同的名稱時, 用於記錄表示法的語言擴展允許避免使用字段標簽,因此,無需編碼模式Node { cont=cont; left=left; right=right }
Node { cont=cont; left=left; right=right }
Node { cont=cont; left=left; right=right }
您可以編寫Node{cont;left;right}
您也可以查看Ocaml的stdlib / set.ml源文件。
注意,您的'a bin_tree
類型幾乎等同於'a tree option
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.