5 ms·
Monads should be a familiar concept for the seasoned C# programmer. LINQ's 'from in' syntax and the haskell monad 'do' syntax are almost the same! Heck, the
by arianvanp 14y ago
Monads should be a familiar concept for the seasoned C# programmer. LINQ's 'from in' syntax and the haskell monad 'do' syntax are almost the same!
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 :)
- daknok 14y agoLINQ is very similar to the List monad, specifically.
- chadzawistowski 14y agoFurther proof for my personal conviction that C# is a very interesting, progressive language which masquerades as a Java clone. 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.
- daknok 14y agoYou should use try/catch; branching would imply a race condition in a multithreaded environment (what if another process deletes the file between the check and the use of the file?).
- krallja 14y agoLINQ has an .Empty() extension method, and you should use that instead of .Count()==0 when determining if an expression is empty.
- snprbob86 14y agoLikewise, Scala's "for" loop compiles to calls to map and flatMap, which are the same as Select and SelectMany, which represent the list monad. You can use map, flatMap, and for notation in lieu of a more generally named do syntax.
- runT1ME 14y agoIt goes beyond that . LINQ isn't a monad, it's monadic syntax for any monad. It just so happens that the one everyone uses is IEnumerable. Here, I wrote the Reader monad for IoC to show it could be done: https://gist.github.com/vmarquez/4640678 https://gist.github.com/vmarquez/4640678