Arithmetic computer

I need help in the prologue, which is quite new to me. I have to develop a small arithmetic computer. The expression to be evaluated will be presented in a list, for example:

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

I am trying to do this by creating two predicates, one of which is called parse to convert my list, for example:

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

and the other to evaluate the new expression.

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

I have problems with the first part, can someone help me with the code?

+1
source share
1 answer

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

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 really evaluate the expression, you can use the built-in predicate: / 2. Request example:

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

All Articles