Search code examples
clojurelazy-evaluationsequenceslazy-sequences

clojure storing vs. using a sequence in expression


Helo, In an effort to learn clojure, I have taken an interest in clojure.core functions that act on sequences. Recently, I noticed some odd behaviour and would like an explaination of the difference between the folling expressions:

What I'm trying to do is this:

user=> (reduce + (take-while (partial > 1000) (iterate inc 1)))
499500

However, when I store (iterate inc 1) with def a get an error:

user=> (def a (iterate inc 1))
#'user/a
user=> (reduce + (take-while (partial > 1000) (a)))
java.lang.ClassCastException: clojure.lang.Cons cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)

Could someone please explain what the difference between storing iterate inc 1 and using it directly in the expression? I know that a is a lazy sequence but am missing something...

Thank you very much for your time.


Solution

  • You should be doing

    (reduce + (take-while (partial > 1000) a))
    

    (a) attempts to call a, but it's not a function.