0

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.

3
  • Actually what I get is: ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn Commented Sep 1, 2013 at 22:44
  • 1
    1. I think I'd choose Forth for this challenge -- done. 2. Are you forgetting the reverse in RPN? 3. (defn rpn [& e](reduce #(if (fn? %2)(let [[l r & m]%](cons (%2 r l) m))(cons %2 %))[]e)) @learnclojure Commented Sep 2, 2013 at 2:40
  • @A.Webb 1. I shall look into Forth. 2. Sorry, I meant PN. It's been a while since I learned about it. Got the two slightly muddled in my head. 3. Tasty! I'm going to pick that apart. Thanks. Commented Sep 2, 2013 at 3:54

1 Answer 1

1

You are using extra parentheses after defn args vector. It should be:

(defn r[e]
  (load-string 
    (reduce 
      (fn[x c] 
        (s/replace x #"([\+\-\*\/] (\(.*\) \d+|\d+ \d+))" "($0)")) 
      e 
      (subvec (s/split e #"\d") 1))))

user=> (r "+ 3 5")
8
Sign up to request clarification or add additional context in comments.

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.