10

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....

2 Answers 2

17

Look at the resolve function

((resolve (symbol "+")) 1 2)
Sign up to request clarification or add additional context in comments.

Comments

2

you can use load-string or read-string. That's something like READ-FROM-STRING in common lisp, which adhere to the principle of 'Code is Data', treats the string as codes - evaluate and return the value.

user=> (class (load-string "+"))
clojure.core$_PLUS_
user=> (read-string "+")
+
user=>

then you can simply use it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.