I am studying binary tree in Prolog and I have some problem to add leaves to a specific b-tree.
I have the following predicates that add a single leaf to a b-tree:
addLeaf(nil, X, t(nil, X, nil)).
addLeaf(t(Left, X, Right), X, t(Left, X, Right)).
addLeaf(t(Left, Root, Right), X, t(Left1, Root, Right)) :-
gt(Root, X), addLeaf(Left, X, Left1).
addLeaf(t(Left, Root, Right), X, t(Left, Root, Right1)) :-
gt(X, Root), addLeaf(Right, X, Right1).
gt(Element1, Element2) :- Element1 @> Element2.
This is pretty simple and I think that I have not problem with it.
My problem is related about to use it to perform query that add more then a single leaf to a bin tree,
For example if, in the Prolog shell, I perform the following statement:
[debug] ?- addLeaf(nil, 6, Tree).
Tree = t(nil, 6, nil).
the original tree is nil (there is no tree), so add a new leaf is equivalent to create a new tree (called Tree) that have the element 6 as root.
Now my problem is: "I have create a new tree, that corresponds to the Tree variable, what have I to do to add others leaves to this tree?"
Because, if now I try to perform the following statement:
[debug] ?- addLeaf(Tree, 6, NewTree).
Tree = nil,
NewTree = t(nil, 6, nil)
I obtain that Tree = nill (also if I had just created it in the previous statement. Evidently the Tree variable (in the two statement) are independent of each other, evidently the variables are independent of each other.
So I try to perform:
[debug] ?- addLeaf(nil, 6, Tree), addLeaf(Tree, 8, NewTree).
Tree = t(nil, 6, nil),
NewTree = t(nil, 6, t(nil, 8, nil)).
and it work fine adding the 8 element as the right child of 6 (according to the b-tree rules)
But, I am asking if, in the Prolog shell, is it possible do something this:
create new tree.
add a leaf.
add another leaf.
add another leaf.
...
...
without declare all the operation in an unique statement, some idea about it?
assert
. - Usert
in the 3rd arg of the 3rd clause ofaddLeaf
. - Will Ness