Anonymous iterators blocks in Clojure?

Posted by Checkers on Stack Overflow See other posts from Stack Overflow or by Checkers
Published on 2010-05-02T12:50:09Z Indexed on 2010/05/02 12:58 UTC
Read the original article Hit count: 222

I am using clojure.contrib.sql to fetch some records from an SQLite database.

(defn read-all-foo []
  (let [sql "select * from foo"]
    (with-connection *db*
      (with-query-results res [sql]
         (into [] res)))))

Now, I don't really want to realize the whole sequence before returning from the function (i.e. I want to keep it lazy), but if I return res directly or wrap it some kind of lazy wrapper (for example I want to make a certain map transformation on result sequence), SQL bindings will be gone after I return, so realizing the sequence will throw an error.

How can I enclose the whole function in a closure and return a kind of anonymous iterator block (like yield in C# or Python)?

Or is there another way to return a lazy sequence from this function?

© Stack Overflow or respective owner

Related posts about clojure

Related posts about lazy-sequences