1

going through the exercises in the fp-oo book and i'm having trouble with an early exercise to add squares. Here's my code:

 (defn square [n]
   (* n n))

 (defn add-squares [l]
   (cond
     (nil? l) 0
     :else (+ (square (first (l))) (add-squares (rest (l))))))

This example:

(add-squares '(2 2 2 2))

should return

16

but fails with this exception:

ClassCastException clojure.lang.PersistentList cannot be cast to clojure.lang.IFn  user/add-squares (NO_SOURCE_FILE:4)

which i guess means i'm trying to pass a function somewhere instead of a list which was expected. Can someone tell me which part of the code is the culprit?

Thanks, James

1 Answer 1

4

This is wrong:

(first (l))

This means that you are calling l as a function.

You should use:

(first l)

And of course, the same thing for (rest (l))

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

1 Comment

thanks, removing those parentheses around the l in the call to first and rest did it.

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.