POV-Ray : Newsgroups : povray.off-topic : Monads in C# : C# monads Server Time
29 Jul 2024 02:25:19 EDT (-0400)
  C# monads  
From: Orchid Win7 v1
Date: 28 Mar 2013 09:03:47
Message: <51543fb3$1@news.povray.org>
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

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.