Haskell-Lambda表达式 [英] Haskell - lambda expression

查看:216
本文介绍了Haskell-Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解什么有用,以及如何在Haskell中实际使用lambda表达式. 我真的不明白使用lambda表达式比定义函数的常规方法的优势. 例如,我通常执行以下操作:

I am trying to understand what's useful and how to actually use lambda expression in Haskell. I don't really understand the advantage of using lambda expression over the convention way of defining functions. For example, I usually do the following:

let add x y = x+y

我可以简单地致电

add 5 6

得到11的结果 我知道我也可以执行以下操作:

and get the result of 11 I know I can also do the following:

let add = \x->(\y-> x+y)

并获得相同的结果. 但是,就像我之前提到的那样,我不理解使用lambda表达式的目的. 另外,我在前奏中键入了以下代码(一个无名函数?),它给了我一条错误消息.

and get the same result. But like I mentioned before, I don't understand the purpose of using lambda expression. Also, I typed the following code (a nameless function?) into the prelude and it gave me an error message.

let \x -> (\y->x+y)

parse error (possibly incorrect indentation or mismatched backets)

提前谢谢!

推荐答案

许多Haskell函数是高阶函数",即它们希望其他函数作为参数.通常,我们想要传递给这种高阶函数的函数在该特定点仅在程序中使用一次.与使用lambda表达式相比,为此目的定义一个新的本地函数要简单得多.

Many Haskell functions are "higher-order functions", i.e., they expect other functions as parameters. Often, the functions we want to pass to such a higher-order function are used only once in the program, at that particular point. It's simply more convenient then to use a lambda expression than to define a new local function for that purpose.

下面是一个示例,该示例从给定列表中过滤所有大于十的偶数:

Here's an example that filters all even numbers that are greater than ten from a given list:

ghci> filter (\ x -> even x && x > 10) [1..20]
[12,14,16,18,20]

这是另一个遍历列表的示例,对于每个元素,x计算项x^2 + x:

Here's another example that traverses a list and for every element x computes the term x^2 + x:

ghci> map (\ x -> x^2 + x) [1..10]
[2,6,12,20,30,42,56,72,90,110]

这篇关于Haskell-Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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