In this series we’re approaching an understanding of monads “bottom up”, by trying to suss out the pattern, rather than by going “top down”, starting with category theory or functional language practice. Last time I identified five generic types that are frequently used in C#; today we’ll start looking for commonalities beyond their being generic types.
Last time on FAIC I set out to explore monads from an object-oriented programmer’s perspective, rather than delving into the functional programmer’s perspective immediately. The “monad pattern” is a design pattern for types, and a “monad” is a type that uses that pattern. Rather than describing the pattern itself, let’s start by listing some monad-ish types that you are almost certainly very familiar with, and see what they have in common.
These five types are the ones that immediately come to my mind; I am probably missing some. If you have an example of a commonly-used C# type that is monadic in nature, please leave a comment.
Nullable<T>— represents a T that could be null
Func<T>— represents a T that can be computed on demand
Lazy<T>— represents a T that can be computed on demand once, then cached
Task<T>— represents a T that is being computed asynchronously and will be available in the future, if it isn’t already
IEnumerable<T>— represents an ordered, read-only sequence of zero or more Ts
Lots of other bloggers have attempted this, but what the heck, I’ll give it a shot too. In this series I’m going to attempt to answer the question:
I’m a C# programmer with no “functional programming” background whatsoever. What is this “monad” thing I keep hearing about, and what use is it to me?
Bloggers often attempt to tackle this problem by jumping straight into the functional programming usage of the term, and start talking about “bind” and “unit” operations, and higher-order functional programming with higher-order types. Even worse is to go all the way back to the category theory underpinning monads and start talking about “monoids in the category endofunctors” and the like. I want to start from a much more pragmatic, object-oriented, C#-type-system focussed place and move towards the rarefied heights of functional programming as we go. Continue reading