Sujet : Accumulating in hash-table
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lispDate : 22. Jul 2024, 21:47:49
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v7md14$pr7r$1@dont-email.me>
User-Agent : XanaNews/1.18.1.6
(defun distribution1 (items values test)
(let ((table (make-hash-table :test test)))
(loop for item in items
for value in values
do (incf (gethash item table 0) value))
(let ((items-list nil))
(maphash (lambda (item sum-value)
(push (cons item sum-value) items-list))
table)
(sort items-list #'> :key #'cdr))))
An example call:
CL-USER 58 > (distribution1 '("a" "b" "c" "b" "a" "f" "e" "g"
"h" "k" "z" "k" "r" "u" "f")
'(1 5 8 7 14 8 3 7 9 4 3 21 5 7 9)
#'equal)
(("k" . 25) ("f" . 17) ("a" . 15) ("b" . 12) ("h" . 9) ("c" . 8)
("g" . 7) ("u" . 7) ("r" . 5) ("e" . 3) ("z" . 3))
Gauche Scheme
(define (distribution1 items values test)
(let1 table (make-hash-table test)
(for-each
(^(item value)
(hash-table-update! table item (cut + value <>) 0))
items
values)
(sort (hash-table->alist table) > cdr)))
(distribution1 '("a" "b" "c" "b" "a" "f" "e" "g"
"h" "k" "z" "k" "r" "u" "f")
'(1 5 8 7 14 8 3 7 9 4 3 21 5 7 9)
'equal?)
===>
(("k" . 25) ("f" . 17) ("a" . 15) ("b" . 12) ("h" . 9) ("c" . 8) ("g" . 7)
("u" . 7) ("r" . 5) ("z" . 3) ("e" . 3))