I'm using Clojure for a code golf challenge, in which the aim is to write a function that evaluates and returns the value from a Polish Notation expression. Below is my code.
(require '[clojure.string :as s])
(defn p[e](
(load-string (reduce (fn[x c]
(s/replace x #"([\+\-\*\/] (\(.*\) \d+|\d+ \d+))" "($0)")
) e (subvec (s/split e #"\d") 1)))))
Remember this is golfed code (not meant to be readable).
In short, the function takes a string, the string is then split into a vector. Reduce iterates over the vector and applies the expression for the n-1 elements in the vector. What comes out is a string that Clojure should be able to evaluate with load-string
.
If I declare a var called e
with the value "+ 3 5"
then run just the reduce from the function, "(+ 3 5)"
is expected as returned. But when I call the function as (p "+ 3 5")
I get the following error.
java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)
No idea what's going on here.
You are using extra parentheses after defn args vector. It should be: