在Prolog中构建表达式树 [英] Building an Expression Tree in Prolog

查看:78
本文介绍了在Prolog中构建表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在Prolog中构建表达式树的方法.我已经做过一些实验,并提出了以下工作代码(仅处理常量和加号表达式):

I'm looking for a way to build an Expression Tree in Prolog. I already did some experiments and came up with the following working code (that will only handle constants and the plus expression):

const(_).
plus(_, _).

eval(const(R), R).

eval(plus(A, B), R) :- number(A), number(B), R is A+B.
eval(plus(A, B), R) :- number(A), eval(B, B_R), R is A+B_R.
eval(plus(A, B), R) :- eval(A, A_R), number(B), R is A_R+B.
eval(plus(A, B), R) :- eval(A, A_R), eval(B, B_R), R is A_R+B_R.

除了这种方法,还有其他更简单的选择吗?我是否需要为计划添加到程序中的每个运算符定义这4种情况?

Is there any simpler alternative to this approach? Will I have to define these 4 cases for each one of the operators I plan on adding to my program?

推荐答案

我认为应该这样做,尽管我对结构pred1(pred2(...)...) :- ...并不熟悉(我的Prolog非常生锈).

I think this should do it, though I'm not familiar with the construct pred1(pred2(...)...) :- ... (my Prolog is very rusty).

eval(A, A) :- number(A).
eval(plus(A, B), R) :- eval(A, A_R), eval(B, B_R), R is A_R+B_R.

这篇关于在Prolog中构建表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆