Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a function in Clojure?

Tags:

clojure

I've been working on Clojure question 135 Infix Calculator, basically a simplified infix to prefix arithmetic calculator:

(= 7  (__ 2 + 5))

I solved the problem as specified. But that got me wondering - what if the argument had been supplied as a string - how would I get it to work?

(= 7  (__ "2 + 5"))

Obviously I'd start with a split, then munch through the result:

(clojure.string/split "2 + 5" #"\s")
user=> ["2" "+" "5"]

But how would I convert the "+" to a function call? This isn't going to work:

("+" 2 5)
user=> java.lang.ClassCastException: java.lang.String cannot be 
cast to clojure.lang.IFn <snip>

Enlightenment sought....

like image 495
Sonia Hamilton Avatar asked Jun 10 '12 10:06

Sonia Hamilton


1 Answers

Look at the resolve function

((resolve (symbol "+")) 1 2)
like image 52
DanLebrero Avatar answered Oct 21 '22 03:10

DanLebrero