Skip to main content

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.


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.


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.

private int Double(int i)
  return i * 2;

Map(Double, new [] {1, 2, 3});


The implementation of map in C# is quite straight forward.

public static IEnumerable<U> Map<T, U>(Func<T, U> fn, IEnumerable<T> list)
    if (fn == null)
        throw new ArgumentNullException("fn", "Supplied function to Map is not allowed to be null");

if (list == null)
    throw new ArgumentNullException(&quot;list&quot;, &quot;Supplied list to Map is not allowed to be null&quot;);

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 called Select, as a part of LINQ. You should use that instead of rolling your own. In a more realistic example, you've gotten a list of people from data source, and would like to extract their names.

var people = new[]
    new Person { FirstName = "Mikael", Surname = "Lundin" },
    new Person { FirstName = "John", Surname = "Doe" },
    new Person { FirstName = "Foo", Surname = "Bar" },

var names = people.Select(p => p.FirstName + " " + p.Surname);

/* => new [] { "Mikael Lundin", "John Doe", "Foo Bar" } */


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!

comments powered by Disqus