这是封闭吗?

fe2*_*e2s 4 lisp closures

有些人声称下面的代码是Lisp中闭包的一个例子.我不熟悉Lisp,但相信他错了.我没有看到任何自由变量,在我看来它是普通高级函数的一个例子.你能否判断......

 (defun func (callback)
   callback()
)

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

func(f1)
func(f2)
Run Code Online (Sandbox Code Playgroud)

Cal*_*ngh 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 ")
Run Code Online (Sandbox Code Playgroud)

输出:

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."
> 
Run Code Online (Sandbox Code Playgroud)

f定义并返回,其中,第一和最后一个字的封闭封闭,并且其然后通过调用重用新创建的功能f1f2.


这篇文章有几百个视图,因此如果非计划者正在阅读这个,这里是python中同样愚蠢的例子:

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.'
Run Code Online (Sandbox Code Playgroud)