[plt-scheme] Sequencing with a resource that needs to be released

From: Christopher Bowron (cwbowron at gmail.com)
Date: Tue Dec 16 15:21:49 EST 2008

I recently figured out how the sequence generators can be helpful in my
program and I was putting together a function to generate all the rows of
the database in my app, but I realized I have a problem.

I am using Jay McCarthy's SQLite module and using prepare, load-params, step
and finalize to generate all the matching rows.  I see that I could use the
exec function, but I was interested in using sequences for stylistic reasons
and to learn sequences better.

My problem is how to call finalize correctly.  In the ideal case, where the
entire sequence is iterated on, I can clean up in the functions the
determine whether or not to continue the sequence, but it seems that if the
sequence is short circuited as in a for/and or for/or then my statement
cannot be finalized and the database will stay locked.

>From reading the docs I couldn't think of a way to ensure that I was
releasing the resources correctly, but I was wondering if anyone had an

Here is the code that I wrote:

(define (in-database-file-indexes (where #f) . rest)
  (let ([stmt (prepare
               (if where
                   (format "SELECT file_index FROM media WHERE ~A" where)
                   "SELECT file_index FROM media"))])
     (lambda ()
        (lambda (p)
          (and-let* ([r (step p)])
            (vector-ref r 0)))
        (lambda (p) p)
          (when (and where
                     (not (null? rest)))
            (apply load-params stmt rest))
        (lambda (p) #t)
        (lambda (v)
          (if v
                (finalize stmt)
        (lambda (p v) #t))))))

Christopher W. Bowron <chris at bowron.us>
[ Nothing is exciting if you know what the outcome will be ]
   - Joseph Campbell
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20081216/0c594a45/attachment.html>

Posted on the users mailing list.