Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the compelling scenario for using Monads in C#

Tags:

Let me state up front that I have an infantile understanding of Monads. I have read the various threads on Monads here and have done a few hours of study on the concept. I hardly feel comfortable with the term, but I think it is safe to say that I generally understand what a Monad is/does.

I'm a C# developer who is looking to improve the way I work. What would help me further in my Monaducation is see a real world application of a Monad in C# (i.e. via a linq SelectMany() or somesuch) that is clearly an improvement over other ways of solving the same sort of problem in oldskool C#.

Has anyone seen such a beast?

like image 225
Kevin Won Avatar asked May 15 '09 03:05

Kevin Won


People also ask

What is the purpose of a monad?

A monad is an algebraic structure in category theory, and in Haskell it is used to describe computations as sequences of steps, and to handle side effects such as state and IO. Monads are abstract, and they have many useful concrete instances. Monads provide a way to structure a program.

What are monads explain with example?

In functional programming, a monad is a software design pattern with a structure that combines program fragments (functions) and wraps their return values in a type with additional computation.

How do monads work?

So in simple words, a monad is a rule to pass from any type X to another type T(X) , and a rule to pass from two functions f:X->T(Y) and g:Y->T(Z) (that you would like to compose but can't) to a new function h:X->T(Z) . Which, however, is not the composition in strict mathematical sense.

What is monad C#?

In C# terms, a Monad is a generic class with two operations: constructor and bind. class Monad<T> { Monad(T instance); Monad<U> Bind(Func<T, Monad<U>> f); } Constructor is used to put an object into container, Bind is used to replace one contained object with another contained object.


2 Answers

Here is one such scenario: you want to author a parsing library (a nice example of an embedded DSL), and you discover that the best ones are monadic parser combinator libraries. So you write it leveraging LINQ syntax sugars to author C# code that has the same structure as the grammar of the language you're parsing, and you get the benefits of an awesome programming model for on-the-fly semantic analysis and error-recovery. See this blog for a description.

like image 150
Brian Avatar answered Oct 19 '22 16:10

Brian


Find Pythagorean triples:

  var r = from a in Enumerable.Range(1, 25)
          from b in Enumerable.Range(a, 25-a)
          from c in Enumerable.Range(b, 25-b)
          where a*a + b*b == c*c
          select new [] { a, b, c };
like image 42
Greg Bacon Avatar answered Oct 19 '22 17:10

Greg Bacon