failing to insert a tree in a sorted treelist

65 views Asked by At

I am trying to insert a tree in a sorted tree list with the following code :

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;;

the trees have four fields, and a tree with a smaller int should be placed before the others, but here is what I get :

b5
a3
1

There are 1 answers

0
ivg On

your statement

insertree' t tree prev@[h]

is actually interpreted as

(insertree' t tree prev) @ [h]

because function applications bind stronger than operators. So you need to rewrite this as,

insertree' t tree (prev @ [h])