function - 该函数未定义 : IF (Emacs Lisp)

标签 function lisp

为什么这告诉我“if”是一个未定义的函数?

    (defun sum (n m)
      (if (and (integerp n) (integerp m))
         (cond
          ((zerop n) m)
          ((zerop m) n)
            (if (< n 0)
              (sum (+ n 1) (- m 1))
              (sum (- n 1) (+ m 1))))
        nil))

最佳答案

应用常规范式和一些注释后,您的代码是:

(defun sum (n m)
  ;; if n and m are integers
  (if (and (integerp n) (integerp m))
      ;; then …
      (cond
        ;; first case: if the expression `(zerop n)` is true, then return m
        ((zerop n) m)
        ;; second case: if the expression `(zerop m)` is true, then return n
        ((zerop m) n)
        ;; third case: if the expression `if` is true, then
        ;; evaluate (< n 0), evaluate (sum (+ n 1) (- m 1)),
        ;; and return (sum (- n 1) (+ m 1))
        (if (< n 0)
            (sum (+ n 1) (- m 1))
            (sum (- n 1) (+ m 1))))
      ;; else return nil
      nil))

当我在 emacs 中评估这个定义,然后尝试评估,例如 (sum 2 3) 时,我得到的错误实际上是:

Debugger entered--Lisp error: (void-variable if)
  (cond ((zerop n) m) ((zerop m) n) (if (< n 0) (sum ... ...) (sum ... ...)))
  (if (and (integerp n) (integerp m)) (cond (... m) (... n) (if ... ... ...)) nil)
  sum(2 3)
  eval((sum 2 3))
  eval-last-sexp-1(nil)
  eval-last-sexp(nil)
  call-interactively(eval-last-sexp nil nil)

因为第三个子句试图将 if 的值作为变量。我希望您想要的是一个otherwise子句。使第三个子句的形式与其他子句相同,条件始终为真,例如 t:

(defun sum (n m)
  (if (and (integerp n) (integerp m))
      (cond
        ((zerop n) m)
        ((zerop m) n)
        (t (if (< n 0)
               (sum (+ n 1) (- m 1))
               (sum (- n 1) (+ m 1)))))
      nil))

然后(sum 2 3)返回5

关于function - 该函数未定义 : IF (Emacs Lisp),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18939475/

相关文章:

c++ - 理解这种递归的困难

javascript - 在函数之间传递值

postgresql - 根据输入数据填充 x、y 或 long、lat 字段,并根据输入创建点

lisp - 为什么 setq 削减了我的列表

Python/Kivy - 替换调用函数的另一个屏幕中的标签值

更改 HTML 的 JavaScript 函数不起作用

c# - 我们如何将这个Scheme (Lisp) 函数转换为C#

lisp - 普通口齿不清 : function A passes a function to B which passes it to C which invokes the function

lisp - 将输出打印到文件中还是不打印输出?

Lisp:生成 10 个随机整数的列表