闭包(在Haskell中) [英] Closures (in Haskell)

查看:418
本文介绍了闭包(在Haskell中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我来说,Closure是一个(嵌套的)函数,具有共同位置的数据。

To me a Closure is a (nested?) function with co-located data.

当您在Haskell编写软件并在之后查看它时,您经常会发现您无意中创建的闭包。

When you write software in Haskell and look it through afterwards, you frequently find closures that you have created unintentionally.

我不太适合自己。在什么情况下我会故意想要关闭代码?毕竟,在所有的例子中,我发现共同位置的数据量是微不足道/小,因此它似乎在我看来不像在实践中,将证明他们(有意)的创作。有没有任何Haskell模块,将支持我有意创建闭包,将它们存储在映射中?

I do not quite get this right for myself. In what situations would I intentionally want to code closures? After all, in all examples I find the amount of co-located data is trivial/small and thus it does not quite seem to me as if in practice that would ever justify their (intentional) creation. Is there any Haskell module that would support me in intentionally creating closures and e.g. storing them in a map?

推荐答案

在Haskell中,函数是语言的一个重要部分,主要是因为Haskell基于 Lambda微积分

In Haskell, functions are an essential part of the language, largely because Haskell is based on the Lambda Calculus.

在Lambda微积分中,有函数有自由变量,意味着他们使用的变量没有作为直接参数传递给他们。具有自由变量的函数在这种情况下称为闭包。

In the Lambda Calculus, there are functions that have "free variables", meaning that they use variables that were not passed as direct parameters to them. Functions with free variables are what you would call "closures" in this case.

由于自由变量的函数在LC中如此常见,它们也构成了Haskell语言。例如,当您写下:

Because functions with free variables are so common in LC, they also form an integral part of the Haskell language. For example, when you write this:

f a b c = a * b + c

...您也可以写这个,结果完全相同:

... you could also be writing this, with the exact same result:

f a b = \ c -> a * b + c

...或甚至:

f a b = let product = a * b in \ c -> product + c

...进一步的等效变更:

... further equivalent changes:

f a = \ b -> let product = a * b in \ c -> product + c

这是因为Haskell本质上创建了自由变量 ,因此,始终创建闭包。其中一些可能由编译器优化,但是可以安全地假设将使用比您自己可能发现的更多的闭包。

This is because Haskell essentially creates functions with free variables everywhere, and thus, closures are created all the time. Some of these might be optimized away by the compiler, but it is safe to assume that there will be more closures used than you might ever be able to discover on your own.

所以,不要尝试找到闭包;他们在Haskell没有什么特别的,并一直使用。

So, don't try to locate closures; they are nothing special in Haskell and are used all the time.

这篇关于闭包(在Haskell中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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