Clojure getting loop IllegalArgumentException Key must be integer clojure.lang.APersistentVector.invoke

I am stuck trying to get a simple loop in Clojure to work and I have no idea how to fix this exception. I am trying to write a function arrange

for elements exchange

in a vector. Here is the code.

(defn exchange [v i] 
  (let [[src dst] i]
    (assoc v dst (v src) src (v dst))))

(defn arrange []
  (loop [idxs [0 0] 
         deck [\a \b \c \d \e] 
         pts [[0 1] [2 3] [4 1]]]
    (println idxs deck pts)
    (empty? pts)
      deck
      (recur (first pts) (exchange deck idxs) (rest pts))))    

;(arrange)
;[b e d c a]

      

If I remove println I don't see anything in the REPL. I come from COBOL to let you know that I am trying my best to bring this up :) Any suggestions to make this more idiomatic would be appreciated.

6 / 11- This is a revised code. arrange

should only have two parameters in the loop.

(defn arrange []
  (loop [deck [\a \b \c \d \e] 
         lst [[0 1] [2 3] [4 1]]]
    (if (empty? lst)
      deck
      (recur (exchange deck (first lst)) (rest lst)))))

      

or even better, use (reduce exchange deck lst)

@Magos instead!

+3


source to share


1 answer


You are missing if

, and you need to end the loop with idxs

, not pts

(or you miss the final pair):

(if (empty? idxs)
  deck
  (recur (first pts) (exchange deck idxs) (rest pts)))

      



should work better.

+2


source







All Articles