Chicken Library: hash-let

While I do not now use hash tables as often as I did when using Perl regularly, they're still pretty useful. However the setter/getter notation that Scheme uses can lead an awful lot of typing. What I want is to be able to do this:

(define f (make-hash-table))
(hash-table-set! f 'name 'william)
(hash-table-set! f 'rank 'dude)
(hash-table-set! f 'sn  '12-34-567)

(hash-let ((name sn) f)
  (print name " " sn #\newline))

 =>  william 12-34-567

That is, I want to be able to bring particular keys into the lexical environment with the correct values. So I wrote a macro.

The simplest use, as in the example above, assumes you're using symbols as keys. I suspect most people will use it that way. However, if you're using different types as keys, or if you want to rename the variable, use the notation (var key) to use a new name:

(define f (make-hash-table string=?))
(hash-table-set! f "name" 'william)
(hash-table-set! f "rank" 'dude)
(hash-table-set! f "sn"  '12-34-567)

(hash-let (((name "name") (serial-number "sn")) f)
  (print name " " serial-number #\newline))

 =>  william 12-34-567

Finally, you can use a three element list for the binding name to set a default, like so:

(hash-let ((name (last-name last-name "Smith")) f)
  (print name " " last-name #\newline))

 =>  william Smith

The third element must be an expression. If you want a symbol for the default, you must quote it:

(hash-let ((name (ssn ssn 'none)) f)
  (print name " " ssn #\newline))


 => william none

Source: hash-let.scm.





Scheme (Chicken)