【问题标题】:Elisp function return valueElisp 函数返回值
【发布时间】:2013-05-09 00:18:59
【问题描述】:

我对 Elisp 有一个(可能)愚蠢的问题。我想要一个函数根据when 条件返回tnil。这是代码:

(defun tmr-active-timer-p
  "Returns t or nil depending of if there's an active timer"
  (progn
    (if (not (file-exists-p tmr-file))
        nil
      ; (... more code)
      )
    )
)

但我有一个错误。我不知道如何让函数返回一个值...我已经读过一个函数返回最后一个表达式结果值,但在这种情况下,我不想做出类似(PHP 混乱警告)之类的事情:

// code

if ($condition) {
  return false;
}

// more code...

也许我没有抓住重点,函数式编程不允许这种方法?

【问题讨论】:

  • 好吧,问题实际上是在 tmr-active-timer-p 之前缺少括号。
  • 您需要接受答案。

标签: function emacs return elisp


【解决方案1】:

首先tmr-active-timer-p后面需要一个参数列表; defun 语法是

(defun function-name (arg1 arg2 ...) code...)

第二progn中不需要包裹body。

第三,返回值是最后评估的形式。如果你的情况,你可以写

(defun tmr-active-timer-p ()
  "Returns t or nil depending of if there's an active timer."
  (when (file-exists-p tmr-file)
      ; (... more code)
    ))

如果文件不存在则返回nil(因为(when foo bar)(if foo (progn bar) nil)相同)。

最后,挂括号被认为是 lisp 中糟糕的代码格式样式。

PS。 Emacs Lisp 没有return,但它有Nonlocal Exits。我敦促您避免使用它们,除非您真的知道自己在做什么。

【讨论】:

  • 嗯,你的回答是正确的。基本上没有返回sintaxis。您不能从 Elisp 中的函数中间轻松返回,并且由于函数范式的原因,这可能不是一个好主意。感谢您提供带括号的建议。
猜你喜欢
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多