Common Lisp譯本筆記2之第三章:簡單的數據庫實現(源碼)

源代碼:

;;定義一個全局變量,用於存放數據
(defvar *db* nil)

;;製作一個CD需要的信息
(defun make-cd (title artist rating ripped)
  (list :title title :artist artist :rating rating :ripped ripped))

;;將一條CD信息記錄到全局變量中
(defun add-record (cd) (push cd *db*))

;;格式化輸出數據
(defun dump-db ()
  (format t "~{~{~A: ~10t~A~%~}~%~}" *db*))

;;交互信息
(defun prompt-read (prompt)
  (format *query-io* "~A: " prompt)
  (force-output *query-io*)
  (read-line *query-io*))

;;交互獲取CD信息
(defun prompt-for-cd ()
  (make-cd
   (prompt-read "Title")
   (prompt-read "Artist")
   (or (parse-integer (prompt-read "Rating") :junk-allowed t) 0)
   (y-or-n-p "Ripped [y/n]: ")))

;;添加任意個CD信息
(defun add-cds ()
  (loop (add-record (prompt-for-cd))
     (if (not (y-or-n-p "Another? [y/n]: ")) (return))))

;;將所有CD信息保存到文件中
(defun save-db (filename)
  (with-open-file (out filename
		       :direction :output
		       :if-exists :supersede)
    (with-standard-io-syntax
      (print *db* out))))

;;加載文件中的CD信息
(defun load-db (filename)
  (with-open-file (in filename)
    (with-standard-io-syntax
      (setf *db* (read in)))))
;;通用查詢
(defun select (selector-fn)
  (remove-if-not selector-fn *db*))

;;根據artist查詢
(defun artist-selector (artist)
  #'(lambda (cd) (equal (getf cd :artist) artist)))
;;比較根據鍵比較值
(defun make-comparison-expr (field value)
  `(equal (getf cd ,field) ,value))

;;循環比較
(defun make-comparisons-list (fields)
  (loop while fields
     collecting (make-comparison-expr (pop fields) (pop fields))))

;;定義一個where宏
(defmacro where (&rest clauses)
  `#'(lambda (cd) (and ,@(make-comparisons-list clauses))))
;;刪除函數
(defun delete-rows (selector-fn)
  (setf *db* (remove-if selector-fn *db*)))

在eamcs中使用C-x C-f新建一個文件,輸入文件名之後回車。



將上述源代碼粘貼複製到此文件中,使用C-x C-s保存文件。

保存完成之後,在emacs中使用M-x輸入slime回車,啓動REPL(lisp環境)。



在REPL中輸入:(load   "CD.lisp")回車,加載保存的文件。



到這一步,則可使用上述源碼中的所有函數,接下來進行測試。

測試代碼如下:

CL-USER> *db*
NIL
CL-USER> (add-cds)
Title: BangBom
Artist: Are
Rating: 5


Ripped [y/n]:  (y or n) y


Another? [y/n]:  (y or n) y
Title: So happy
Artist: Bre
Rating: 8


Ripped [y/n]:  (y or n) n


Another? [y/n]:  (y or n) n


NIL
CL-USER> (dump-db)
TITLE:    So happy
ARTIST:   Bre
RATING:   8
RIPPED:   NIL


TITLE:    BangBom
ARTIST:   Are
RATING:   5
RIPPED:   T


NIL
CL-USER> (save-db "CD.db")
((:TITLE "So happy" :ARTIST "Bre" :RATING 8 :RIPPED NIL)
 (:TITLE "BangBom" :ARTIST "Are" :RATING 5 :RIPPED T))
CL-USER> (select (where :title "BangBom"))
((:TITLE "BangBom" :ARTIST "Are" :RATING 5 :RIPPED T))
CL-USER> (select (where :artist "Bre"))
((:TITLE "So happy" :ARTIST "Bre" :RATING 8 :RIPPED NIL))
CL-USER> 



發佈了79 篇原創文章 · 獲贊 20 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章