How to convert user-friendly infix math code to Clojure code?
Asked Answered
M

1

8

I want user to be able to input like this:

5+6*t+sin(2*t)

, so it will get converted to this:

(+ 5 (* 6 t) (sin (* 2 t)))

, so I can eval it to some function that will be JITted and executed efficiently later.

Are there already available libraries (with operator priorities) that works in up-to-date Clojure already?

Marginalia answered 8/8, 2012 at 22:40 Comment(1)
I'm sure there are dozen or so examples for that in antlr that you can pick up and use with a little modification.Gittens
I
9

the Incanter package include a module for doing infix math

user> ($= 7 + 8 - 2 * 6 / 2)
9

and others have written packages.

Impressive answered 8/8, 2012 at 23:1 Comment(3)
Requiring spaces seems to be a bit restricting. And I expect string as input (here I also need to mess with read).Marginalia
I tried clojuire-infix, but it seems to be abandonware (that is why I included "works in up-to-date Clojure" clause).Marginalia
@Marginalia Can't you just automatically parse the string to add a space around all the operators?Ralphralston

© 2022 - 2024 — McMap. All rights reserved.