45 lines
1.2 KiB
Common Lisp
45 lines
1.2 KiB
Common Lisp
;;; HASH TABLES 4: MAPHASH
|
|
;;;
|
|
;;; MAPHASH walks every key and value pair, handing each to a
|
|
;;; function of two arguments - the key first:
|
|
;;;
|
|
;;; (maphash (lambda (key value) ...) table)
|
|
;;;
|
|
;;; The order of the walk is not promised, so build answers that do
|
|
;;; not care about order.
|
|
|
|
(defparameter *stock*
|
|
(let ((table (make-hash-table)))
|
|
(setf (gethash 'tea table) 2
|
|
(gethash 'coffee table) 3
|
|
(gethash 'cocoa table) 4)
|
|
table))
|
|
|
|
;; TODO: The total number of items in stock.
|
|
(defun stock-total ()
|
|
(let ((total 0))
|
|
(maphash (lambda (key value)
|
|
(incf total key))
|
|
*stock*)
|
|
total))
|
|
|
|
;; TODO: The keys of TABLE, as a list.
|
|
(defun keys-of (table)
|
|
(let ((keys '()))
|
|
(maphash (lambda (key value)
|
|
(push value keys))
|
|
table)
|
|
keys))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check-equal 9 (stock-total))
|
|
(check (let ((keys (keys-of *stock*)))
|
|
(and (= 3 (length keys))
|
|
(member 'tea keys)
|
|
(member 'coffee keys)
|
|
(member 'cocoa keys))))
|