lisp - 这是闭包吗?

标签 lisp closures

有些人断言以下代码是 Lisp 中闭包的示例。我不熟悉 Lisp,但相信他是错的。我没有看到任何自由变量,在我看来这是普通高级函数的一个例子。能否请您判断...

 (defun func (callback)
   callback()
)

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

func(f1)
func(f2)

最佳答案

没有。

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


这篇文章有数百个浏览量,因此如果非策划人员正在阅读这篇文章,这里是 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.'

关于lisp - 这是闭包吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5528779/

相关文章:

scheme - 在方案中反转数字时参数数量错误

swift - Swift 中的宏闭包

javascript - 在循环中使用 javascript 闭包作为上下文

Emacs:键绑定(bind)到匿名函数的性能

lisp - 错误 : null character for <input concatenated stream>

emacs - 如何用 "one less"C-u调用原始函数?

ruby - 如何使 block 局部变量成为 ruby​​ 1.9 中的默认值?

rust - 在 Rust 闭包中重用绑定(bind)

有委托(delegate)的 Swift 闭包

lisp - 如何写一个clisp可执行文件?