concept Map in category c#

appears as: Map
Functional Programming in C#: How to write better C# code

This is an excerpt from Manning's book Functional Programming in C#: How to write better C# code.

An implementation of Map for IEnumerable can be written as follows.

Listing 4.1. Map applies a function to each element of the given IEnumerable
public static IEnumerable<R> Map<T, R> (this IEnumerable<T> ts, Func<T, R> f) { foreach (var t in ts) yield return f(t); }

Map maps a list of T’s to a list of R’s by applying a function T → R to each element in the source list. Notice that in this implementation the results are packaged into an IEnumerable as a result of using the yield return statement.

Maybe you recognized that this is exactly the behavior you get when you call LINQ’s Select method. Indeed, Map can be defined in terms of Select:

public static IEnumerable<R> Map<T, R>
   (this IEnumerable<T> ts, Func<T, R> f)
   => ts.Select(f);

This is potentially more efficient, because LINQ’s implementation of Select is optimized for some specific implementations of IEnumerable. The point is that I’m going to use the name Map, rather than Select, because Map is the standard terminology in FP, but you should consider Map and Select synonyms.

Listing 4.2. Definition of Map for Option
public static Option<R> Map<T, R> (this Option<T> optT, Func<T, R> f) => optT.Match( () => None, (t) => Some(f(t)));

If the given option is None, Map will just return an Option of the expected return type in the None state. If it’s Some(t), where t is the wrapped value, it will feed t to the given function (T → R) and then lift the resulting value into a new Option. You can see this in figure 4.2.

Figure 4.2. Mapping a function over an Option

Intuitively, it can be useful to think of Option as a special kind of list that can either be empty (None) or contain exactly one value (Some). If you look at it in this light, it becomes very clear that the implementations of Map for Option and IEnumerable are consistent: the given function gets applied to all available inner values of the structure.

  • Implement Map for ISet<T> and IDictionary<K, T>. (Tip: start by writing down the signature in arrow notation.)
  • Implement Map for Option and IEnumerable in terms of Bind and Return.