0

I'm pretty new to closure and I don't understand why I'm getting this error message at runtime. Here is my code:

(defn invert [lst]
  (if (empty? lst)
    ()
    (cons (invert-helper lst) (invert (rest lst)))))

(defn invert-helper [lst]
  (list (nth lst 1) (first lst)))
1
  • You need to define invert-helper before using it in invert. Commented Sep 1, 2014 at 21:44

2 Answers 2

3

This should fix the problem:

(defn invert-helper [lst]
  (list (nth lst 1) (first lst)))

(defn invert [lst]
  (if (empty? lst)
    ()
    (cons (invert-helper lst) (invert (rest lst)))))

That is: the invert-helper function must be defined before its first use in invert.

Sign up to request clarification or add additional context in comments.

3 Comments

that makes sense, but now I'm getting and index out of bounds exception clojure.lang.RT.nthFrom (RT.java:795).
@ChrisPhillips You're calling (nth lst 1) where lst may have only one element - this will throw the exception you're seeing.
@ChrisPhillips as soulcheck mentions, the error is caused because lst might have less than two elements. Just to be sure: don't forget that indexes in clojure start at 0, that is: the first element is (nth lst 0), the second is (nth lst 1) and so on.
2

Another option, apart from defining all the functions before using them, may be declaring invert-helper before invert:

(declare invert-helper)

(defn invert [lst]
  (if (empty? lst)
    ()
    (cons (invert-helper lst) (invert (rest lst)))))

(defn invert-helper [lst]
  (list (nth lst 1) (first lst)))

You're also calling (nth lst 1) where lst may have only one element - this will throw an exception.

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.