You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LISP使用if语句返回NIL如何避免?以calculate-bill函数实现为例

问题原因

  1. Common Lisp 中,(format t ...) 执行输出操作后,返回值固定为NIL
  2. 你定义的calculate-bill函数没有显式声明返回值,默认会返回最后一行表达式的执行结果,也就是第二个if语句的返回值,无对应分支的if语句返回值同样是NIL
  3. 调用函数时外层套了write,相当于把函数返回的NIL又打印了一遍,所以出现了多余的后缀

修复方案

方案1:最简修改,直接调用函数

你的函数内部已经通过format完成了打印操作,不需要再用write输出函数返回值,直接调用即可,修改调用部分代码:

(calculate-bill 200 50)
(terpri)
(calculate-bill 200)

方案2:优化函数逻辑(更规范的写法)

合并冗余的if判断,同时可显式指定函数返回空值,避免后续误打印返回值:

(defun calculate-bill (amount &optional discount)
  (let ((total (if discount (- amount discount) amount)))
    (format t "Total bill is ~d." total)
    ;; 显式返回空多值,不会产生可打印的返回内容
    (values)))

;; 直接调用即可
(calculate-bill 200 50)
(terpri)
(calculate-bill 200)

内容的提问来源于stack exchange,提问作者Aniruddha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:15:01