2011-04-03 50 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?都不是!