search
HomeBackend DevelopmentPython Tutorial闭包(计算机科学)是什么?

在The Swift programming langauge看到closures,但是不太理解是什么,有什么样的特性,能做什么Objective-C做不到的?编程初学者,求指教

回复内容:

要说 Closure 就得说 Closed Lambda Expression,一个 Closed Lambda Expression 就是没有自由变量的 Lambda Expression,如 λx. x,而 λx. yx 就不是 Closed。Closed Lambda Expression 最好的性质之一就是它的类型必然同构于某个逻辑重言式,如 λx. λy. xy 的类型就是「肯定前件」(αβ) → αβ
那么如何把某个 Open Lambda Expression 给 Enclose 住呢?答案就是把它引用的所有自由变量给保存到什么东西里面,这种保存了自由变量的 Lambda Expression 就是 Closure。在其同构的逻辑一面,则是在相继式左边加入前提。

语法上东西我就不说了。


计算机程序可以粗略的分成,代码+数据。初学者很容易就会将这两者对立起来,会认为代码就是代码,数据就是数据,两者是完全不同的。但实际上,两者可以统一起来的。将代码跟数据统一起来,是学习计算机编程的一道门槛。


可以参考,我以前的回答。回调函数是什么?


将数据保存起来,以后再使用,会觉得很自然。但将代码保持起来,以后再使用,很多人会觉得很别扭,难以理解。都是因为还没有过那道槛。


代码指令执行时候,会处于一定的环境,单纯将代码保存下来,还是不够的,需要将代码所处的环境也保存下来。闭包其实是,将代码跟代码所处于的环境做为一个整体来看待。周围的环境,表现为代码所使用的数据。在有些语言中,这个概念叫代码块(block),匿名函数(lambda)等等。


数据跟代码不再人为割裂开来,统一起来看待。闭包就会是很自然的概念。数据可以传递,从一个地方传递到另一个地方,并且以后再使用。闭包从某个角度来说,也是数据,当然也可以传递,从一个函数传递到另一个函数,也可以保持下来,以后再调用。因为将环境也保持下来了,以后调用的时候,就还原当时的情况,延迟执行,就很容易,很自然地实现了。而延迟执行有什么作用?就是另一个话题了。

function makeCounter()
      local count = 0
      return function()
           count = count + 1
           return count
end
闭包就是一个函数,或者一个指向函数的指针,加上这个函数执行的非局部变量。
说的通俗一点,就是闭包允许一个函数访问声明该函数运行上下文中的变量,甚至可以访问不同运行上文中的变量。
我们用脚本语言来看一下:
<span class="kd">function</span> <span class="nx">funA</span><span class="p">(</span><span class="nx">callback</span><span class="p">){</span>
    <span class="nx">alert</span><span class="p">(</span><span class="nx">callback</span><span class="p">());</span>
<span class="p">}</span>

<span class="kd">function</span> <span class="nx">funB</span><span class="p">(){</span>
    <span class="kd">var</span> <span class="nx">str</span> <span class="o">=</span> <span class="s2">"Hello World"</span><span class="p">;</span> <span class="c1">// 函数funB的局部变量,函数funA的非局部变量</span>
    <span class="nx">funA</span><span class="err">(</span>
        <span class="kd">function</span><span class="err">()</span><span class="p">{</span>
            <span class="k">return</span> <span class="nx">str</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="err">);</span>
<span class="p">}</span>
Javascript闭包——懂不懂由你,反正我是懂了
这个比较容易懂 至少JavaScript闭包是指有权访问另一个函数作用域中的变量的函数,其他语言的不知道(逃 可以和对象的概念对比起来理解,简单地说:
对象是带方法的数据,而闭包是带数据的方法
后半句的数据特指外部数据 一块内存区域,存放着可执行代码和一些变量,指针 学过离散没?在某些集合上某些运算的结果始终在这个集合里,这就叫闭包性质…………虽然和这个闭包一点关系都没有=_=。
闭包在函数式语言当中是一个非常有力的工具,但是有点只可意会的感觉。
简单的来说你可以把闭包看成是绑定了某些变量的值的函数,由于函数式语言中函数是一级对象,所以,这样的性质就非常有用了,比如说可以通过在函数里面返回一些闭包来定义一些数据结构什么的。
举个栗子:
这是我学common lisp 的时候写的一个栈
<span class="p">(</span><span class="nb">defun</span> <span class="nv">stackpush</span> <span class="p">(</span><span class="nv">stack</span> <span class="nv">x</span><span class="p">)</span>
        <span class="p">(</span><span class="nb">cons</span> <span class="nf">#'</span><span class="p">(</span><span class="k">lambda</span> <span class="p">()</span> <span class="nv">x</span><span class="p">)</span>
              <span class="nf">#'</span><span class="p">(</span><span class="k">lambda</span> <span class="p">()</span> <span class="nv">stack</span><span class="p">)))</span>
<span class="p">(</span><span class="nb">defun</span> <span class="nv">stackpop</span> <span class="p">(</span><span class="nv">stack</span><span class="err">)</span>
        <span class="p">(</span><span class="nb">apply</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">stack</span><span class="p">)</span><span class="no">nil</span><span class="p">))</span>
<span class="p">(</span><span class="nb">defun</span> <span class="nv">stacktop</span> <span class="p">(</span><span class="nv">stack</span><span class="p">)</span>
        <span class="p">(</span><span class="nb">apply</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">stack</span><span class="p">)</span> <span class="no">nil</span><span class="p">))</span>
穷人的类
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools