关闭,因为它可以做什么或因为它做 [英] Closure Because of What it Can Do or Because it Does

查看:100
本文介绍了关闭,因为它可以做什么或因为它做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是一个有点问题,但我想确保我正确理解的定义。闭包标记用于描述可以 在本地作用域中提升变量的匿名函数(无论它们是否实际执行),或者只有在 / strong>来提升其局部范围内的变量(因为语言提供了这种能力),但是不会,它仍然被认为是一个闭包?



是一个闭包,只有当局部变量被提升。但是一个匿名函数不会(即使它可以)不是一个闭包。所以不是所有的匿名函数都是闭包,但所有闭包都是匿名函数。



再次,对不起,这些东西啃我。 :)

解决方案

假设你是在计算机科学的上下文中...

闭包是一个第一类函数,它捕获自由变量在其定义环境中的词法绑定。一旦它捕获了词法绑定,函数就成为一个闭包,因为它关闭这些变量。



注意这意味着闭包只存在于运行时。 / em>



对于要作为闭包的函数与匿名或命名的函数正交。



这里是一个Python命名的闭包:

  def maker():
count = [0]
def counter():
count [0] ] +1
return count [0]
return counter


Ok, this is a bit of a pedantic question but I'd like to make sure I'm understanding the definition correctly. Is the closure moniker used to describe anonymous functions that can lift variables in the local scope (Whether they actually do or not) or only when they do lift variables in local scope?

In other words if an anonymous function has the ability to lift variables in its local scope (Because the language offers that capability) but doesn't, is it still considered a closure?

My understanding is that it is a closure only when local variables are lifted. But an anonymous function that doesn't (Even though it can) is not a closure. So not all anonymous functions are closures but all closures are anonymous functions.

Again, sorry for the pedantry, but these things gnaw at me. :)

解决方案

Assuming you mean within the context of computer science...

A closure is a first class function which captures the lexical bindings of free variables in its defining environment. Once it has captured the lexical bindings the function becomes a closure because it "closes over" those variables.

Note this means closures only exist at run time.

For a function to be a closure is orthogonal to the function being anonymous or named. You can create a language that allows you to define named functions to be closures.

Here is a "named" closure in Python:

def maker():
  count=[0]
  def counter():
    count[0]=count[0]+1
    return count[0]
  return counter

这篇关于关闭,因为它可以做什么或因为它做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆