[plt-scheme] hash-table question

From: Eli Barzilay (eli at barzilay.org)
Date: Fri Feb 4 10:43:02 EST 2005

On Feb  4, Larry White wrote:
> is there a way to get at the values of a hash-table as a list?
> 
> I have a need to access data sometimes using search, and sometimes
> iteratively.  I could implement search over the data held as a list,
> but it would be much less efficient.  Other languages have the
> equivilent of a function like (values my-hash-table) that would
> return a list of values.  Anything like that available?

`hash-table-for-each' and `hash-table-map' are exactly what you need.
The first one just iterates over the list, and the second one collects
the result in the list.  For example:

  > (require 'etc)
  > (define t (hash-table (1 2) (3 4) (5 6)))
  > (hash-table-for-each t (lambda (key val) (printf "~s -> ~s\n" key val)))
  5 -> 6
  3 -> 4
  1 -> 2
  > (hash-table-map t (lambda (key val) val))
  (6 4 2)

So it is simple to define a function that will get the list of values:

  > (define (hash-table-values tbl) (hash-table-map tbl (lambda (key val) val)))
  > (hash-table-values t)
  (6 4 2)


> Since the hash-table-for-each and hash-table-map functions require a
> proc with exactly two procedures (key and value), they're not really
> useful for my situation.  I need to apply a four parameter function
> to each value.

I suspect that Robby's answer is relevant here.

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!



Posted on the users mailing list.