Shammer's Philosophy

My private adversaria

push を使って dictionary を実現する

何かデータを一箇所に保存しておく、そんな箱を簡単に実現したい。昔、Lisp 独自 dictionary version 20111105 - Shammerismで書いたものがあるが、あまりにイケていない。。。push を使うと、もっとシンプルになった。

? (defparameter table nil)
TABLE
? (push (cons "Key1" "AAA") table)
(("Key1" . "AAA"))
? (push (cons "Key2" "BBB") table)
(("Key2" . "BBB") ("Key1" . "AAA"))
? (defun get-value (key)
(remove-if-not #'(lambda (s) (string= (car s) key)) table))
GET-VALUE
? (get-value "Key1")
(("Key1" . "AAA"))
? (get-value "Key2")
(("Key2" . "BBB"))
? (get-value "Key3")
NIL
? (defun push-value (key value)
(let ((tmp (remove-if #'(lambda (s) (string= (car s) key)) table)))
  (push (cons key value) tmp)
  (setf table tmp)))
PUSH-VALUE
? (push-value "Key1" "000")
(("Key1" . "000") ("Key2" . "BBB"))
? (push-value "Key3" "CCC")
(("Key3" . "CCC") ("Key1" . "000") ("Key2" . "BBB"))
? 

空の変数に、(push (cons KEY VALUE) table)という感じでどんどん放り込んでいくだけ。だが、これだと同じ KEY が重複してしまうので、push の前に工夫が必要なので、push-value という関数を用意した。なんか value というのは変か。。。HashTable でも同じようなことができるが、HashTable だと文字列をキーにできなかった記憶がある。これなら文字列もキーにできる。