Lambda expressions

wwiki
이동: 둘러보기, 검색

LISP에 들어 있다. λxyㆍplus(x, y) 처럼 함수를 사용하는 변수를 명시하는 표기방법이다. λ(람다)는 그리스 문자로 물리에서는 소립자의 하나이고, 부피의 단위로 100만분의 1을 나타내기도 한다.

c#에서 람다표현식을 사용해서 익명함수를 만든다.

=> : 람다 선언 연산자이다.

(input-parameter, ...) => expression
(input-parameters) => { <sequence-of-statements> }
class Program
{
    delegate int Calc(int a, int b);
  
    public static void Main(string [] args)
    {
        Calc c = (a, b) => a +b;
        int sum = c(1,1);
    }
}

람다 식에서 값을 반환하지 않는 경우 Action 대리자 형식 중 하나로 변환할 수 있다.

Action hello = () => Console.WriteLine("Hello");

hell();

매개변수가 2개이고 값을 반환하지 않는 람다식은 Action<T1, T2>대리자로 변환할 수 있다.

Action<int, int> showSum = (x, y) => 
{
    int sum = x + y;
    Console.Write(sum);
}
showSum(1, 2);

값을 반환하는 경우 Func대리자 형식으로 변환할 수 있다. 매개변수가 하나이고 값을 반환하는 람다식은 Func<T, TResult> 대리자로 변환할 수 있다.

Func<int> func = () => 10; // 10을 반환
int ten = func();

Func<int, int> square = (x) => x*x;
Cosole.Write(square(10)); // 100출력
// Declare a Func variable and assign a lambda expression to the
// variable. The method takes a string and converts it to uppercase.
Func<string, string> selector = str => str.ToUpper();

// Create an array of strings.
string[] words = { "orange", "apple", "Article", "elephant" };
// Query the array and select strings according to the selector method.
IEnumerable<String> aWords = words.Select(selector);

// Output the results to the console.
foreach (String word in aWords)
    Console.WriteLine(word);

/*
This code example produces the following output:

ORANGE
APPLE
ARTICLE
ELEPHANT

*/

'Expression lambda'는 'expression tree' 타입으로 변환할 수 있다.

System.Linq.Expressions.Expression<Func<int, int>> e = x => x * x;
Console.WriteLine(e);
// Output:
// x => (x * x)

Expression lambdas(식 람다)[편집 | 원본 편집]

블록이 없는 람다

(input-parameters) => expression

Statement lambdas(문 람다)[편집 | 원본 편집]

블록이 있는 람다이다.

(input-parameters) => { <sequence-of-statements> }