Lisp 函数错误地返回Nil
我现在正试图学习Lisp,作为CS1课程的补充,因为课程对我来说太慢了。我学习了《实用通用Lisp》,到目前为止,这本书是一本很棒的书,但我在获得一些示例时遇到了一些困难。例如,如果我将以下文件加载到REPL中:Lisp 函数错误地返回Nil,lisp,common-lisp,read-eval-print-loop,sbcl,Lisp,Common Lisp,Read Eval Print Loop,Sbcl,我现在正试图学习Lisp,作为CS1课程的补充,因为课程对我来说太慢了。我学习了《实用通用Lisp》,到目前为止,这本书是一本很棒的书,但我在获得一些示例时遇到了一些困难。例如,如果我将以下文件加载到REPL中: ;;;; Created on 2010-09-01 19:44:03 (defun makeCD (title artist rating ripped) (list :title title :artist artist :rating rating :ripped ripp
;;;; 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)))
并使用(选择(artistSelector“the Beatles”)
查询“数据库”),即使我在数据库中确实有一个条目,其中:artist
等于“the Beatles”
,函数返回NIL
我在这里做错了什么?没什么,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))
$sbcl
这是SBCL 1.0.34.0。。。
[[逐字粘贴在上面的代码中,然后:]
*(addRecord(制作CD“白色专辑”“披头士”5T))
(:标题“白色专辑”:艺术家“披头士”:评级5:T))
*(选择(艺人选择“披头士”))
(:标题“白色专辑”:艺术家“披头士”:评级5:T))
请注意,EQUAL是区分大小写的,当然,如果您从未调用addRecord,那么select将返回NIL。好的,当我通过
addCDs
函数添加记录时,问题似乎会出现,但当我直接调用addRecord
时,问题就不会出现了。我已经解决了。使用addCDs
函数时,您不会在引号中输入字符串。Heh。我完全错过了(addcd)
。我查找选择,如问题中所示,然后回过头来看看我需要如何称呼它。哎呀!
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))