Prolog Language Definite Clause Grammars (DCGs) Extra arguments


Example

The extra arguments add results to predicates of a DCG clause, by decorating the derivation tree. For example, it's possible to create a algebraic grammar that computes the value at the end.

Given a grammar that supports the operation addition:

% Extra arguments are passed between parenthesis after the name of the DCG clauses.
exp(C) --> int(A), [+], exp(B), {plus(A, B, C)}.
exp(X) --> int(X).
int(X) --> [X], {integer(X)}.

The result of this grammar can be validated and queried:

?- phrase(exp(X), [1,+,2,+,3]).
X = 6 ;