How to parse a little language in Prolog

Submitted by:Andery Smith

Date added:02 July, 2011


How to parse a token list into functors (structured terms) in Prolog.
The book "Logic in Prolog" by Gibbins has some good example code See, listing 9 for the little language

Tags: logic in prolog

Code Snippet:

% This is a simple (nay,trivial!) "dialect"
% with only two commands.

% Obviously only scratches the surface -
% Written as a learning exercise!
% First define a grammar using prolog's Definite
% Clause Grammar (DCG) notation
% DCG is a bit like a macro system -
% the grammar rules are expanded into
% ordinary prolog clauses before execution:
% Thanks to prolog unification, the Cmd variable
% will end up being instantiated to a functor like
% sell(abc,10,5) or buy(xyz,55):

cmd(Cmd) --> sell,!,amount(Amount),of,stock(Stock),at,price(Price),
{ Cmd = sell(Stock,Amount,Price) }.
cmd(Cmd) --> buy,!,amount(Amount),of,stock(Stock),
{Cmd = buy(Stock,Amount)}.
sell --> [sell].
of --> [of].
at --> [at].
buy --> [buy].
amount(Amount) --> [Amount].
stock(Stock) --> [Stock].
price(Price) --> [Price].

% mini-evaluator:

eval(sell(Stock,Amount,Price)) :-
format('Sold ~d ~a shares at $~d.~n',[Amount,Stock,Price]).
eval(buy(Stock,Amount)) :-
format('Bought ~d ~a shares.~n',[Amount,Stock]).

% parse a statement, if it's a command,
% evaluate it, otherwise write an error
% (NB. ";" is prolog's % "or".)

interp(Statement) :- cmd(Cmd,Statement,[]),
eval(Cmd);write('Unrecognised command!').

% Examples:
% ( First two match , the last fails.)

test :-