【问题标题】:How to call a function that prints a list in lisp?如何调用在 lisp 中打印列表的函数?
【发布时间】:2019-05-04 08:50:13
【问题描述】:

我试图在 lisp 中调用一个函数,将它的参数分配给一个列表并将它们打印到控制台,但没有将任何内容打印到控制台。 代码如下所示

(defun make-cd (title artist rating ripped)
  (list :title title :artist artist :rating rating :ripped ripped))
(make-cd "Roses" "Kathy Mattea" 7 t)

调用make-cd函数应该返回

(:TITLE "Roses" :ARTIST "Kathy Mattea" :RATING 7 :RIPPED T)

我该如何解决这个问题?

【问题讨论】:

  • 如果你从 REPL 调用 (make-cd ...) 会自动打印结果,也许这对测试来说已经足够了。你想一直打印一些东西吗?

标签: common-lisp


【解决方案1】:

您可以通过将值推送到 CD 列表来简单地返回该值,我相信您最初使用的书中的示例会这样做(稍后您将在打印它们时格式化数据库中的每张 CD):

(defun make-cd (artist title rating ripped)
   (push (list :artist artist :title title :rating rating :ripped ripped)
     *cds*))

因此,如果我调用该函数,它会将 CD 的内容返回到控制台:

(make-cd "Cece Winans" "Mercy Said No" 10 t)
((:ARTIST "Cece Winans" :TITLE "Mercy Said No" :RATING 10 :RIPPED T))

在您推送到 CD 数据库的 CD 的情况下,该值将返回到控制台。

【讨论】:

    【解决方案2】:

    你可以看这里:What's the difference between write, print, pprint, princ, and prin1?

    format 也可用于在 REPL 或任何输出流(文件、管道等)中打印列表。

    (format t "~a" (list "Peter" 15 "Steven" 59.4d0))
        => (Peter 15 Steven 59.4d0)
    

    您可以查看 CLHS 中的材料:http://www.lispworks.com/documentation/lw50/CLHS/Body/f_format.htm 或者在 Practical Common Lisp 中,我相信你从中得到了你的例子:http://www.gigamonkeys.com/book/a-few-format-recipes.html

    【讨论】:

    • format t 是将列表打印到控制台的好方法。你说得对,我从教科书 Practical Common Lisp 中得到了示例。
    【解决方案3】:
    (defun make-cd (title artist rating ripped)
      (print (list :title title :artist artist :rating rating :ripped ripped)))
    

    抱歉解决了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多