Created
October 27, 2013 23:03
-
-
Save mmontone/7188967 to your computer and use it in GitHub Desktop.
Common Lisp hash table syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun read-separator (str) | |
(let | |
((*readtable* (copy-readtable *readtable* nil))) | |
(set-macro-character #\, (lambda (stream char) | |
(declare (ignore char) (ignore stream)) | |
'break)) | |
(read str nil))) | |
(set-macro-character #\{ | |
(lambda (str char) | |
(declare (ignore char)) | |
(let | |
((*readtable* (copy-readtable *readtable* nil))) | |
(set-macro-character #\} (lambda (stream char) | |
(declare (ignore char) (ignore stream)) | |
'end)) | |
(let | |
((pairs (loop for key = (read str nil nil t) | |
for sep = (read str nil nil t) | |
for value = (read str nil nil t) | |
for end? = (read-separator str) | |
do (when (not (eql '=> sep)) (error "Expected =>, did not get")) | |
do (when (not (or (eql 'end end?) (eql 'break end?))) (error "Expected , or }")) | |
collect (list key value) | |
while (not (eql 'end end?)))) | |
(retn (gensym))) | |
`(let | |
((,retn (make-hash-table :test #'equal))) | |
,@(mapcar | |
(lambda (pair) | |
`(setf (gethash ,(car pair) ,retn) ,(cadr pair))) | |
pairs) | |
,retn))))) | |
(set-pprint-dispatch 'hash-table | |
(lambda (str ht) | |
(format str "{~{~{~S => ~S~}~^, ~}}" | |
(loop for key being the hash-keys of ht | |
for value being the hash-values of ht | |
collect (list key value))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment