On 26/04/12 19:06, Asranz wrote:
Oh sorry i mean i didt wit sums and multiplications but i dont get how
it can do it conbined in the same line

On 25 abr, 22:18, Asranz<alekx.on...@gmail.com>  wrote:
Hi. im having a little problem i need to do a parser like to do
operations but i dont get how to do it very well

ex.

  "1+2*3+4-5*6+7*8-9" = 431
i have to do it with sums but i dont get it how i can take all the
operations.
any advices?
Here it is:
------------------------------------------------------------------------
;(infix (1 + 4 * 5 - 10 / 3)) -> 5
(defmacro infix [expr]
 `(loop [
          ops#   (filter #(not (number? %)) '~expr) ;operators
          args#  (filter #(number? %) '~expr)         ;operands
         ]
 (if (empty? ops#) (first args#)
 (recur
       (rest ops#)
       (conj (rest (rest args#))
       ((eval (first ops#)) (first args#) (second args#)))))))
------------------------------------------------------------------------------

It is worth pointing out that this macro violates one of the macro-writing 'rules'...that is, macros are not supposed to return values but expressions. It would be nicer if instead of calculating the actual result inside the macro, to simply transform the expression into prefix form and let clojure calculate the result on that...it also would be easier to write than this...

Jim

ps: the above macro does not handle parenthesis or operator precedence....if you want to go the full way have a look at the incanter source...hope that helps!

--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to