Search code examples
javaprogramming-languagesclojure

Clojure "eval" unable to evaluate!


Possible Duplicate:
How do you evaluate a string as a clojure expression?

Getting data from a JTextField/Area (from Java Application) returns the data of class java.lang.String. passing this data to eval of Clojure isn't evaluating it, instead printing as such because it is a string. How to make eval evaluate this data and return output.

e.g.) Assume data in text-field is (+ 2 3)

(println (eval (.getText text-field) ))

enter image description hereThis prints (+ 2 3) instead of 5


Solution

  • You need to convert the string to a Clojure data structure before it can be eval'd, since eval expects a valid form data structure as per the docs:

    (doc eval)
    -------------------------
    clojure.core/eval
    ([form])
      Evaluates the form data structure (not text!) and returns the result.
    

    The easiest way of doing this is to use read-string on your String, e.g.

    (eval (read-string "(+ 2 7)"))
    => 9