Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't with-open force evaluation

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?

like image 852
shmish111 Avatar asked Jun 07 '26 16:06

shmish111


1 Answers

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.

like image 120
Alex Avatar answered Jun 10 '26 05:06

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!