DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Carl has posted 4 posts at DZone. View Full User Profile

How To Parse A Little Language In Prolog

04.21.2007
| 4988 views |
  • submit to reddit
        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 http://www.ddj.com/184404172, listing 9 for the little language
%
% 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 :-
    interp([sell,100,of,xyx,at,50]),
    interp([buy,45,of,abc]),
    interp([not,accepted]).