CSharp/Functional Programming

Functors (Map, Filter, Reduce)

yogingang 2022. 9. 15. 00:00
반응형

Functor는 값이 있는 컨테이너이며 해당 값에 함수를 적용하면 내부 값이 변환된 동일한 종류의 컨테이너를 얻게 된다. 

대표적으로 Map, Filter, Reduce 등이 있다. 

 

Map 

: 일련 의 항목을 가져와서 각 항목에 일부 변환을 적용하고 결과 항목과 함께 새 시퀀스를 반환한다.

 

Filter

: 시퀀스를 특정 condition 으로 필터링하여 필터링된 항목만 포함하는 새 시퀀스를 반환한다.

 

Reduce

: 일련의 배열이 있고 이 중에 두 개를 취해서 일부 처리를 수행한 후 하나를 반환하는 함수.

 

 

그렇다면 C# 에서  이들을 어떻게 구현 해볼 수 있을까?

물론 하나 하나를 다 구현 할 수 있지만 C# 에서는 이미 이와 관련된 내용이 구현되어 있다.

우리는 Linq 와 lambda 식을 이용해서 위 내용들을 간단히 사용할 수 있다. 

 

Map ==> Select

https://yogingang.tistory.com/46

 

LINQ Projection 연산자 (Select)

ProductList 와 CusomerList 는 아래 sample 참고 https://github.com/dotnet/try-samples/tree/main/101-linq-samples/src/DataSources GitHub - dotnet/try-samples Contribute to dotnet/try-samples developme..

yogingang.tistory.com

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var multipleNumbers =  numbers.Select(n => n * 2);
// [2,4,6,8,10,12,14,16,18]
var squaredNumbers = numbers.Select(n => n * n);
// [1,4,9,16,25,36,49,64,81]

 

Filter ==> Where

https://yogingang.tistory.com/45

 

LINQ 제한 연산자 (Where)

ProductList 와 CusomerList 는 아래 sample 참고 https://github.com/dotnet/try-samples/tree/main/101-linq-samples/src/DataSources GitHub - dotnet/try-samples Contribute to dotnet/try-samples developme..

yogingang.tistory.com

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var evenNumbers = numbers.Where(n => n % 2 == 0);
// [2,4,6,8]
var multipleOf3Numbers = numbers.Where(n => n % 3 == 0);
// [3,6,9]

 

Reduce ==> Aggregate

https://yogingang.tistory.com/54

 

LINQ Aggregator Operators (집계연산자)

시퀀스의 값에 대해 계산을 수행하는 방법 Count // 중복되는 값을 제거하고 counting int[] factorsOf300 = { 2, 2, 3, 5, 5 }; int uniqueFactors = factorsOf300.Distinct().Count(); Console.WriteLine($"Ther..

yogingang.tistory.com

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var sumNumbers = numbers.Aggregate((x, y) => x + y);
// 45
var multipleNumbers = numbers.Aggregate((x, y) => x * y);
// 362880

 

 

 

관련영상

https://youtu.be/Q0Qq7i6YHEo

 

 

 

반응형