|
![](/i/fill.gif) |
On 13/03/2013 09:30 PM, Orchid Win7 v1 wrote:
> OK, so just for giggles, I tried to implement monads in C#.
>
> The short version: It appears that I can create a class with forms a
> monad, however it appears to be impossible to define the concept of
> "being a monad" such that you can write code which polymorphically works
> for any monad.
It appears I missed the elephant in the room. Apparently C# already
*has* several classes which form monads, and even a special monad
comprehension syntax for dealing with them.
Consider the following Haskell parser:
identifier :: Parser String
identifier = do
leading <- many space
first <- letter
rest <- many alphanum
trailing <- many space
return ([first] ++ rest)
Now consider the following C# LINQ query:
Parser<string> identifier =
from leading in Parse.Whitespace.Many()
from first in Parse.Letter.Once()
from rest in Parse.LetterOrDigit.Many()
from trailing in Parse.Whitespace.Many()
select new string(first.Concat(rest).ToArray());
Notice any similarity?
C# *already* has monads. The designers of LINQ even explicitly mention
Haskell and monads as influencing their design.
So much for "only functional programmers understand monads and only
functional programmers need monads"... :-P Monads are in fact one of the
star features of a highly commercially successful programming platform.
(Although I'll admit LINQ is definitely tailored more towards
*container* monads rather than being a general monad framework.)
I notice in passing that there is no "interface" which describes all the
methods you have to implement to make a monad. (Or to make something
that LINQ will work on.) Rather, it uses a strange system of "extension
methods" - a very un-OO concept, if you look it up. But anyway, LINQ
queries let you easily write monadic expressions without drowning in a
sea of lambda functions.
Post a reply to this message
|
![](/i/fill.gif) |