2011-04-03 52 views
4

有些人聲稱以下代碼片段是Lisp中閉包的一個例子。我對Lisp不熟悉,但相信他錯了。我沒有看到任何自由變量,在我看來,它是普通高級函數的一個例子。能否請您判斷...這是封口嗎?

(defun func (callback) 
    callback() 
) 

(defun f1() 1) 
(defun f1() 2) 

func(f1) 
func(f2) 
+2

應該是'(funcall callback)'和'(func'f1)'和'(func'f2)'? – Ken 2011-04-03 16:52:13

+2

'(func#'f1)',當然是 – dsm 2011-04-04 08:24:39

+0

它是更高層次的功能:)我曾經犯過同樣的錯誤,所以我想分享 – nourdine 2012-12-09 13:36:21

回答

17

沒有內部func會附上內func局部變量被定義功能。 這裏是基於你 一個人爲的例子下面是一個很好的例子:

輸入:

(define f 
    (lambda (first-word last-word) 
    (lambda (middle-word) 
     (string-append first-word middle-word last-word)))) 

(define f1 (f "The" "cat.")) 
(define f2 (f "My" "adventure.")) 

(f1 " black ") 
(f1 " sneaky ") 

(f2 " dangerous ") 
(f2 " dreadful ") 

輸出:

Welcome to DrScheme, version 4.1.3 [3m]. 
Language: Pretty Big; memory limit: 128 megabytes. 
"The black cat." 
"The sneaky cat." 
"My dangerous adventure." 
"My dreadful adventure." 
> 

f定義並返回一個封蓋,其第一個和最後文字是,內附,然後通過調用新創建的函數f1f2


這個帖子有幾百意見,因此,如果非陰謀家正在讀這篇文章,這裏是蟒蛇一樣傻例如:

def f(first_word, last_word): 
    """ Function f() returns another function! """ 
    def inner(middle_word): 
     """ Function inner() is the one that really gets called 
     later in our examples that produce output text. Function f() 
     "loads" variables into function inner(). Function inner() 
     is called a closure because it encloses over variables 
     defined outside of the scope in which inner() was defined. """ 
     return ' '.join([first_word, middle_word, last_word]) 
    return inner 

f1 = f('The', 'cat.') 
f2 = f('My', 'adventure.') 

f1('black') 
Output: 'The black cat.' 

f1('sneaky') 
Output: 'The sneaky cat.' 

f2('dangerous') 
Output: 'My dangerous adventure.' 

f2('dreadful') 
Output: 'My dreadful adventure.' 
0

這是我作爲一個JavaScript程序員貢獻:

閉包是一個可以訪問在其詞法範圍中定義的變量(當實際調用閉包時可能不再存在的範圍)的函數。在這裏:

function funktionFactory(context) { 
    // this is the lexical scope of the following anonymous function 
    return function() { 
     // do things with context 
    } 
} 

一旦funktionFactory返回詞彙範圍,就永遠走了,但(這是一個很大的「而是」)如果返回的功能仍然被引用(因此不收集的垃圾),那麼這樣的函數(閉包)仍然可以使用原始變量context。在這裏:

var closure = funktionFactory({ 
    name: "foo" 
}); 

沒有人,但closure可以訪問上下文對象的name財產(不可達在軟件的任何其他實體時funktionFactory返回)。

那麼要回答你的問題:是func一閉?不。而callback?都不是!