From: Rusty Shackleford
Subject: string as hash key question
Date: 
Message-ID: <slrnd2uttu.qmo.rs@mwilson.umlcoop.net>
I'm new to lisp, and I'm confused by what is happening here:

    CL-USER> (let ((h (make-hash-table )))
               (setf (gethash "aaa" h) 1)
               (format t "value stored with key ~A is ~A." 
                "aaa" (gethash "aaa" h)))
    value stored with key aaa is NIL.
    NIL

    CL-USER> (let ((h (make-hash-table )))
               (setf (gethash 'aaa h) 1)
               (format t "value stored with key ~A is ~A." 
                'aaa (gethash 'aaa h)))
    value stored with key AAA is 1.
    NIL

In the first form, *something* goes wrong when I store with the key
"aaa", but when I use a symbol 'aaa in the second form, that works fine.

Is it possible to use strings as hash keys?

The big picture is that I have a text file with some column data and I
want to count how many times each value appears.

For example, if the file looked like:

    aaa
    aaa
    bbb
    ccc
    aaa

I want to know that aaa appeared 3 times, and bbb and ccc each appeared
once.  My plan was that for each line, I would check to see if it
already exists in the hash.  If it did, then I would add 1 to the value
at the key.  Otherwise, I'd add a new key and set the value to 1.

But since I can't figure out how to store and retrieve values from a
hash, I'm stuck.

All commentary is welcome.  I thought I understood hashes because I used
them in Perl, but apparently I'm missing something basic here.

TIA
From: Edi Weitz
Subject: Re: string as hash key question
Date: 
Message-ID: <uvf80v2zd.fsf@agharta.de>
On Wed, 09 Mar 2005 22:25:01 GMT, Rusty Shackleford <··@natchie.mine.nu> wrote:

>     CL-USER> (let ((h (make-hash-table )))
>                (setf (gethash "aaa" h) 1)
>                (format t "value stored with key ~A is ~A." 
>                 "aaa" (gethash "aaa" h)))
>     value stored with key aaa is NIL.
>     NIL

  * (let ((h (make-hash-table :test #'equal)))
      (setf (gethash "foo" h) 1)
      (gethash "foo" h))

  1
  T

> I thought I understood hashes because I used them in Perl, but
> apparently I'm missing something basic here.

The basic difference is that in Lisp you can specify a hash test which
is used to compare two keys and decide whether they're equal - the
default (in your case above) is EQL.  In Perl you can't do this -
IIRC, hash keys are always (converted to) strings, and the test is
always the function eq.

  <http://www.gigamonkeys.com/book/collections.html>
  <http://www.lispworks.com/documentation/HyperSpec/Body/18_.htm>

Cheers,
Edi.

-- 

Lisp is not dead, it just smells funny.

Real email: (replace (subseq ·········@agharta.de" 5) "edi")