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

From: Eli Barzilay (eli at barzilay.org)
Date: Fri Mar 27 00:43:54 EDT 2009

On Mar 27, Ryan Culpepper wrote:
> Eli Barzilay wrote:
> > 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.
> >  [...]
> > 
> > Any objections?
> I don't like the name.

That's the best I could think of -- and the good point in it is that
it's a strong hint that it's a macro.

> I think you should make it a procedure (use the normal hash
> value/thunk convention) and name it 'hash-ref/default!' or something
> similarly descriptive.

That's actually a point that I forgot to mention.  At some point,
Matthew made `hash-ref' accept a plain value for a default rather than
a thunk.  The reason is that

  (or (hash-ref t k #f) ...stuff..)

is faster than putting stuff in a thunk.  This is especially important
with hash tables, when you're trying to speed things up.

> Also, how about making it generic instead and adding it to
> scheme/dict?  I'd rather procedures for common usage patterns of
> dictionaries were put in scheme/dict than added to the base
> language.

That would of course be useful as a dict method too -- but there's no
contradiction in having both.  (As with other methods that correspond
to specific functions -- you pay for the dispatch when you prefer a
generic code.)

On Mar 27, Henk Boom wrote:
> If the last argument were a thunk then it would almost make sense to
> just call it 'hash-ref!'. That feels like an oxymoron though =).

That *was* my first choice -- but I didn't want that name for a macro.

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

Posted on the dev mailing list.