Lisp 独自 dictionary version 20111025
Java でいう Hashtable や HashMap のようなものが欲しい。でも、実際にはキーはそんなに複雑じゃなくていい。せいぜい登録することになるであろうデータも100もいかないだろうから。ドット対のデータを並べてそれっぽく見せかける実装を書いた。
(defun add-keyvalue-to-dictionary (source key value) (append source (list (cons key value)))) (defun add-keypair-to-dictionary (source pair) (append source (list pair))) (defun show-dictionary (dictionary) (format t "==========~%") (dolist (x dictionary) (format t "~A:~A~%" (car x) (cdr x))) (format t "==========~%")) (defun get-keypair-from-dictionary (target key) (dolist (x target) (when (string-equal key (car x)) (format t "~A~%" (cdr x))))) (defun get-keyvalue-from-dictionary (target key) (cdr (get-keypair-from-dictionary target key))) (defun remove-keypair-from-dictionary (target key) (let ((new-dictionary nil)) (dolist (x target) (unless (string-equal key (car x)) (setf new-dictionary (add-keypair-to-dictionary new-dictionary x)))) new-dictionary))
とりあえず、
- key と value のペア(ドット対セル)を追加する
- 内容を表示する
- ペア(ドット対セル)を追加する
- key をキーにしてペア(ドット対セル)を削除
を実装。以下は簡単な使用例。
(defparameter *data* nil) (setf *data* (add-keyvalue-to-dictionary *data* "a" 0)) (setf *data* (add-keyvalue-to-dictionary *data* "b" 1)) (setf *data* (add-keyvalue-to-dictionary *data* "c" 2)) (setf *data* (add-keyvalue-to-dictionary *data* "d" 3)) (show-dictionary *data*) (format t "~A~%" (get-keyvalue-from-dictionary *data* "d")) (setf *data* (remove-keypair-from-dictionary *data* "b")) (show-dictionary *data*) (format t "~A~%" (get-keyvalue-from-dictionary *data* "b")) (quit)