[dev] Re: Lexers and parsers 2

From: Maurí­cio CA <mauricio.antunes_AT_gmail.com>
Date: Thu, 12 Aug 2010 16:34:14 -0300

>>> echo '(+ 1 2 (+ 3 4) (+ 5 6) 7)' | calc.noam

>> I'm sorry, but looking at the above I just couldn't [not] notice the
>> Greenspun's Tenth Rule of Programming :)

The nice thing about that law is that it can easily be adapted to
your language of choice. Let's try the Haskell version, this time
with addition and multiplication :)

   #!/usr/bin/noam
   number : /[0-9]+/ ;
   list : /\[/ number (/,/ number)* /\]/
       {printf "%s" "$2$3" | tr '[]' '()' > $OUTPUT} ;
   plus : /plus/ list
       {printf "%s" $2 | sed 's/,/+/g' > $OUTPUT} ;
   times : /times/ list
       {printf "%s" $2 | sed 's/,/*/g' > $OUTPUT} ;
   number : (plus | times)
       {printf "%s\n" "$1" | bc > $OUTPUT} ;
   main : number {echo "Result: " $1} ;

You can type:

   echo "plus[1,2,times[plus[3,4],plus[5,6]],7]" | calctest2.noam

Then you get:

   Result: 87

Best,

Maurício
Received on Thu Aug 12 2010 - 21:34:14 CEST

This archive was generated by hypermail 2.2.0 : Thu Aug 12 2010 - 21:36:02 CEST