APPLYING OPERATIONS: MAP

The Map function is quite simple — but then that’s the nature of the standard higher order functions; that’s what makes them the great building blocks they are in functional programming. Map takes a list of elements and a function to call with each element in turn. Then it constructs a new list from the results of the function calls and returns that new list.

Using iterators in C#, Map can be implemented lazily. Here is the implementation from FCSlib:

static IEnumerable<R> Map<T, R>(Converter<T, R> function, IEnumerable<T> list)

{

  foreach (T sourceVal in list)

    yield return function(sourceVal);

}

The Converter<T,R> delegate type is a function that receives a parameter of type T and returns an element of type R. The name Converter can be a bit misleading, since the function doesn’t necessarily convert anything. It might just as well extract something, which is a major use case of the Map function. For example, given a list of objects, Map can be used to extract a particular property from each of the objects:

var people = new List<Person> {

  new Person {Name = "Harry", Age = 32},

  new Person {Name = "Anna", Age = 45},

  new Person {Name = "Willy", Age = 43},

  new Person {Name = "Rose", Age = 37}

};

var names = Functional.Map(p => p.Name, people);

Of course, actual calculations can be performed just as easily:

var squares = Functional.Map(i => i * i, Enumerable.Range(1, 10));

Using Criteria: Filter

Filter is a function that applies criteria to ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.