I'm trying to write a program for subtree(S,T) where S is a subtree of T.
This is my program, unfortunately it doesn't work and I don't know why. I'm very much a newbie in Prolog, so be gentle please.
subtree(T,T).
subtree(S,tree(X,left,right)) :-
subtree(S,left).
subtree(S,tree(X,left,right)) :-
subtree(S,right).
subtree(tree(X,void,void),tree(X,left,right)).
subtree(tree(X,S_left,S_right),tree(X_left,right)) :-
subtree(S_left,X_left),
subtree(S_right,X_right).
The first two rules are for finding subtrees that range to the leafs of the tree. The last two rules are supposed to find subtrees that do not range to the leafs.
If I e.g. call
subtree(tree(one,void,void),tree(one,tree(two,void,void),tree(three,void,void))).
Prolog returns false and I don't know why, doesn't this rule:
subtree(tree(X,void,void),tree(X,left,right)).
capture exactly that query?
subtree(tree(one,void,void),tree(one,tree(two,void,void),tree(three,void,void))).fails becausetree(one, void, void)is not a subtree oftree(one,tree(two,void,void),tree(three,void,void)). And what do the atomsleftandrightmean? Are they the values for leaf nodes? I would expect a leaf node to look like,tree(X, void, void)whereXis the value of the node. You don't have a consistent definition of what a tree structure looks like. Can you sort that out first and explain what a valid tree looks like? Once that's nailed down, it will be easier to create a correct predicate. - lurkerleftandrightwhich are not trees but atoms. So it's unclear what you're trying to express as a tree structure. For example, what does the clause,subtree(S,tree(X,left,right)) :- subtree(S,left).mean? What does the termtree(X, left, right)mean in your definition of tree versustree(X, void, void)? Atoms can't have values. - lurkerleftandrightto be variables? If so, they need to start with a capital letter. - lurker