【问题标题】:Function Erroneously Returning Nil函数错误地返回 Nil
【发布时间】:2011-04-07 21:50:06
【问题描述】:

我现在正在尝试学习 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

我在这里做错了什么?

【问题讨论】:

  • 注意 EQUAL 区分大小写

标签: lisp common-lisp read-eval-print-loop sbcl


【解决方案1】:

没什么,AFAICT:

$ sbcl 这是 SBCL 1.0.34.0... [[逐字粘贴在上面的代码中,然后:]] * (addRecord (makeCD "White Album" "The Beatles" 5 t)) ((:TITLE“白色专辑”:ARTIST“披头士”:RATING 5:RIPPED T)) * (select (artistSelector "The Beatles")) ((:TITLE“白色专辑”:ARTIST“披头士”:RATING 5:RIPPED T))

【讨论】:

  • 当然,如果你从不调用 addRecord 那么确实,select 将返回 NIL。
  • 好的,所以我通过addCDs函数添加记录时似乎会出现问题,但当我直接调用addRecord时不会出现问题。
  • 我想通了。使用addCDs函数时,不要输入用引号括起来的字符串。
  • 嘿。我完全错过了(addCDs)。我在问题中寻找select,然后回头看看我需要调用它。糟糕!
【解决方案2】:
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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2016-08-13
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2020-01-05
    相关资源
    最近更新 更多