未能在已排序的树形图中插入树

时间:2014-11-27 14:51:32

标签: 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 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;;

树有四个字段,一个小int的树应放在其他字段之前, 但这是我得到的:

b5
a3

1 个答案:

答案 0 :(得分:1)

你的陈述

insertree' t tree prev@[h]

实际上被解释为

(insertree' t tree prev) @ [h]

因为函数应用程序绑定比运算符强。所以你需要将其重写为,

insertree' t tree (prev @ [h])