Chris
Chris

Reputation: 1128

Clojure IndexOutOfBoundsException

((fn [coll] (letfn [(add-item [acc coll idx] 
                              (conj acc (nth coll idx)))

                    (add-group [acc coll] 
                               (conj acc (create-group coll)))

                    (decrease-coll [coll acc] 
                                   (drop (count (last acc)) coll))

                    (not-group-member? [idx coll] 
                                       (not= (first coll) (nth coll idx)))

                    (out-of-bounds? [idx coll] 
                                    (or (empty? coll) (> idx (count coll))))

                    (create-group [coll] (loop [idx 0 
                                                coll coll
                                                acc []]
                                           (if (or (out-of-bounds? idx coll)
                                                   (not-group-member? idx coll))
                                             acc
                                             (recur (inc idx) coll (add-item acc coll idx)))))
                    (process-coll [coll] (loop [coll coll
                                                acc []]
                                           (if (empty? coll)
                                             acc
                                             (recur (decrease-coll coll acc) 
                                                    (add-group acc coll)))))] 
                    (process-coll coll))) [1 1 2 1 1 1])

When I try to run this I receive

java.lang.IndexOutOfBoundsException: null
             RT.java:795 clojure.lang.RT.nthFrom
             RT.java:764 clojure.lang.RT.nth
 /clojure/scratch-work-4clojure.clj:13 user/eval10378[fn]
 /clojure/scratch-work-4clojure.clj:22 user/eval10378[fn]
 /clojure/scratch-work-4clojure.clj:7 user/eval10378[fn]
 /clojure/scratch-work-4clojure.clj:30 user/eval10378[fn]
 /clojure/scratch-work-4clojure.clj:31 user/eval10378[fn]
 /clojure/scratch-work-4clojure.clj:3 user/eval10378

I've been trying to debug this for some time now. I broke it into several functions to try to track down what's causing the error but haven't been able to determine it yet. Any help on what's causing this and how to debug such errors in Clojure in the future would be appreciated.

Upvotes: 2

Views: 1307

Answers (1)

Diego Basch
Diego Basch

Reputation: 13069

Your out-of-bounds? check is wrong. You want >= instead of >. Indexes go from 0 to n-1.

Upvotes: 5

Related Questions