70 exercises in 20 chapters, from first s-expressions to restarts, macros, CLOS, and a tiny Lisp interpreter. Each exercise ships broken with a solved twin and a hint. Includes a watch-mode runner, a plain-CL check harness, a nix flake, and verification tooling. All plain SBCL, no dependencies.
31 lines
1.1 KiB
Common Lisp
31 lines
1.1 KiB
Common Lisp
;;; HASH TABLES 2: IS THE KEY THERE?
|
|
;;;
|
|
;;; GETHASH returns TWO values: the stored value, and T or NIL for
|
|
;;; presence. A stored NIL is different from an absent key!
|
|
;;; (multiple-value-bind (value present) (gethash key table) ...)
|
|
|
|
;; TODO: T when KEY exists in TABLE (even with a NIL value), NIL
|
|
;;; otherwise.
|
|
(defun has-key-p (key table)
|
|
(gethash key table))
|
|
|
|
;; TODO: The value for KEY, or DEFAULT when the key is absent.
|
|
(defun lookup (key table default)
|
|
(gethash key table))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check (let ((table (make-hash-table)))
|
|
(setf (gethash 'a table) 1
|
|
(gethash 'b table) nil)
|
|
(and (has-key-p 'a table)
|
|
(has-key-p 'b table)
|
|
(not (has-key-p 'c table)))))
|
|
(check (let ((table (make-hash-table)))
|
|
(setf (gethash 'a table) 1)
|
|
(and (eql 1 (lookup 'a table 0))
|
|
(eql 99 (lookup 'c table 99)))))
|