算术计算机 [英] arithmetic computer

查看:59
本文介绍了算术计算机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些 prolog 方面的帮助,这对我来说很新.我必须设计一台小型算术计算机.要计算的表达式将表示为一个列表,例如:

I need some help in prolog, which is pretty new to me. I have to design a small arithmetic computer. The expression to be evaluated will be represented as a list for example:

?-evaluate([2,+,4,*,5,+,1,*,2,*,3],R).

我试图通过设计两个谓词来实现这一点,一个称为 parse 的谓词来转换我的列表,例如:

I am trying to do this by designing two predicates one called parse to transform my list for example:

?-parse([1,+,2,*,3],PF).
PF=[+,1,[*,2,3]]

和另一个来评估新表达式.

and another one to evaluate the new expression.

?-evpf([+,1,[*,2,3]],R).
R=7

第一部分有问题,谁能帮我写代码?

I have problems with the first part, can anyone help my with the code?

推荐答案

使用 DCG 可以轻松解析(= 将列表转换为抽象语法树):

Parsing (= converting a list to an abstract syntax tree) is easy with DCGs:

list_ast(Ls, AST) :- phrase(expression(AST), Ls).

expression(E)       --> term(T), expression_r(T, E).

expression_r(E0, E) --> [+], term(T), expression_r(E0+T, E).
expression_r(E0, E) --> [-], term(T), expression_r(E0-T, E).
expression_r(E, E)  --> [].

term(T)       --> power(P), term_r(P, T).
term_r(T0, T) --> [*], power(P), term_r(T0*P, T).
term_r(T0, T) --> [/], power(P), term_r(T0/P, T).
term_r(T, T)  --> [].

power(P)          --> factor(F), power_r(F, P).
power_r(P0, P0^P) --> [^], factor(P1), power_r(P1, P).
power_r(P, P)     --> [].

factor(N) --> [N], { number(N) }.
factor(E) --> ['('], expression(E), [')'].

要实际计算表达式,您可以使用内置谓词 is/2.示例查询:

To actually evaluate the expression, you can then use the built-in predicate is/2. Sample query:

?- list_ast([2,+,4,+,5,+,1,+,2,*,3], Ast), V is Ast.
Ast = 2+4+5+1+2*3,
V = 18 ;
false.

这篇关于算术计算机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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