1

Hello as part of the 4Clojure problem set I am attempting to return a list of the first N fibonacci numbers. I have successfully implemented this using non-anonymous functions:

(defn nth-fibo [i]
  (cond
    (= i 1) 1
    (= i 2) 1
    :else (+ (nth-fibo (- i 1)) (nth-fibo (- i 2)))))

(defn fibos [i]
  (loop [x i]
    (when (> x 0)
      (cons (nth-fibo x) (fibos (- x 1))))))

(reverse (fibos 5))

However, I must provide a single callable function to the 4Clojure evaluator to pass the tests. My attempt to do so:

#(
  (letfn [
          (nth-fibo [i]
            (cond
              (= i 1) 1
              (= i 2) 1
              :else (+ (nth-fibo (- i 1)) (nth-fibo (- i 2)))))
          (fibos [i]
            (loop [x i]
              (when (> x 0)
                (cons (nth-fibo x) (fibos (- x 1))))))
          ]
    (reverse (fibos %))))

Leads to the error:

java.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to clojure.lang.IFn

1 Answer 1

5

There's an extra set of parentheses around your anonymous function that's causing the issue. See if this works:

#(letfn [(nth-fibo [i]
           (cond
             (= i 1) 1
             (= i 2) 1
             :else (+ (nth-fibo (- i 1)) (nth-fibo (- i 2)))))
         (fibos [i]
           (loop [x i]
             (when (> x 0)
               (cons (nth-fibo x) (fibos (- x 1))))))]
   (reverse (fibos %)))

A smaller reproduction of the same issue:

#(str %)
=> #object[playground.so$eval1751$fn__1752 0x718c0dd5 "playground.so$eval1751$fn__1752@718c0dd5"]
(*1 1)
=> "1"
#((str %))
=> #object[playground.so$eval1767$fn__1768 0x5375a819 "playground.so$eval1767$fn__1768@5375a819"]
(*1 1)
ClassCastException java.lang.String cannot be cast to clojure.lang.IFn  playground.so/eval1767/fn--1768 (so.clj:21)
Sign up to request clarification or add additional context in comments.

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.