常用编程语言对Lambda表达式的支持(二)

2014-11-24 03:13:52 · 作者: · 浏览: 1
da表达式,使得编写事件处理函数更加简洁,lambda表达式更新一个计算表达式,使用“=>”符合来连接事件参数和事件处理代码。如:

button1.Click += (o, e) => { System.Windows.Forms.MessageBox.Show("Click!"); };

在C#中,事件处理函数其实就是委托。委托除了可以作为事件处理函数,还可以作为函数指针,或回调函数使用,都可以使用lambda表达式的写法。如:

delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25

或者:

Func myFunc = x => x == 5;
bool result = myFunc(4); // returns false of cour

另外Lambda表达式在LINQ中发挥了重要作用。

PHP 5.3

PHP5.3增加了Lambda的支持,对于接受回调函数的PHP函数来说,lambda表达式非常方便。比如使用array_map函数遍历数组,并将回调结果重新赋值给数字各元素。在早期PHP版本中,我们在调用array_map之前,必须事先定义好回调函数,比如:

function quoteWords()
{
     if (!function_exists ('quoteWordsHelper')) {
         function quoteWordsHelper($string) {
             return preg_replace('/(\w)/','"$1"',$string);
         }
      }
      return array_map('quoteWordsHelper', $text);
}

现在PHP5.3对lambda表达式的支持,使得编码根据简单。如下使用lambda表达式的实现:

function quoteWords()
{
     return array_map('quoteWordsHelper',
            function ($string) {
                return preg_replace('/(\w)/','"$1"',$string);
            });
}

Python

Python世界的lambda表达式根据简单,只是在python世界里,lambda表达式主要适用比较小的函数。如普通Python的函数定义:

def func(x):
    return x * 2
func(2) # 4

使用lambda表达式的写法:

func = lambda x:x*2
func(2) # 4

python的lambda表达式常用在一些回调中,比如:

a = [1, 2, 3, 4]
map(lambda x:x**2, a) # output: [1, 4, 9, 16]

或者

a = [1,2,3,4,5,6,7,8,9]
low, high = 3, 7
filter(lambda x:high>x>low, a) # output: [4,5,6]

"x**2"表示x的平方。"high>x>low"等于“high>x and x > low”。

java script

java script中的lambda表达式通常称为匿名函数,如果你使用过jquery库,那么你肯定知道匿名函数,这里主要作为回调函数使用。比如:

$('#submit').on('click', function(){ functionbody. })

其中方法on的第二个参数就是匿名函数,java script中的你们函数还有其他存在形式,比如:

var func = new Function('x', 'return 2*x;');

或者

var func = function(x) { return 2*x; }

还有就是很多js库常用的方式,表示创建匿名函数,并调用之:

(function(x, y) {
    alert(x+y);
})(2, 3);

总结

lambda表达式的出现简化了编码量,多用于函数回调、事件、匿名函数,并且与闭包的结合使用,更能发挥强大的作用。另外,支持lambda表达式的编程语言有很多,这里主要介绍了我相对熟悉的几种。

参考

http://datumedge.blogspot.co.uk/2012/06/java-8-lambdas.htmlhttp://www.softwarequalityconnection.com/2011/06/the-biggest-changes-in-c11-and-why-you-should-care/http://www.cnblogs.com/hujian/archive/2012/02/14/2350306.htmlhttp://msdn.microsoft.com/zh-cn/LIBRARY/bb397687(v=vs.90). aspxhttp://php.net/manual/zh/migration53.new-features.phphttp://my.oschina.net/u/574366/blog/146422http://www.xs-labs.com/en/archives/articles/objc-blocks/ 版权所有,转载请注明出处:http://guangboo.org/2014/01/16/lambda-supported-programming-language