Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you evaluate a string as a clojure expression?

How would I get something similar to the following?:

(evaluate-text "(+ 1 2)")  ; resolves to 3 
like image 961
Nick Orton Avatar asked Dec 11 '09 02:12

Nick Orton


People also ask

How do you evaluate in Clojure?

Both the operator and the operands (if any) are evaluated, from left to right. The result of the evaluation of the operator is cast to IFn (the interface representing Clojure functions), and invoke() is called on it, passing the evaluated arguments. The return value of invoke() is the value of the call expression.

What is a form in Clojure?

Get Programming with Clojure MEAP V02 Compound expressions are always wrapped into parenthesis. Compound expressions are also called forms. The name of the form is given by the first element of the expression. For instance (+ 1 2) is a “ + form” and (def my-variable 10) is a “ def form”. to see more go to Lesson 4.


1 Answers

user> (eval (read-string "(+ 1 2)")) 3 

You probably shouldn't ever need to do this. Macros and fns make this kind of thing unnecessary 99% of the time. This is quite brittle, and can be unsafe if these strings are coming from user input, and so on.

like image 149
Brian Carper Avatar answered Oct 09 '22 01:10

Brian Carper