什么是 lambda 以及什么是示例实现?

发布于 2024-07-10 02:04:24 字数 296 浏览 2 评论 0原文

我对编程相当陌生,虽然读了很多书,但 lambda 的概念不断出现,但我很难弄清楚它到底是什么,以及实现它如何让我的编程生活变得更好。 首先,什么是 lambda;其次,它是如何实现的?

感谢所有发帖的人。 正如评论中所提到的,这是重复的,但这里有很多很棒的答案,我想为社区保留它们,所以我将其变成社区帖子。 这是另一个问题的链接:

什么是 lambda(函数)?

I am fairly new to programming and while doing a lot of reading this concept of a lambda keeps coming up but I'm having a hard time putting my finger on what it actually is and how implementing it will make my programming life so much better. So first, what is a lambda and second how might it be implemented?

Thanks to all who posted. As has been mentioned in the comments, this is a duplicate, but there are so many great answers here I want to preserve them for the community so I'm turning it into a community post. Here is the link to the other question:

What is a lambda (function)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

一紙繁鸢 2024-07-17 02:04:24

Lambda 很难捕捉到,但是一旦你想象了它们,你就无法理解为什么你以前没有捕捉到它。

Lamdba 是匿名函数

Lambda 是普通函数,唯一的区别是你没有给它们命名。

要理解这一点,你必须首先知道,当你创建函数时,代码存储在内存中的地址只有计算机知道。

因此,当您执行类似操作时:

function Foo ()
{
 /* your code here */
}

您真正要做的是将名称“Foo”绑定到内存中代码的地址。

现在,还有另一种访问地址的方法:引用(和指针,但让我们跳过这个讨厌的家伙)

好吧,lambda 函数是一个没有名称的函数,因此只能访问及其参考。

你如何使用它们?

当您创建 lambda 函数时,您通常计划只使用它一次。

逐步过程通常是:

  1. 创建函数
  2. 获取引用
  3. 将引用传递到将要使用的地方

最后,引用是丢失,则该功能自动销毁。

典型的用例是回调函数。 您可以在一行中声明、创建和传递该函数,因此非常方便。

来自真实单词的示例

在 Python 中,您可以在列表推导式中使用 lambda :

/* create a list of functions */
function_list = [(lambda x : number_to_add + x) for number_to_add in range(0, 10) ]

在 Javascript 中,您通常将一个函数传递给其他函数。 以 JQuery 为例:

 $("img").each(

 /* here we pass a function without any name to the "each()" method   */

 function(i){  his.src = "test"   i   ".jpg"; }

 );

您最好了解的事情

  • 某些语言,如 Javascript 或 Lisp,大量使用
    拉姆达。 这可能是出于文化原因,但函数式编程范式往往会导致 lambda 狂热。

  • 长 lambda 表达式使代码难以阅读。 这就是为什么有些语言限制 lambda 的可能性,例如 Python 不允许在其中使用“if”语句。

  • Lambda 只是普通函数。 无论您在哪里使用它,都可以使用普通函数来代替。 这只是编码风格的问题。

Lambda are hard to catch, but once you have pictured them, you cannot understand why you didn't get it before.

Lamdba are anonymous functions

Lambda are ordinary functions, the only difference is that you don't give them a name.

To understand that, you must know first that when you create a function, the code is stored in memory at an address only knowned by the computer.

So when you do something like that :

function Foo ()
{
 /* your code here */
}

What you really do is binding the name "Foo" to the adress of the code in memory.

Now, there is an other way to access an address : references (and pointers, but let's skip this nasty guys)

Well, a lambda function is a function that have no name, so it can be only access with its reference.

How do you use them ?

When you create a lambda function, you usually plan to use it only once.

The step by step process is usually :

  1. Create the function
  2. Get the reference
  3. Pass the reference somewhere it will be used

Finally, the reference is lost, and so the function is destroyed automatically.

The typical use case is a callback function. You declare, create and pass the function in one row, so it's handy.

Example from the real word

In Python, you can use lambda in list comprehensions :

/* create a list of functions */
function_list = [(lambda x : number_to_add + x) for number_to_add in range(0, 10) ]

In Javascript, you usually pass a function to others functions. Example with JQuery :

 $("img").each(

 /* here we pass a function without any name to the "each()" method   */

 function(i){  his.src = "test"   i   ".jpg"; }

 );

The things you'd better know

  • Some languages, like Javascript or Lisp, make a massive use of
    lambdas. It can be for cultural reason, but the functional programming paradigm tends to lead to lambda-mania.

  • Long lambdas make the code hard to read. That's why some languages restrain the possibilities of lambdas, such as Python that does not allow "if" statement in them.

  • Lambdas are just normal functions. Where ever you use one, you can use an ordinary function instead. It's just a matter of coding style.

哎呦我呸! 2024-07-17 02:04:24

lambda 是函数的内联描述。 它起源于函数式编程语言,如今支持类似功能的其他语言的数量正在不断增长。 这个名字来源于一种叫做 Lambda 演算的数学事物,它影响了函数式编程语言(例如 Lisp),而 lambda 的想法也来自于此。

您的问题取决于您所讨论的编程语言。 例如,在 F# 中,您可以使用 fun x -> x * x 来表示

int myfunction(int x) { return x * x; }

在 C# 中,您可以使用 x =>; x * x 来表示相同的函数。
它的使用方式以及您可以用它做什么很大程度上取决于您所使用的语言。

谈到 C#,它们的伟大之处在于能够将它们解析为表达式树。 lambda 表达式可以用作代码,如表达式树中的委托(大致是函数指针)或数据。 使用它们作为表达式树,使 LINQ to SQL 等库能够使用表达式创建 SQL 语句,以便提交到服务器并获得适当的结果。

A lambda is an inline description of a function. It has originated from functional programming languages and the number of other languages that support something like it is growing these days. The name comes from a mathematical thing called Lambda calculus which has influenced functional programming languages (such as Lisp) and the idea of lambdas come from it.

Your question depends on the programming language you're talking about. For instance, in F#, you would use fun x -> x * x to represent

int myfunction(int x) { return x * x; }

In C#, you would use x => x * x to represent the same function.
How it's used and what you can do with it pretty much depends on the language you are working in.

Talking about C#, the great thing about them is the ability to parse them as expression trees. A lambda expression can be used as a code, like a delegate (roughly a function pointer) or as data, in an expression tree. Using them as expression trees, make libraries such as LINQ to SQL to be able to use the expression to create a SQL statement in order to submit to server and get the appropriate results.

寄风 2024-07-17 02:04:24

Lambda 是一种创建匿名函数或闭包的方法。 在命令式语言(和函数式语言)中,它相当于允许嵌套函数,其中内部函数可以访问封闭函数的局部变量和参数。 它可以在函数式语言中的关键字 lambdafunfn 甚至 \ 下找到; 在 Smalltalk 中,它被称为。 它也存在于大多数脚本语言中,例如 Perl、Python、Lua 等。

没有 lambda 的唯一语言是

  • 没有嵌套函数的语言,例如标准 C 或 Icon

  • 具有第二类嵌套函数的语言 --- 函数可能无法从函数返回、存储在全局变量中或存储在堆分配的数据结构中。 该语言家族包括 Pascal 及其在 Modula、Ada 和 CLU 家族中的后代。

Lambda 对程序员和编译器编写者具有重要意义:不再可能将所有局部变量存储在堆栈上。 相反,一些变量可能会被捕获并存储在堆分配的闭包中。 请注意,当您编写 lambda 时,您正在编写分配

示例:最简单的函数之一是组合(Haskell 语法):

compose f g = \x -> f (g x)

这表示 compose 将两个函数 fg 作为参数,并且它返回一个匿名函数,该函数接受其参数 x,然后将 gf 应用于 xcompose 的应用程序创建一个在堆上分配的闭包,它存储 fg 的值以及指向 lambda 主体代码的指针。 在 lambda 很常见的语言中,例如 Haskell、ML、Caml 和Scheme,已经花费了大量的精力使分配速度快得令人眼花缭乱。 某些脚本语言(例如 Lua)具有不寻常的实现,这使得非 lambda 情况与命令式语言中的情况相同,同时也使 lambda 相当快。 Smalltalk 中的 Lambda 也很快,它也设计用于在堆上分配大量对象。 在对 lambda 进行改造的语言中,例如 Perl 或 Java(内部类与 lambda 相关),费用可能相对要高得多。

一般来说,如果一种语言在设计时就考虑到了 lambda,那么您可以随心所欲地使用它们。 特别是在 ML、Caml、Scheme、Haskell 中,甚至匿名函数也非常便宜——大量使用它们!

Lambda is a means of creating an anonymous function or closure. In imperative languages (and functional ones) it is equivalent to allowing nested functions where the inner function has access to local variable and parameters of the enclosing function. It is found in functional languages under the keywords lambda, fun, fn or even \; in Smalltalk it is called a block. It is also found in most scripting languages, e.g., Perl, Python, Lua, etc.

About the only languages without lambda are

  • Languages without nested functions, like Standard C or Icon

  • Languages with second-class nested functions---a function may not be returned from a function, stored in a global variable, or stored in a heap-allocated data structure. This language family includes Pascal and its descendants in the Modula, Ada, and CLU families.

Lambda has important implications for programmers and compiler writers: it is no longer possible to store all local variables on a stack. Instead some variables may be captured and stored in a heap-allocated closure. Be aware that when you write lambda you are writing an allocation.

Example: one of the simplest functions is composition (Haskell syntax):

compose f g = \x -> f (g x)

This says that compose takes two functions f and g as arguments, and it returns an anonymous function which takes its argument x and then applies g and then f to x. An application of compose creates a closure allocated on the heap which stores the value of f and g as well as a pointer to code for the body of the lambda. In languages where lambda is common, such as Haskell, ML, Caml, and Scheme, a great deal of effort has been expended making allocation blindingly fast. Some scripting languages, such as Lua, have unusual implementations which make the non-lambda case the same as in an imperative language, while also making lambda reasonably fast. Lambda is also fast in Smalltalk, which was also designed to allocated lots of objects on the heap. In languages where lambda was retrofitted, like Perl or Java (inner classes are related to lambda), the expense can be relatively much higher.

In general, if a language was designed with lambdas in mind, you can use them as much as you like. Especially in ML, Caml, Scheme, Haskell, even anonymous functions are dirt cheap---use lots of them!

落墨 2024-07-17 02:04:24

Lambda 是 lambda 演算,但我认为人们将它与术语 闭包可互换。 请参阅什么是闭包?

Ruby 的实现易于理解且非常强大。 在下面的代码中,times 方法接受大括号之间的代码块,并将其回调 HEIGHT 次。 您可以定义类似的方法来接受代码块并实现循环构造式的东西。

@cells = []
HEIGHT.times { @cells << empty_row }

我想如果有一个参数会更有趣。

5.times { |i| puts i, " " }

Lambda is lambda calculus, but I think people use it with the term closure interchangeably. See What is a Closure?

Ruby's implementation is easy to understand and very powerful. In the following code times method accepts a block of code between the curly braces and calls it back HEIGHT times. You can define similar method that accepts a block of code and implement looping construct-ish things.

@cells = []
HEIGHT.times { @cells << empty_row }

I guess it's more interesting if there's a parameter.

5.times { |i| puts i, " " }
梦年海沫深 2024-07-17 02:04:24

Lambda 对于不同的语言意味着不同的东西。 我在 python 的背景下了解它们,但我听说 python 有与其他语言不同的方法。

本质上,在 python 中,lambda 是一个匿名函数,只能包含单个表达式,并返回其结果。

我知道在其他语言中,它们是更通用的匿名函数,没有单一表达式的限制,但我不确定细节。

匿名函数,顾名思义。 没有名称的函数。 例如,它们经常用作事件处理程序,或者您需要简单的回调函数但又不想弄乱命名空间的任何情况。

Lambda means different things to different languages. I know about them in the context of python, but I've heard that python has a different approach than other languages.

Essentially, in python, a lambda is an anonymous function that can only consist of a single expression, the result of which is returned.

I understand that in other languages, they are more generalized anonymous functions, without the single expression limitation, but I'm not certain about the details.

An anonymous function, is just what it sounds like. A function without a name. For example, they are frequently used as event handlers, or any case in which you need a simple callback function, but don't want to clutter up the namespace.

错爱 2024-07-17 02:04:24

lambda 在编程世界中意味着可以像其他普通变量一样传递和返回的匿名函数。 所谓的函数式语言内置了它们,但最近有越来越多的语言支持它们,因为它们允许编写可重用的代码。 例如,请参阅用 C++ 的下一版本编写的示例:

// write this once...
int transform_values(int * values, int n, function<int(int)> f) {
    for(int i = 0; i < n; i++)
        values[i] = f(values[i]);
}

int values[] = { 1, 2, 3, 4 };
// ... then call it to double the values in an array
transform_values(values, 4, [](int v) { return v * 2; });

它在 C# 和其他支持 lambda 的语言中看起来确实相似。 现在有一个“闭”字。 这意味着 lambda 可以捕获局部变量并在其结果的计算中使用它们:

int local_variable = 5;
int values[] = { 1, 2, 3, 4 };
// ... then call it to multiply the values in an array
transform_values(values, 4, [=](int v) { return v * local_variable; });

变量local_variable现在在闭包内捕获并可以在其中使用。 变量也可以通过闭包更新。 Lambda 是函数式语言的基本构建块。 这是 haskell 中的一个示例:

map (\x -> x * 2) [1, 2, 3, 4]

将执行与上面的 C++ 代码相同的操作。 它使用给定函数(此处为 lambda)将列表中的值映射到结果列表中。 使用 haskell,您可以清楚地看到所使用的语法如何映射到 Lambda 演算 的数学概念。

lambda in the programming world means an anonymous function that can be passed and returned like every other normal variable. So-called functional languages have them builtin but recently there is a growing set of languages supporting them, since they allow writing reusable code. See this for example, written in the next version of C++:

// write this once...
int transform_values(int * values, int n, function<int(int)> f) {
    for(int i = 0; i < n; i++)
        values[i] = f(values[i]);
}

int values[] = { 1, 2, 3, 4 };
// ... then call it to double the values in an array
transform_values(values, 4, [](int v) { return v * 2; });

It does look similar in C# and other languages supporting lambdas. Now there is the word "closure". It means that a lambda can capture local variables and use them in the computation of its result:

int local_variable = 5;
int values[] = { 1, 2, 3, 4 };
// ... then call it to multiply the values in an array
transform_values(values, 4, [=](int v) { return v * local_variable; });

The variable local_variable is now captured inside the closure and can be used within it. Variables may also be updated by a closure. Lambdas are a basic building block of functional languages. Here is an example in haskell:

map (\x -> x * 2) [1, 2, 3, 4]

Will do the same as the C++ code above. It maps the values in the list using the given function (a lambda here) into a result list. Using haskell, you can see nicely how the syntax used maps to the mathematical notion of Lambda Calculus.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文