11

这是一个简单的问题,但不知何故我无法通过谷歌搜索找到答案:

如果不满足某些条件,如何在任意执行点退出函数。例如(我在这里使用“(退出)”作为替代):

(defun foo ()
  (progn (if (/= a1 a2)
             (exit) ; if a1!=a2, exit the function somehow
           t)
         (blahblah...)))
4

4 回答 4

13

在 elisp 中,您可以使用catchandthrow 代替 cl 的blockandreturn-from

(defun foo ()
  (catch 'my-tag
    (when (not (/= a1 a2))
      (throw 'my-tag "non-local exit value"))
    "normal exit value"))

C-hig (elisp) Nonlocal Exits RET

于 2013-04-27T06:30:49.420 回答
10

在身体周围放一个块并从中返回:

(require 'cl-macs)
(defun foo ()
  (block foo
    (if (/= a1 a2)
        (return-from foo)
        reture-value))))
于 2013-04-27T05:44:52.450 回答
9

只需使用defun*而不是defun(随附cl包装)。这个宏已经像 Common Lisp 的一样defun(将函数的主体包装在一个 try-catch 块中,并return-from为其命名throw等)。

例如:

(require 'cl)

(defun* get-out-early ()
  "Get out early from this silly example."
  (when (not (boundp some-unbound-symbol))
    (return-from get-out-early))
  ;;
  ;; Get on with the func...
  ;;
  (do-such-and-such with-some-stuff))
于 2013-04-27T07:56:13.123 回答
3

函数返回最后评估的表单的值。如果您不在乎价值是什么,那么nil可能是候选人。在这种情况下,函数返回函数的值if

例如:

(defun foo ()
  (if (/= a1 a2)
      nil
    "return-value"))

在这个简单的例子中,这些也是等价的:

(defun foo ()
  (if (not (/= a1 a2))
      "return-value"))

(defun foo ()
  (when (not (/= a1 a2))
    "return-value"))
于 2013-04-27T05:54:41.047 回答