From: mtg
Subject: increment hash value
Date: 
Message-ID: <1177487317.819780.94390@r3g2000prh.googlegroups.com>
Moin,

I try to count list items with the following function:

(defun count-items (lst)
  (let ((ht (make-hash-table)))
    (loop :for item :in lst :do
       (incf (gethash item ht 0))
       :finally
       (maphash #'(lambda (k v) (format t "~A: ~A~%" k v)) ht))))

(count-tags '('foo 'bar 'foo)) gives me

'FOO: 1
'BAR: 1
'FOO: 1

but I need
'FOO: 2
'BAR: 1

What ist wrong with my function? Is there a better way to count items?
Many thanks
Matthias
From: Edi Weitz
Subject: Re: increment hash value
Date: 
Message-ID: <u4pn46gah.fsf@agharta.de>
On 25 Apr 2007 00:48:37 -0700, mtg <······@gmail.com> wrote:

> Moin,

Moin... :)

> I try to count list items with the following function:
>
> (defun count-items (lst)
>   (let ((ht (make-hash-table)))
>     (loop :for item :in lst :do
>        (incf (gethash item ht 0))
>        :finally
>        (maphash #'(lambda (k v) (format t "~A: ~A~%" k v)) ht))))
>
> (count-tags '('foo 'bar 'foo)) gives me
>
> 'FOO: 1
> 'BAR: 1
> 'FOO: 1
>
> but I need
> 'FOO: 2
> 'BAR: 1
>
> What ist wrong with my function?

Try (COUNT-TAGS '(FOO BAR 'FOO)) instead.  Look at this

  CL-USER 4 > '(foo bar baz)
  (FOO BAR BAZ)

  CL-USER 5 > '('foo 'bar 'baz)
  ((QUOTE FOO) (QUOTE BAR) (QUOTE BAZ))  

and try to figure out yourself why your function behaves differently
for the second input.

HTH,
Edi.

-- 

Lisp is not dead, it just smells funny.

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