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

Lisp高阶函数传参报错求助:调用自定义函数时出现异常

问题原因分析与解决

核心错误点

你的问题出在高阶函数的参数传递和调用方式上,具体有三个关键问题:

  1. 传递了函数执行结果而非函数对象
    调用(landslide (ask-number) (count-down))时:

    • (ask-number)会立即执行,返回用户输入的数字,而非ask-number函数本身;
    • (count-down)直接调用却未传参,而你的count-down定义需要一个正整数参数,这直接触发了“参数数量无效”的报错。
  2. 未使用#'获取函数对象
    在Common Lisp中,要传递函数作为参数,必须用#'(或function特殊运算符)显式获取函数对象。直接写函数名会被当成变量,而非函数。

  3. 高阶函数内部未用funcall/apply调用传入的函数
    如果你的landslide定义是直接调用参数(比如(fn2 (fn1))),会因为fn1、fn2是变量,不能直接作为函数调用,这会导致编译警告。

修正后的代码示例

1. 正确的基础函数定义(参考Paul Graham的实现)

(defun ask-number ()
  (format t "请输入一个正整数: ")
  (let ((n (read)))
    (if (and (integerp n) (> n 0))
        n
        (progn
          (format t "输入无效,请重新输入~%")
          (ask-number)))))

(defun count-down (n)
  (if (> n 0)
      (progn
        (format t "~a " n)
        (count-down (- n 1)))
      (format t "0~%")))

2. 正确的高阶函数landslide定义

(defun landslide (input-func count-func)
  ;; 使用funcall调用传入的函数对象
  (funcall count-func (funcall input-func)))

3. 正确的调用方式

(landslide #'ask-number #'count-down)

关键说明

  • #'ask-number表示获取ask-number的函数对象,作为参数传递给landslide;
  • funcall input-func执行输入函数,获取用户输入的正整数;
  • funcall count-func ...将数字传递给倒计时函数执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:06:25