Newsgroups: comp.lang.dylan
Path: cantaloupe.srv.cs.cmu.edu!das-news2.harvard.edu!news2.near.net!howland.reston.ans.net!news.sprintlink.net!dorite!ts4-ind-4.iquest.net!user
From: fritza@iquest.net (Fritz Anderson)
Subject: Key-of-<table>?
Message-ID: <fritza-1903952154480001@ts4-ind-4.iquest.net>
Sender: news@dorite.use.com (News Admin)
Organization: Himself
Date: Mon, 20 Mar 1995 02:54:48 GMT
Lines: 40

Given an object foo, with key foos-key, and table bar, I want to do this:

   if (table-contains-key(baz, foos-key))
      bar[foos-key] := modify(bar[foos-key], foo)
   else
      bar[foos-key] := new-entry(foo)
   end if;

The question is, how to express table-contains-key(a-table :: <table>,
key)?  I am surprised not to find a direct function that does this in the
DIRM (always modulo my missing something).  One could do:

define constant table-contains-key =
   method(a-table :: <table>, a-key)
      member?(a-key, key-sequence(a-table))
   end method;

but it seems to me this involves creating, populating, and (eventually)
collecting the key-sequence list, which for this purpose is a waste of
time and memory.  Element-getter for <table> knows whether keys get used
in tables (it raises an error if they don't exist), and presumably does
the check without conjuring up an entire key list.  One alternative might
be:

bar[foos-key] := 
   block
      modify(bar[foos-key], foo)
   exception(<error>)
      new-entry(foo)
   end;

I guess it would be prudent to include as little as possible in the block,
so as to be sure that the <error> that got raised arises only from the
attempt to access the nonexistent table entry.  This would work, but is it
naive of me to be surprised to use the exception mechanism in so
unexceptional a case?

-- 
Fritz Anderson         Indianapolis, Indiana   317-257-2227            fritza@well.sf.ca.us   fritza@iquest.net       WT9T
I've begun to suspect that large portions of the Universe -- possibly including history itself -- do not properly reward fair play, and I tell you I'm pretty worked up about it.
