Shammer's Philosophy

My private adversaria

Lisp 独自 dictionary version 20111102

Lisp 独自 dictionary version 20111029 - Shammerismに手を加え、show-dictionary を見やすくしてみた。具体的には sort するように改良。最終的に以下のようになった。

(defun add-keypair-to-dictionary (source pair)
  (append source (list pair)))

(defun add-keyvalue-to-dictionary (source key value)
  (if (null source)
      (list (cons key value))
      (let ((new-dictionary (list (cons key value))))
	(dolist (x source)
	  (unless (string-equal key (car x))
	    (setf new-dictionary (add-keypair-to-dictionary new-dictionary x))))
	new-dictionary)))

(defun show-dictionary (dictionary)
  (format t "==========~%")
  (let ((dictionary-copied (copy-list dictionary)))
    (dolist (x (sort dictionary-copied #'string<= :key #'car))
      (format t "~A~%" 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))

最初はうまく表示されず大変だった。というか、sort のたびに既存のデータが欠如することがあり、その理由を色々調べた。結果としては、sort は破壊的(destructive)というのを見落としていただけだったのだが。もともとのデータが壊れないように sort の前に copy-list でデータをコピーし、コピーしたデータを対象に sort するようにした。コピーしたデータなら壊れても後の処理に影響しない。とりあえずこんなもんだろうか。