questions
Anyone in the class can edit this page.
Brownie points for both good questions
and good answers.
Or you can just email Jim.
lisp hash tables
Sep 16 or so:
Alex : How can you initialize a lisp hash table with something like the {'a' :1, 'b':2} in python?
(defun dict (&rest args)
"Returns a hash-table from :key value args"
; Usage:
; > (setf jim (dict :name "Jim" age 52))
; > (maphash (lambda (key val) (format t " ~s ~s ~%" key val)) jim)
; :name "Jim"
; :age 52
(assert (evenp (length args))
(args) nil "dict: ~s must have an even number of args." args)
(do ((dictionary (make-hash-table)))
((null args) dictionary)
(let* ((a (pop args)) (b (pop args)))
(setf (gethash a dictionary) b))))
For really simple cases, you can also type a hash directly using the #s() form that the interactive lisp outputs for hashes, though the stuff within the #s() isn't typically evaluated.
> (setf h (make-hash-table))
> (setf (gethash 'name h) 'bob)
> (setf (gethash 'kids h) '(joe jane))
> h
#S(HASH-TABLE :TEST FASTHASH-EQL (KIDS . (JOE JANE)) (NAME . BOB))
So we can do things like
> (setf g #s(hash-table :test eq (name . harry) (:age . 42)))
> (gethash 'name g)
HARRY