[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: hash strangeness
From: |
Pascal J. Bourguignon |
Subject: |
Re: hash strangeness |
Date: |
Sun, 02 Nov 2014 19:43:25 +0100 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux) |
Tom <adatgyujto@gmail.com> writes:
> Here's a code which gives me some headache. It's silly, because
> it was shortened from a longer code to demonstrate the problem.
>
> It is supposed to count something in elisp functions, though
> the condition is removed, so with this code the count should be
> 1 for every function.
>
> So the code checks if the function is already in the hash
> and if not then it inserts new info for that function:
>
>
> (let ((h (make-hash-table :test 'equal)))
> (mapatoms
> (lambda (s)
> (let* ((name (symbol-name s))
> (info (gethash name h)))
>
> (unless info
> (setq info '(count 0)))
>
> (setq info (plist-put info
> 'count (1+ (plist-get info 'count))))
>
> (puthash name info h))))
>
> (pop-to-buffer "*testout*")
> (erase-buffer)
> (maphash (lambda (name info)
> (insert (format "%s %s" (plist-get info 'count) name) "\n"))
> h))
>
>
> The new info is newly created in the lambda function (it is
> a plist, because in the real code there are other fields too),
> yet for some reason the same info structure is used for all
> iterations.
>
> I tried to debug it and at the "(unless info" part info is nil
> and then it is set to the previous value, though it should be a
> new value.
>
> Am I missing something here?
You've identified the problem with the literal list. However, you could
write it much simplier:
(require 'cl) ; always
(let ((h (make-hash-table :test 'eql)))
(mapatoms (lambda (name)
(incf (getf (gethash name h) 'count 0))))
(pop-to-buffer "*testout*")
(erase-buffer)
(maphash (lambda (name info)
(insert (format "%s %s\n" (getf info 'count) name)))
h))
In the current emacs lisp, there's no point in using symbol-name strings
as key in the hash-table: just use symbols with eql as test.
Notice that in emacs lisp:
(not (equal (symbol-name :hello) (symbol-name 'hello)))
It would be different if emacs lisp had packages like Common Lisp.
--
__Pascal Bourguignon__ http://www.informatimago.com/
“The factory of the future will have only two employees, a man and a
dog. The man will be there to feed the dog. The dog will be there to
keep the man from touching the equipment.” -- Carl Bass CEO Autodesk
- Re: hash strangeness, (continued)
- Re: hash strangeness, Tom, 2014/11/02
- Re: hash strangeness, Thien-Thi Nguyen, 2014/11/02
- Message not available
- Re: hash strangeness, Barry Margolin, 2014/11/02
- Re: hash strangeness, Tom, 2014/11/03
- Re: hash strangeness, Robert Thorpe, 2014/11/03
- Re: hash strangeness, Michael Heerdegen, 2014/11/03
- RE: hash strangeness, Drew Adams, 2014/11/03
- Re: hash strangeness, Marcin Borkowski, 2014/11/04
Re: hash strangeness,
Pascal J. Bourguignon <=