编程技巧:将lambda用作局部函数预备知识:变量及函数的作用域应该做到最小化根据这一原则,如果某个函数A只
编程技巧:将lambda用作局部函数
预备知识:变量及函数的作用域应该做到最小化
根据这一原则,如果某个函数A只在另一个函数B内调用的话,A函数应该在B函数内定义并使用,即把A函数定义成B函数内部的局部函数。
注:这里的函数是泛指,OOP语言中类的方法以及FP语言中的lambda都可视作函数。
以下用C#代码示例
using System;namespace ConsoleApplication1{ class Program { static int f(int a) { g(a, "a"); g(a, "b"); return a; } static void g(int a, string b) { Console.WriteLine("a={0},b=\"{1}\"", a, b); } static void Main(string[] args) { int n = f(1) + f(2); Console.WriteLine("n={0}", n); } }}/*a=1,b="a"a=1,b="b"a=2,b="a"a=2,b="b"n=3*/以上代码平淡无奇,不过只要简单分析一下就不难发现,函数f()仅在Main中调用,而函数g()仅在f中调用。如果语言中存在局部函数,根据函数作用域最小化原则,f()应该在Main中定义,而函数g()应该在f()中定义。
虽然C#中并没有真正的局部函数,但是我们可以将lambda视为局部函数的代用品。
以下使用lambda的改进版:
using System;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { Func<int, int> f = a => { Action<string> g = b => Console.WriteLine("a={0},b=\"{1}\"", a, b); g("a"); g("b"); return a; }; int n = f(1) + f(2); Console.WriteLine("n={0}", n); } }}将lambda用作局部函数时,应注意一下几点:a
C++版本:
#include <iostream>#include <string>using namespace std;int main(){auto f = [](int a)->int{auto g = [&](string b){cout << "a=" << a << ",b=" << b << endl;};g("a");g("b");return a;};int n = f(1) + f(2);cout << "n=" << n << endl;return 0;} 