Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happened with lazy evaluation of Clojure

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.

like image 736
John Wang Avatar asked Dec 02 '22 22:12

John Wang


1 Answers

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.

like image 169
DanLebrero Avatar answered Dec 19 '22 04:12

DanLebrero