From the course: Advanced C#: Functional Programming Patterns

Understand map and other concepts - C# Tutorial

From the course: Advanced C#: Functional Programming Patterns

Understand map and other concepts

- [Instructor] Many programming languages have a concept called map. In functional programming, map is implemented as a higher order function. A map function usually has at least two parameters. One is a list of data and the other is a delegate or Lambda. The map applies the function to each item in the list, which is primarily used to transform the list of data. The list is called a functor in functional programming. So we could say we are applying the map to a functor. Here's what this might look like in a functional language. On line 13, we are declaring a function variable and using X times X as the operation. Line 16 declares an array. Then online 18, we can use the map keyword to apply this square function to every item in the array. In C#, we don't have a map keyword. This is typically implemented as an extension method. We usually implement the functor in our higher order function as I enumerable of T. That way our map function can work with arrays and most of the .NET collection types. We've seen an example of map earlier in this course when I talked about pipelining. Here is the code from that example. TransformAsPipeline, shown on line 40, is our extension method, and it's a higher order function that is operating on the I enumerable of T parameter. The transformer function is modifying each item in the source and outputting the transformed items into a new I enumerable of T. There is a map function built into LINQ, language integrated query. It's called select. This could have been named map, but Microsoft implemented this as part of the language integrated query feature and modeled it after structured query language, or SQL, where a map is called select. You'll see other areas in LINQ that have different names for functional programming concepts. For example, filter's called Where in LINQ. The bind pattern appears in LINQ as SelectMany and ContinueWith. And the fold concept is aliased to various LINQ functions, like Sum and Aggregate. Overall, the name differences aren't important in most cases. Calculating a total from a list of items is useful, whether you call it fold or sum, what we'll look at in the rest of this chapter is how to use these concepts in LINQ.

Contents