by arianvanp · 13y ago · 0 comments
Heck, the type signature of SelectMany and (>>=) are even the same!
(>>=) :: m a -> (a -> m b) -> m b
and public static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector
)
m = IEnumerable
b = TResult
a = TSource
=> m<a> SelectMany<a,b>(this m<a> source, Func<a,m<b>> selector)
The type signatures are _EXACTLY_ the same. This isn't a coincidence. LINQ is actually a monad :)So I think taking this approach to explain the Monad voodoo to a C# programmer is the way to go. He actually uses them already :)
I once copied the style of a maybe monad using LINQ - the WinRT apis lack a "FileExists?" method, so I used LINQ to search a directory's contents for a filename. An IEnumerable of size of zero represented None, and size one represented Some.
Unfortunately, a simple try/catch around an attempt to open the desired file was more efficient and clearer to understand.
Here, I wrote the Reader monad for IoC to show it could be done: