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


Reply via email to