I have a LazySeq of connections that are created when realized. If an exception occurs while attempting to create a connection, I'd like to iterate through all of the connections that have already been realized in the LazySeq and close them. Something like:
(try
(dorun connections)
(catch ConnectException (close-connections connections)))
This doesn't quite work though since close-connections
will attempt to realize the connections again. I only want to close connections that have been realized, not realize additional connections. Any ideas for doing this?
Code:
This returns the previously realized initial fragment of the input seq as a vector:
Testing at the REPL:
(Using
;=>
to indicate a printout.)Discussion:
realized?
is indeed the way to go, as suggested by Nathan. However, as I explained in my comments on Nathan's answer, one must also make sure that one doesn't inadvertently callseq
on the one's input, as that would cause the previously-unrealized fragments of the input seq to become realized. That means that functions such asnon-empty
andempty?
are out, since they are implemented in terms ofseq
.(In fact, it is fundamentally impossible to tell whether a lazy seq is empty without realizing it.)
Also, while functions like
lazify
are useful for unchunking sequences, they do not prevent their underlying seqs from being realized in a chunked fashion; rather, they enable layers of processing (map
,filter
etc.) to operate in an unchunked fashion even while their original input seqs are chunked. There is in fact no connection at all between such "lazified" / "unchunked" seq being realized and its underlying, possibly chunked seq being realized. (In fact there is no way to establish such a connection in the presence of other observers of the input seq; absent other observers, it could be accomplished, but only at the cost of makinglazify
considerably more tedious to write.)