Just wondering why with-open doesn't force evaluation of a LazySeq and yet prn does?
with-open is specifically for doing side effects, isn't it a bad idea to be doing something inside with-open that produces something lazy for possible consumption later on? In what situation would you do this?
The two serve completely different purposes. prn is a function designed specifically to print things in a way that can be read by the reader. If the thing being printed happens to be 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 general-purpose macro designed to execute any arbitrary code in its body in a context where resources are closed on completion of the code. It's essentially syntactic sugar. The macro knows nothing about what the code in its body is doing, or what sort of result it's going to produce.
You are correct that returning lazy sequences from a with-open that try to read from an already-closed resource is a common source of bugs in Clojure programs. However, it's not feasible for the with-open macro to reliably detect when its body causes a lazy sequence to be produced and automatically force it. You have to be aware of this situation and handle it in your own code when it arises.
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