【问题标题】:How do I evaluate "&optional argument" in emacs lisp?如何评估 emacs lisp 中的“&可选参数”?
【发布时间】:2015-07-28 00:11:35
【问题描述】:

我不明白如何在 emacs lisp 中评估“&可选参数”。

我的代码是:

(defun test-values (a &optional b)

  "Function with an optional argument (default value: 56) that issues a 
message indicating whether the argument, expected to be a
number, is greater than, equal to, or less than the value of 
fill-column."

(interactive "p")

(if (or (> a b)(equal a b))
  (setq value a)
(setq value fill-column)
(message "The value of payina is %d" fill-column))

**(if (equal b nil)
  (setq value 56)))**

在第一部分,如果我评估 (test-values 5 4)(test-values 5 5),一切都完美。

但是,当我评估 (test-values 5 ())(test-values 5 nil) 时,出现以下错误:

**Debugger entered--Lisp error: (wrong-type-argument number-or-marker-p nil)
  >(5 nil)
  (or (> a b) (equal a b))
  (if (or (> a b) (equal a b)) (setq value a) (setq value fill-column) 
(message "The value of payina is %d" fill-column))
  test-values(5 nil)
  eval((test-values 5 nil) nil)
  eval-last-sexp-1(nil)
  eval-last-sexp(nil)
  call-interactively(eval-last-sexp nil nil)
  command-execute(eval-last-sexp)**

有人可以帮帮我吗?谢谢。

【问题讨论】:

  • 函数> 需要两个数字参数。它收到的参数之一是nil。您为参数b 传递了nil 值。 (> 5 nil) 不计算。
  • 非常感谢。我会理解可选参数的概念,谢谢。
  • “payina”是什么意思?

标签: emacs elisp optional-parameters optional-arguments optional-values


【解决方案1】:

感谢 Drew 和 Stephen Gildea。

我接受了你的建议和开发,现在我接受代码。

如果这是最后一个代码,我反转流程并嵌套(anide)第二个。

非常感谢。

该代码适用于 EMACS LISP。

来自墨西哥的问候。

(defun test-values (a &optional b)

  "Function with an optional argument that tests wheter its argument, a  
number, is greater than or equal to, or else, less than the value of 
fill-column, and tells you which, in a message. However, if you do not 
pass an argument to the function, use 56 as a default value."

(interactive "p")

(if (equal b nil)
    (setq value 56)
  (if (or (> a b)(equal a b))
      (setq value a)
    (setq value fill-column)
    (message "The value of test is %d" fill-column))))


(test-values 6 3)

(test-values 3 3)

(test-values 3 6)

(test-values 6 nil)

(test-values 6)

现在我可以用 nil 来评估这个函数了。

非常感谢。

【讨论】:

  • “光开发”是什么意思?
【解决方案2】:

未提供的可选参数绑定到nil。在函数体中,您可以在进行算术运算之前显式测试nil。在您的流程中,您可以像这样将b 设置为56

(or b (setq b 56))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多