<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: dsl code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sun, 27 Jul 2008 02:51:39 GMT</pubDate>
    <description>DZone Snippets: dsl code</description>
    <item>
      <title>How to parse a little language in Prolog</title>
      <link>http://snippets.dzone.com/posts/show/3851</link>
      <description>How to parse a token list into functors (structured terms) in Prolog.&lt;br /&gt;The book "Logic in Prolog" by Gibbins has some good example code  &lt;br /&gt;See http://www.ddj.com/184404172, listing 9 for the little language&lt;br /&gt;&lt;code&gt;&lt;br /&gt;%&lt;br /&gt;% This is a simple (nay,trivial!)  "dialect" &lt;br /&gt;% with only two commands.&lt;br /&gt; &lt;br /&gt;% Obviously only scratches the surface - &lt;br /&gt;% Written as a learning exercise!&lt;br /&gt;% First define a grammar using prolog's Definite &lt;br /&gt;% Clause Grammar (DCG) notation&lt;br /&gt;% DCG is a bit like a macro system - &lt;br /&gt;% the grammar rules are expanded into&lt;br /&gt;% ordinary prolog clauses  before execution:&lt;br /&gt;% Thanks to prolog unification, the Cmd variable&lt;br /&gt;% will end up being instantiated to a functor like&lt;br /&gt;% sell(abc,10,5) or buy(xyz,55):&lt;br /&gt;&lt;br /&gt;cmd(Cmd) --&gt; sell,!,amount(Amount),of,stock(Stock),at,price(Price), &lt;br /&gt;             { Cmd = sell(Stock,Amount,Price) }.&lt;br /&gt;cmd(Cmd) --&gt; buy,!,amount(Amount),of,stock(Stock), &lt;br /&gt;             {Cmd = buy(Stock,Amount)}.&lt;br /&gt;sell --&gt; [sell].&lt;br /&gt;of --&gt; [of].&lt;br /&gt;at --&gt; [at].&lt;br /&gt;buy --&gt; [buy].&lt;br /&gt;amount(Amount) --&gt; [Amount].&lt;br /&gt;stock(Stock)   --&gt; [Stock].&lt;br /&gt;price(Price)   --&gt; [Price].&lt;br /&gt;&lt;br /&gt;% mini-evaluator:&lt;br /&gt;&lt;br /&gt;eval(sell(Stock,Amount,Price)) :- &lt;br /&gt; format('Sold ~d ~a shares at $~d.~n',[Amount,Stock,Price]).&lt;br /&gt;eval(buy(Stock,Amount)) :- &lt;br /&gt; format('Bought ~d ~a shares.~n',[Amount,Stock]).&lt;br /&gt;&lt;br /&gt;% parse a statement, if it's a command, &lt;br /&gt;% evaluate it, otherwise write an error&lt;br /&gt;% (NB.  ";" is prolog's % "or".)&lt;br /&gt;&lt;br /&gt;interp(Statement) :- cmd(Cmd,Statement,[]),&lt;br /&gt;             eval(Cmd);write('Unrecognised command!').&lt;br /&gt;&lt;br /&gt;% Examples: &lt;br /&gt;% ( First two match , the last fails.)&lt;br /&gt;&lt;br /&gt;test :-&lt;br /&gt;    interp([sell,100,of,xyx,at,50]),&lt;br /&gt;    interp([buy,45,of,abc]),&lt;br /&gt;    interp([not,accepted]).&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sun, 22 Apr 2007 01:44:35 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3851</guid>
      <author>cratylus (crat)</author>
    </item>
  </channel>
</rss>
