【问题标题】:How can I avoid the nil printed in the end?我怎样才能避免最后打印的 nil ?
【发布时间】:2013-06-30 01:33:46
【问题描述】:

我已经编写了这个打印出板子状态的函数,但最后,由于没有返回这个函数打印一个零!

功能:

(defun show-board (board)
        (dotimes (number 8)
            (dotimes (number2 8)
                (let ((pos (aref board number number2))) 
                    (cond
                        ((equal pos 0) (format t "~a " "B"))   
                        ((equal pos 1) (format t "~a " "P"))
                        (t (format t "~a " "L")))))
                    (format t "~%")))

板是一个 8x8 阵列!

命令行上的函数调用输出:

B P B P B P B P
P B P B P B P B
B P B P B P B P
P B P B P B P B
B P B P B P B P
P B P B P B P B
B P B P B P B P
P B P B P B P B
NIL

我怎样才能摆脱 NIL??

【问题讨论】:

  • 这很挑剔,但值得指出的是,show-board 没有打印NIL。如果您在 REPL 中并执行 CL-USER> (show-board ...),您将看到 nil,但如果您执行 CL-USER> (progn (show-board) 2),则不会(但您会看到 2)。 REPL 打印最后一个评估表单的值。这意味着从任何调用show-board 的应用程序代码中,您都不会看到NIL,因此虽然它对REPL 来说是一个不错的选择,但您通常不需要担心。即使使用(values),您仍然会得到(list (show-board)) => (NIL)

标签: arrays format lisp null read-eval-print-loop


【解决方案1】:

您可以摆脱代码中的多种格式:

通常在函数式语言中我会返回一个值。退回电路板本身是有意义的。由于这样的函数通常是从游戏逻辑中调用的,因此返回值可能很有用,而对于输出来说并不重要。

(defun show-board (board)
  (dotimes (i 8)
    (dotimes (j 8)
      (write-string (case (aref board i j)
                      (0         "B ")
                      (1         "P ")
                      (otherwise "L "))))
    (terpri))
  board)

【讨论】:

    【解决方案2】:

    添加(values) 作为dotimes 的返回表单即可:

    (dotimes (number 8 (values))
       .....)
    

    毕竟,show-board 确实不返回任何值,对吧?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 2022-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多