[plt-scheme] Hash-tables and call/cc

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Mon May 7 15:53:38 EDT 2007

Hi all,

I'd like to iterate through the keys in a hash-table
with srfi-42. In order to do that I'd like a function:

   hash-table->generator : hash-table -> thunk

which takes a hash-table as input and returns a
thunk g as output. The first invocation of g
returns the first element, the second invocation
returns the seconc, and so on. When there is no
left, g simply return #f.

Here is an attempt do just that:

(define (hash-table->generator ht)
   (let ([continue 'start])
     (lambda ()
       (case continue
         [(done)    #f]
         [(start)   (let/ec return
                      (hash-table-for-each
                       ht
                       (lambda (x v)
                         (call/cc
                          (lambda (k)
                            (set! continue k)
                            (return x)))))
                      (set! continue 'done)
                      #f)]
         [else      (continue)]))))

It almost work - but only almost.

Here is a session in the REPL:

 > (define g (hash-table->generator
              (make-immutable-hash-table
               '(("1" . 1) ("2" . 2) ("3" . 3)))))
 > (g)
"2"
 > (g)
"3"
 > (g)
"1"
 > (g)
#f

But now the fun begins:

 > (define g (hash-table->generator
              (make-immutable-hash-table
               '(("1" . 1) ("2" . 2) ("3" . 3)))))
 > (list (g) (g))
(#f done)

I have missed /something/ in hash-table->generator,
but what?

-- 
Jens Axel Søgaard




Posted on the users mailing list.