Re: gethash abstraction
Hi,
I don't completely understand what you are trying to do from the code
you give, but note that you can specify default values in a gethash
form. So for example, the following form automagically does the right
thing if the key is not in the hashtable:
(defparameter *table* (make-hash-table))
(incf (gethash 'foo *table* 0))
(gethash 'foo *table*) => 1
Pascal
On 10 Apr 2006, at 05:20, Charles Hoffman wrote:
>
> Hi, I'm relatively new to Lisp... last semester in my classes I had
> a course which involved a good amount of Scheme, and I quite
> enjoyed it, so I thought for my undergrad research I'd try a little
> something with Common Lisp. The project is on network science, and
> since I'm a little new to the language this might seem like a dumb
> question. But then, I figure being afraid to ask the dumb
> questions just makes you look even more dumb later on ;-)
>
> I'm using hash tables in a couple places in my project, but I find
> that I'm using a pattern quite often where I first check to see if
> a hash table has a certain key, by checking whether (gethash key
> myhash) returns nil, and then taking some action on that slot in
> the has table depending on whether or not it already exists.
>
> The question I have is, it seems like I end up repeating the same
> gethash expression like two, three, maybe four times in the same
> function or method -- testing it, setting it, modifying it,
> returning it... This kind of repetition, I gather, is not the Lisp
> Way ;-) nor is it the way I like to program.
>
> However, I tried using a let expression, in a manner similar to the
> following (simplified for clarity):
> ...
> (let ((loc (gethash key myhash)))
> (if (null loc)
> (setf loc 0)
> (incf loc))) ...
> And I'm getting errors. Errors I don't fully understand, as the
> debugger tends to still mistify me a bit right now. Like I said,
> I'm new to the language. But apparently this is not the proper way
> top abstract a reference into a hash table.
> a) I know something's wrong about the above but I don't have the
> words to express what it is.
> Could someone explain it a little?
> b) What's the right way (or at least a way that works) to do what
> I'm getting at?
>
> --ch--
>
--
Pascal Costanza, mailto:pc@p-cos.net, http://p-cos.net
Vrije Universiteit Brussel, Programming Technology Lab
Pleinlaan 2, B-1050 Brussel, Belgium