concept Bind in category c#

appears as: Bind
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.

It’s in such scenarios that Bind is handy. For Option, this is the signature of Bind:

Option.Bind : (Option<T>, (T → Option<R>)) → Option<R>

That is, Bind takes an Option and an Option-returning function, and applies the function to the inner value of the Option. Here’s the implementation.

Listing 4.3. Implementation of Bind and Map for Option

4.3.2. Flattening nested lists with Bind

You’ve just seen how you can use Bind to avoid having nested Options. The same idea applies to lists. But what are nested lists? Two-dimensional lists! We need a function that will apply a list-returning function to a list. But rather than returning a two-dimensional list, it should flatten the result into a one-dimensional list.

Remember that Map loops over a given IEnumerable and applies a function to each element. Bind is similar, but with a nested loop, because applying the “bound” function also yields an IEnumerable. The resulting list is flattened to a one-dimensional list. It’s probably easier to see this in code:

public static IEnumerable<R> Bind<T, R>
   (this IEnumerable<T> ts, Func<T, IEnumerable<R>> f)
{
   foreach (T t in ts)
      foreach (R r in f(t))
         yield return r;
}

If you’re intimately familiar with LINQ, you’ll recognize that this implementation is virtually identical to SelectMany. So for IEnumerable, Bind and SelectMany are identical. Again, in this book I’ll use the name Bind because it’s standard in FP-speak.