问题
Good Day,
I am trying to write a Prolog program that given a tree with a functor of a:
start(a(f,2,9), X).
I want it to square any values inside so that it yields:
X = a(f,4,81).
I have code that squares numbers in a list already that works. Here's what I have so far:
start([],[]).
start(Tree, []) :- Tree =.. [P|C], write(P), nl, write(C), nl, squareMe([P|C], []).
squareMe([X|T], [Y|Result]) :- % I think the problem is here
atom(X),
Y=X,
squareMe(T, Result).
squareMe([X|T], [Y|Result]) :-
number(X),
Y is X * X,
squareMe(T, Result).
squareMe([], []).
when the code writes P and C, I do get the correct values via the UNIV operator, but it seems to be failing inside squareMe.
When I invoke squareMe([P|C], []), my understanding is the P = a and C = [f, 2, 9]. So shouldn't atom(a) be true? It doesn't appear to be the case and I'm not sure why?
I've tried using trace/notrace to track my path, but it would sure be nice to see the values that were passed into squareMe. Is that possible? I'm using SWI-Prolog.
TIA, coson
回答1:
This is an answer instead of a comment only because it is too long; I don't fully understand your question though.
To get the solution to the query you show at the top, it would be enough to write:
start(a(f, X, Y), a(f, XX, YY)) :-
XX is X*X,
YY is Y*Y.
That's it:
?- start(a(f, 2, 9), X).
X = a(f, 4, 81).
This is way too easy, and more importantly, I don't see any tree structure here, which is why I am certain I am misunderstanding the question. I definitely have trouble following the code you have shown. You should edit your question to explain:
- where is the tree structure you are traversing?
- are you using lists, flat terms, nested terms (a tree?)
- does your predicate have to work both ways, so, should you be able to ask:
?- start(X, Y).
for example.
来源:https://stackoverflow.com/questions/40700921/prolog-tree-traversal