user1137267
user1137267

Reputation:

arithmetic computer

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).

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?

Upvotes: 1

Views: 1093

Answers (1)

mat
mat

Reputation: 40768

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), [')'].

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.

Upvotes: 3

Related Questions