Chris Phillips
Chris Phillips

Reputation: 233

CompilerException java.lang.RuntimeException: Unable to resolve symbol: invert-helper in this context

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)))

Upvotes: 0

Views: 551

Answers (2)

soulcheck
soulcheck

Reputation: 36767

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.

Upvotes: 2

Óscar López
Óscar López

Reputation: 236004

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.

Upvotes: 3

Related Questions