% nacteni:
/* ['12.6_23.pl']. */

expr(X) --> term(Y), [+], expr(Z), {X is Y+Z}.
expr(X) --> term(Y), [-], expr(Z), {X is Y-Z}.
expr(X) --> term(X).

term(X) --> factor(Y), [*], term(Z), {X is Y*Z}.
term(X) --> factor(Y), [/], term(Z), {X is Y/Z}.
term(X) --> factor(X).

factor(X) --> ['('], expr(X), [')'].
factor(X) --> [X], {integer(X)}.

% demonstracni vypis

:- dynamic
       write_all_X/3,
       start/0.
       
write_all_X(Goal,X,Name):-
            call(Goal),write('  '),write(Name),write(' = '),write(X),nl,fail.
write_all_X(_,_,_).

start:- 
    write('Vyhodnoceni aritmetickeho vyrazu'),nl,nl,
    write('Dotaz "expr(X,[3,+,4,/,2,-, \'(\' ,2,*,6,/,3,+,2, \')\' ],[])" vrati:'),nl,
    write_all_X(expr(X,[3,+,4,/,2,-, '(' ,2,*,6,/,3,+,2, ')' ],[]), X, 'X').
?-start.

:- retractall(write_all_X/3).
:- retractall(start/0).
