在 Prolog 中创建表达式树列表
让我们考虑以下 prolog 代码,它允许我形成表达式树:
plus(_,_).
eval(A, A) :- number(A).
eval(plus(A, B), R) :- eval(A, A_R), eval(B, B_R), R is A_R+B_R.
我可以通过以下方式轻松定义和评估表达式树:
eval(plus(1,2), R).
其计算结果为
R=3
某些语言允许我们构建表达式树,然后将它们分配给变量,以便稍后可以使用它们用过的。在伪代码中:
my_expr = plus(plus(1, 2), 3)
我想知道使用我当前的树表示是否能够实现类似的结果?我想要一个列表,每个节点中都有不同的表达式树。类似的东西
[ plus(1, 2), plus(3,plus(2,1)), 3 ]
Let's consider the following prolog code that allows me to form expression trees:
plus(_,_).
eval(A, A) :- number(A).
eval(plus(A, B), R) :- eval(A, A_R), eval(B, B_R), R is A_R+B_R.
I can easily define and evaluate expression trees the following way:
eval(plus(1,2), R).
which evaluates to
R=3
Some languages allows us to build expression trees and then assign them to a variable, so they can be later used. In pseudo-code:
my_expr = plus(plus(1, 2), 3)
I'm wondering whether with my current tree representation I'm capable of achieving a similar result? I'd want to have a list with a different expression tree in each node. Something along the lines of
[ plus(1, 2), plus(3,plus(2,1)), 3 ]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于您的示例,
您不能这样做,因为 = 的左侧和右侧不匹配。如果 my_expr 是一个变量(大写),则这将是 true 并且会导致 my_expr 绑定到树 plus(plus(1, 2), 3)。检查一下 -
My_expr 是一个完全合法的结构,您可以将其放入列表或调用下游表达式。
For your example
You cannot do that b/c the left hand and right hand side of the = do not match. If my_expr was a variable (uppercase), this would be true and would cause my_expr to be bound to the tree plus(plus(1, 2), 3). Check this out -
My_expr is a perfectly legitimate structure for you to put into a list or call a downstream expression with.