Never been to DZone Snippets before?

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

About this user

crat

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

How to parse a little language in Prolog

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
   1  
   2  %
   3  % This is a simple (nay,trivial!)  "dialect" 
   4  % with only two commands.
   5   
   6  % Obviously only scratches the surface - 
   7  % Written as a learning exercise!
   8  % First define a grammar using prolog's Definite 
   9  % Clause Grammar (DCG) notation
  10  % DCG is a bit like a macro system - 
  11  % the grammar rules are expanded into
  12  % ordinary prolog clauses  before execution:
  13  % Thanks to prolog unification, the Cmd variable
  14  % will end up being instantiated to a functor like
  15  % sell(abc,10,5) or buy(xyz,55):
  16  
  17  cmd(Cmd) --> sell,!,amount(Amount),of,stock(Stock),at,price(Price), 
  18               { Cmd = sell(Stock,Amount,Price) }.
  19  cmd(Cmd) --> buy,!,amount(Amount),of,stock(Stock), 
  20               {Cmd = buy(Stock,Amount)}.
  21  sell --> [sell].
  22  of --> [of].
  23  at --> [at].
  24  buy --> [buy].
  25  amount(Amount) --> [Amount].
  26  stock(Stock)   --> [Stock].
  27  price(Price)   --> [Price].
  28  
  29  % mini-evaluator:
  30  
  31  eval(sell(Stock,Amount,Price)) :- 
  32   format('Sold ~d ~a shares at $~d.~n',[Amount,Stock,Price]).
  33  eval(buy(Stock,Amount)) :- 
  34   format('Bought ~d ~a shares.~n',[Amount,Stock]).
  35  
  36  % parse a statement, if it's a command, 
  37  % evaluate it, otherwise write an error
  38  % (NB.  ";" is prolog's % "or".)
  39  
  40  interp(Statement) :- cmd(Cmd,Statement,[]),
  41               eval(Cmd);write('Unrecognised command!').
  42  
  43  % Examples: 
  44  % ( First two match , the last fails.)
  45  
  46  test :-
  47      interp([sell,100,of,xyx,at,50]),
  48      interp([buy,45,of,abc]),
  49      interp([not,accepted]).
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS