[plt-dev] Suggestion: `with-hash'

From: Eli Barzilay (eli at barzilay.org)
Date: Thu Mar 26 23:29:28 EDT 2009

Here's a suggestion for a small addition to `scheme/base', with the
obvious meaning:

  (with-hash <hash> <key> <expr>)

    Lookup <key> in <hash> and return the found value.  If there is
    no value evaluate <expr>, store it in <hash> for the <key>, and
    return it.

I'm sure that many are familiar with the usual little dance routine
you need to do to get this done -- it's not hard to write, but it's
very annoying.  Having a memoization tool helps, but there are many
cases where you don't want a function, just the through-the-hash

And yes, you can often use a memoized function to get the above
implicitly -- but what if you want your own hash table for some reason
(for example, Dave's planet package has only two kinds of hashes, what
if you want a weak hash?), or what if want to use the hash table later
to get a list of values?  Or maybe you just don't want the cost of an
extra function for some reason.

In contrast, the above has no overhead, is minimal enough so it's easy
to remember, and convenient enough for many cases (just grepping the
collection tree for "(or (hash-ref" shows that this will be useful).
In addition, it's easy to define a memoized function with this, for

  (define hcons
    (let ([t (make-hasheq)])
      (lambda (a b)
        (with-hash (with-hash t a (make-hasheq)) b (cons a b)))))

Any objections?

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

Posted on the dev mailing list.