Ocaml 未能在已排序树列表中插入树
我正在尝试使用以下代码在已排序的树列表中插入一棵树:Ocaml 未能在已排序树列表中插入树,ocaml,sortedlist,Ocaml,Sortedlist,我正在尝试使用以下代码在已排序的树列表中插入一棵树: exception NilTree;; type hTree = Nil | Node of char * int * hTree * hTree;; let rec printTree t = match t with | Nil -> () | Node(c, w, l, r) -> print_char c ; print_int w ; printTree l ; printTree r;; let r
exception NilTree;;
type hTree = Nil | Node of char * int * hTree * hTree;;
let rec printTree t = match t with
| Nil -> ()
| Node(c, w, l, r) -> print_char c ; print_int w ; printTree l ; printTree r;;
let rec printTreeList l = match l with
| [] -> ()
| h::t -> print_newline (printTree h) ; printTreeList t;;
let insertree l tree =
let rec insertree' l tree prev = match tree with
| Nil -> raise NilTree
| Node(c, w, left, right) -> match l with
| [] -> prev@[tree]
| h::t -> match h with
| Nil -> raise NilTree
| Node(c', w', left', right') ->
if w <= w' then
prev@[tree]@[h]@t
else
insertree' t tree prev@[h]
in insertree' l tree [];;
let tree1 = insertree [Node('a', 3, Nil, Nil)] (Node('b', 5, Nil, Nil));;
printTreeList tree1;;
你的陈述
insertree' t tree prev@[h]
实际上被解释为
(insertree' t tree prev) @ [h]
因为函数应用程序的绑定比运算符强。所以你需要把它改写成
insertree' t tree (prev @ [h])
谢谢!您是printTree中的佼佼者,您不想先打印左子树,然后打印当前节点,然后打印右子树吗?
insertree' t tree (prev @ [h])