序言树遍历 [英] Prolog Tree Traversal
问题描述
美好的一天,
我正在尝试编写一个Prolog程序,该程序给出了一个带有a的函子的树:
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([], []).
当代码写P和C时,我确实通过UNIV运算符获得了正确的值,但是
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.
当我调用squareMe([P | C],[])时,我的理解是P = a和C = [f, 2、9]。那么atom(a)不应该是真的吗?似乎并非如此,我不确定为什么吗?
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?
我已经尝试过使用trace / notrace跟踪我的路径,但是肯定会很高兴看到传递给squareMe的值。那可能吗?我正在使用SWI-Prolog。
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,
子孙
TIA, coson
推荐答案
这是答案,而不是评论,只是因为它太长;我还是不完全理解您的问题。
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.
就是这样:
?- 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:
- 您要遍历的树结构在哪里?
- 您是否在使用列表,平面术语,嵌套术语(一棵树?)
- 您的谓词必须同时使用两种方法,所以,您应该能够问:
?-start(X,Y)。
。例如
- 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.
这篇关于序言树遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!