2010-09-03 93 views
2

我想學習Lisp,作爲我的CS1課程的補充,因爲班級對我來說太慢了。我選擇了「Practical Common Lisp」,這本書迄今爲止是一本很好的書,但我在獲得一些示例工作方面遇到了一些麻煩。舉例來說,如果我下面的文件加載到REPL:功能錯誤地返回零

;;;; Created on 2010-09-01 19:44:03 

(defun makeCD (title artist rating ripped) 
    (list :title title :artist artist :rating rating :ripped ripped)) 

(defvar *db* nil) 

(defun addRecord (cd) 
    (push cd *db*)) 

(defun dumpDB() 
    (dolist (cd *db*) 
    (format t "~{~a:~10t~a~%~}~%" cd))) 

(defun promptRead (prompt) 
    (format *query-io* "~a: " prompt) 
    (force-output *query-io*) 
    (read-line *query-io*)) 

(defun promptForCD() 
    (makeCD 
     (promptRead "Title") 
     (promptRead "Artist") 
     (or (parse-integer (promptRead "Rating") :junk-allowed t) 0) 
     (y-or-n-p "Ripped [y/n]: "))) 

(defun addCDs() 
    (loop (addRecord (promptForCD)) 
     (if (not (y-or-n-p "Another? [y/n]: ")) (return)))) 

(defun saveDB (fileName) 
    (with-open-file (out fileName 
      :direction :output 
      :if-exists :supersede) 
     (with-standard-io-syntax 
      (print *db* out)))) 

(defun loadDB (fileName) 
    (with-open-file (in fileName) 
     (with-standard-io-syntax 
      (setf *db* (read in))))) 

(defun select (selectorFn) 
    (remove-if-not selectorFn *db*)) 

(defun artistSelector (artist) 
    #'(lambda (cd) (equal (getf cd :artist) artist))) 

和查詢使用(select (artistSelector "The Beatles"))「數據庫」,即使我確實有數據庫中的一個條目,其中:artist等於"The Beatles",在函數返回NIL

我在這裏做錯了什麼?

+0

注意,EQUAL是區分大小寫的 – 2010-09-03 18:20:29

回答

4

沒什麼,AFAICT:

 
$ sbcl 
This is SBCL 1.0.34.0... 

[[pasted in code above verbatim, then:]] 

* (addRecord (makeCD "White Album" "The Beatles" 5 t)) 

((:TITLE "White Album" :ARTIST "The Beatles" :RATING 5 :RIPPED T)) 
* (select (artistSelector "The Beatles")) 

((:TITLE "White Album" :ARTIST "The Beatles" :RATING 5 :RIPPED T)) 
+0

當然,如果你從來沒有打電話的addRecord然後的確,選擇將返回NIL。 – 2010-09-03 18:39:48

+0

好的,所以當我通過addCDs函數添加記錄時,問題似乎就會發生,但直接調用addRecord時不會發生。 – Andy 2010-09-03 19:07:30

+0

我想通了。使用addCDs函數時,不要用引號括起來輸入字符串。 – Andy 2010-09-03 19:17:47

1
CL-USER 18 > (addcds) 
Title: Black Album 
Artist: Prince 
Rating: 10 
Title: White Album 
Artist: The Beatles 
Rating: 10 
NIL 

CL-USER 19 > (select (artistSelector "The Beatles")) 
((:TITLE "White Album" :ARTIST "The Beatles" :RATING 10 :RIPPED T))