Artificial
Intelligence

Fall 2011
course
navigation

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?
Jim: http://frank.kank.net/essays/hash.html has a recipe to do just that, including the curly braces. And here's a "dict" function that's more lisp-ish and prob'ly good enough:
(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
http://cs.marlboro.edu/ courses/ fall2011/ai/ wiki/ questions
last modified Monday September 19 2011 7:54 pm EDT