8

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

(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...

也许我错过了重点并且函数式编程不允许这种方法?

4

1 回答 1

16

首先,你需要一个参数列表tmr-active-timer-pdefun语法是

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

其次,你不需要把身体包裹进去progn

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

(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。我敦促您避免使用它们,除非您真的知道自己在做什么。

于 2013-05-14T16:47:06.477 回答