Map - 7 higher order functions
This is the first blog post in a series of posts that will talk about higher order functions. We'll start off easy with a function called Map that I hope everyone has encountered and are using regularly.
Map
The most common higher order function is map, which is also called collect in Ruby, array map in PHP and select in C#. Map takes a function that is run on every item in a collection, then returns the changed collection.
Examples
Map(i => i * 2, new [] {1, 2, 3});
An array [1, 2, 3] run the lambda i => i * 2 on every item in the list. This returns a list [1, 4, 6]. We can extract the lambda function to make it more readable and easily testable.
Map(Double, new [] {1, 2, 3});
Implementation
The implementation of map in C# is quite straight forward.
if (list == null)
{
throw new ArgumentNullException("list", "Supplied list to Map is not allowed to be null");
}
foreach (var item in list)
{
yield return fn(item);
}
}
Map(i => i.ToString(), new[] {1, 2, 3}) -> ["1", "2", "3"]
Realistic example
In .NET Framework you have Map as an extension method on IEnumerable
var names = people.Select(p => p.FirstName + " " + p.Surname);
/* => new [] { "Mikael Lundin", "John Doe", "Foo Bar" } */
Conclusion
If you have a list that needs to be transformed, you should be using a Map function. It will compose code that you've probably written hundreds of times into a nice pattern that is well understood other developers. Less code, more love!