2

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

Community
  • 1
  • 1
vikbehal
  • 1,486
  • 3
  • 21
  • 48
  • Yeah thats a duplicate. I should have checked that before posting answer :) – Ankur Nov 28 '11 at 10:55
  • @sepp2k not only string but all type of data which can be returned by Java app. But Duplicate also solves my problem! – vikbehal Nov 29 '11 at 09:20

2 Answers2

9

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
mikera
  • 105,238
  • 25
  • 256
  • 415
4

You will have to convert the string "(+ 2 3)" to List data structure i.e (list + 2 3) or '(+ 2 3) and then pass it to eval to evaluate the form. A string is evaluated to a string hence you get "(+ 2 3)" after evaling the string "(+ 2 3)"

Ex:

(eval (read (new java.io.PushbackReader (new java.io.StringReader "(+ 1 2)"))))

Read is the "Reader" which read a stream and parses it into clojure code which is then evaluated using eval

Ankur
  • 33,367
  • 2
  • 46
  • 72