I have this Prolog predicate for PreOrder traversal of a tree:
preOrder(nil, []).
preOrder(node(X, nil, nil), [X]).
preOrder(node(X, L, _), [X|T]) :- preOrder(L, T).
preOrder(node(X, _, R), [X|T]) :- preOrder(R, T).
The problem is, it returns an incomplete list. For example, I get:
?- preOrder(node(1, node(2, node(3,nil,nil), node(4,nil,nil)), node(5,nil,nil)), L).
L = [1,2,3]
When it should be L=[1,2,3,4,5]
.
Why is it stopping short?
Look at the answers Prolog produces. It's not a single one:
Each of your rules describes some part independently of the others. But you need to describe them all together.
The best way to solve this is to use DCGs