Next: , Previous: , Up: ref-gru   [Contents][Index]


4.14.3 An Example

As an example, here is a simple grammar that parses an arithmetic expression (made up of digits and operators) and computes its value. Create a file containing the following rules:

grammar.pl

expr(Z) --> term(X), "+", expr(Y), {Z is X + Y}.
expr(Z) --> term(X), "-", expr(Y), {Z is X - Y}.
expr(X) --> term(X).

term(Z) --> number(X), "*", term(Y), {Z is X * Y}.
term(Z) --> number(X), "/", term(Y), {Z is X / Y}.
term(Z) --> number(Z).

number(C) --> "+", number(C).
number(C) --> "-", number(X), {C is -X}.
number(X) --> [C], {"0"=<C, C=<"9", X is C - "0"}.

In the last rule, C is the character code of a decimal digit.

This grammar can now be used to parse and evaluate an expression by means of the built-in predicates phrase/[2,3]. See mpg-ref-phrase. For example,

| ?- [grammar].
| ?- phrase(expr(Z), "-2+3*5+1").

Z = 14

| ?- phrase(expr(Z), "-2+3*5", Rest).

Z = 13,
Rest = [] ;

Z = 1,
Rest = "*5" ;

Z = -2,
Rest = "+3*5" ;

no

Send feedback on this subject.