C# LINQ, Monads, and Abstraction
I want to show you a little trick. If you are a C# developer looking to learn some functional programming, this post might be interesting for you.
LINQ SelectMany
Here’s the definition of the SelectMany method in C# LINQ:
public static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector
)This method gets two parameters:
source—which is a sequence of values;selector—which is a function that should be applied to each value in thesource.
The method returns a sequence of values, each element is the result of invoking the selector function to an item in the source.
Type parameters allows to specify a type of the source elements as TSource and a type of returned elements as TResult.
You may check examples of using SelectMany method.
Moving from C# to Haskell
Now let’s do some simple changes.
First, let’s change types TSouce and TResult to a shorter versions of a and b. We’ll get:
public static IEnumerable<b> SelectMany<a, b>(
this IEnumerable<a> source,
Func<a, IEnumerable<b>> selector
)Now, let’s change the name of the interface from IEnumerable to M:
public static M<b> SelectMany<a, b>(
this M<a> source,
Func<a, M<b>> selector
)And now for the interesting part.
Let’s switch this method definition from C# language to Haskell. Without changing any types the signature of SelectMany will look like the following:
SelectMany :: M a -> (a -> M b) -> M bThis definition describes the same signature as the original SelectMany definition.
Monads
If we’ll look at the Monad definition in Haskell, we’ll find that each Monad should have an implementation of the bind operator that has the following signature:
(>>=) :: M a -> (a -> M b) -> M bAs you can see, the signature is the same as in LINQ SelectMany method. And it is not a coincidence.
If you are a C# developer interested in functional programming, I recommend you to watch this video with Brian Beckman. It won’t make you a functional programming expert, but it is a good starting point in learning it.
Have fun! And don’t fear the Monad!