Search code examples
clojure

Find the smallest number in sequence fails using loop


I am a Clojure beginner and I cannot decode the meaning of the error or understand why it is happening in my small program to find the smallest number in a sequence.

(defn find-min
  [nums]
  (loop [smallest 1000000 i 0]
    (if (= (count nums) i)
      smallest)
    (if (< (nums i) smallest)
      (recur (nums i) (inc i))
      (recur smallest (inc i)))))


(find-min [3 4 0 2])

IndexOutOfBoundsException clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)

Now I do understand that there is an Index out of bound error but the first if function takes care that the function returns so why is it happening?


Solution

  • Your two if are on the same level, so both of them will be executed subsequently. You may want to put the second if nested in the first if

      (defn find-min[nums]
        (loop [smallest 1000000 i 0]
          (if (= (count nums) i)
            smallest
            (if (< (nums i) smallest)
              (recur (nums i) (inc i))
              (recur smallest (inc i))))))