2014-03-29 101 views
0

我有這樣的功能。如何從函數返回

(defun foo() 
    (if (condition) 
    (do-something))) 

但我想這樣寫,以避免不必要的縮進。

(defun foo() 
    (if not (condition) (return)) 
    (do-something)) 

很明顯return沒有被捕獲,因爲這裏沒有任何塊。

如何退出該功能? 或者這是一個不好的方式與lisp?

回答

2

Defun創建一個名爲函數名稱的塊,可以通過調用return-from來使用該塊。

(return-from foo (do-something)) 

這不是一個好的風格,用它來避免一點縮進。您的編輯器應該能夠自動進行縮進,並且功能通常更容易閱讀,而無需提前退貨。

+0

我認爲「好風格」不是主要問題。在一個簡短的答案中這太主觀了。也許你的風格的意思是:因爲在這種情況下,該功能會自動無需調用'返回from'明確,這是一個更好的選擇,因爲它會使代碼更簡潔返回。 – EuAndreh

1

@ m-n已經完全回答了您的問題。我只是想提供什麼「好作風」會是這種情況的一個例子:

(defun foo() 
    (when (condition) 
    (do-something))) 

在我看來,它甚至看起來比

(defun foo() 
    (if (condition) 
     (do-something))) 

,特別是比

(defun foo() 
    (if (not (condition)) (return-from foo)) 
    (do-something)) 

(這是縮進我的emacs的煤泥等產生的話)

NB:與其(when (not (condition)) ...)使用(unless (condition) ...)

+0

我可以問,在這種情況下,爲什麼'when'比'if'好? – ironsand

+0

'when'從來沒有else子句,因此使用'when'使得意圖清楚地表明沒有'else'。從表演看,這並不重要。 'when'是一個至少在SBCL上擴展爲'(if(condition)(do-something)nil)'的宏。我不知道標準說的是什麼。 –