This is the mail archive of the guile@sourceware.cygnus.com mailing list for the Guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: how to work with (weak) hash tables?


Valentin Kamyshenko <val@kamysh.materials.kiev.ua> writes:

> Thank you very much for the help. 
> So, if I want to add one to each value of hash table `ht', I can
> write smth. like:
> 
> (hash-fold 
> 	(lambda (key value alist) 
> 		(hashq-set! ht key (1+ value))) 
> 	() ht)
> 
> It is sufficient for my purposes, but, nevertheless, 
> is not there more effective way? I'd like to write smth. like
> 
> 	(set! value (1+ value))
> 
> in the body of lambda (I understand, that, of course, it can not work
> right now (and it does not), because, evidently, I should not have a
> possibility to change value of `key' in  this way).

If it were non-immediate values, you could actually do something like
this (though admittedly a little bit gross), but it's not possible
with the combination of immediates and hash-fold.  You could write a c
function that would map over the actual pairs making up the hash table
(something like a hash-for-each) which would do this.

Come to think of it, you can do it in scheme, too; the code follows,
but this is not something that you should rely on (hash tables could
stop being scheme vectors for any number of reasons, not the least of
which being the following code ;):

(define (hash-for-each proc hash)
  (let ((len (vector-length hash)))
    (do ((i 0 (+ i 1)))
        ((= i len) ())
      (for-each proc (vector-ref hash i)))))


guile> (define x (make-hash-table 10))
; Prime, shmime ;)
guile> (hashq-set! x 'a 1)
1
guile> (hashq-set! x 'b 1)
1
guile> (hash-for-each (lambda (x) (set-cdr! x (+ (cdr x) 1))) x)
()
guile> x
#(((a . 2)) () () () ((b . 2)) () () () () ())

-- 
Greg

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]