I'm twisting my old java/python head the clojure way. Please help me to understand the lazy feature of clojure.
=> (def myvar (lazy-seq [1 2 (prn "abc")]))
#'user/myvar
The above is easy to understand. Since it's a lazy sequence, the (prn "abc") will not be evaluated, hence nothing printed.
=> (def myvar (lazy-seq [1 2 (prn undefined-var)]))
CompilerException java.lang.RuntimeException: Unable to resolve symbol: undefined-var in this context, compiling:(NO_SOURCE_PATH:1)
The above will raise an error as you can see. Why ?
My (wrong)understanding is, since it's lazy, the (prn undefined-var) could be legally here even the "undefined-var" has not been defined yet.
Please anyone point my understanding to the correct way.
When the clojure reader finds
(def myvar (lazy-seq [1 2 (prn undefined-var)]))
It needs to compile it, that is the reason why it throws the error, as the undefined-var is not defined. In the first case, it compiles ok, but it is not executed until you consume the seq.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With