Question

I have a hash table in Chicken Scheme the hash table has keys with values corresponding to those keys are hashes with corresponding values of hashes again. The keys of the "inner hashes" have corresponding values which are strings. (For Those familiar with, say, Ruby, setting the relevant portion of the hash might look like

the_hash[group_name][section_name][part_name] = some_text

or to read the string:

a_string = the_hash[group_name][section_name][part_name]

, for example.)

At the point where I read the string, I need to know what the group_name, section_name, and part_name are and I need to be able to perform certain actions based on the values of each of the strings and the for-each and map features of Scheme do not seem to be sufficient because only one of the three key/sub-key strings seems available at any given moment. I do not know what patterns the respective strings might hold. A web search turned up no work able solution. At the same time, I am relatively new to Scheme and may not be as familiar as I should. Can Anyone point Me in the direction of a solution?

Was it helpful?

Solution

Scheme doesn't have built-in support for multidimensional hashes, but with the right abstractions you can build your own implementation:

; create a new multidimensional hash table
(define (make-multi-hash)
  (make-hash-table))

; set a value given a non-empty sequence of keys
(define (multi-hash-set! hash-table value . keys)
  (let loop ((hash hash-table)
             (keys keys))
    (cond ((null? (cdr keys))
           (hash-table-set! hash (car keys) value))
          (else
           (if (not (hash-table-exists? hash (car keys)))
             (hash-table-set! hash (car keys) (make-multi-hash)))
           (loop (hash-table-ref hash (car keys)) (cdr keys))))))

; retrieve a value given a non-empty sequence of keys
(define (multi-hash-ref hash-table . keys)
  (foldl (lambda (k h) (hash-table-ref h k))
         hash-table
         keys))

Use it like this:

(define h (make-multi-hash))
(multi-hash-set! h 42 'a 'b 'c)
(multi-hash-ref h 'a 'b 'c)
=> 42

Using the above procedures as a starting point surely you can implement the required functionality. Also notice that Chicken Scheme provides a lot of procedures for dealing with "normal" hash tables, some of them will be useful, as this implementation uses ordinary hash tables under the hood.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top