Why not openly assessing strength
Just wondering why it with-open
doesn't force a to evaluate LazySeq
, and still prn
does?
with-open
specifically designed to perform side effects, isn't it so bad that you are doing something internally with an opening that later creates something lazy for possible consumption? In what situation will you do it?
source to share
Both serve completely different purposes. prn
is a function designed specifically for printing things in a way that the reader can read. If the thing being printed is a lazy sequence, the only thing to do is force evaluation of the lazy sequence in order to print its contents.
with-open
, on the other hand, is a macro general purpose, designed to execute any arbitrary code in its body in a context where resources are closed when the code completes. This is essentially syntactic sugar. The macro does not know anything about what the code is doing in its body, or what result it will produce.
You are correct that returning lazy sequences from with-open
that are trying to read from an already closed resource is a common source of bugs in Clojure programs. However, a macro is with-open
impractical to reliably detect when its body invokes a lazy sequence and forces it automatically. You should be aware of this situation and handle it in your own code when it occurs.
source to share