<p>Having briefly looked at Haskell recently, what would be a <em>brief, succinct, practical</em> explanation as to what a monad essentially is?</p>

<p>I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail.</p>

[{'answer_id': 2538, 'author': 'nlucaroni', 'author_id': 157, 'author_profile': 'https://Stackoverflow.com/users/157', 'pm_score': 7, 'selected': False, 'text': '<p>But, <a href="http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html" rel="noreferrer">You could have invented Monads!</a></p>\n\n<blockquote>\n  <p>sigfpe says:</p>\n  \n  <blockquote>\n    <p>But all of these introduce monads as something esoteric in need of explanation. But what I want to argue is that they aren\'t esoteric at all. In fact, faced with various problems in functional programming you would have been led, inexorably, to certain solutions, all of which are examples of monads. In fact, I hope to get you to invent them now if you haven\'t already. It\'s then a small step to notice that all of these solutions are in fact the same solution in disguise. And after reading this, you might be in a better position to understand other documents on monads because you\'ll recognise everything you see as something you\'ve already invented.</p>\n    \n    <p>Many of the problems that monads try to solve are related to the issue of side effects. So we\'ll start with them. (Note that monads let you do more than handle side-effects, in particular many types of container object can be viewed as monads. Some of the introductions to monads find it hard to reconcile these two different uses of monads and concentrate on just one or the other.)</p>\n    \n    <p>In an imperative programming language such as C++, functions behave nothing like the functions of mathematics. For example, suppose we have a C++ function that takes a single floating point argument and returns a floating point result. Superficially it might seem a little like a mathematical function mapping reals to reals, but a C++ function can do more than just return a number that depends on its arguments. It can read and write the values of global variables as well as writing output to the screen and receiving input from the user. In a pure functional language, however, a function can only read what is supplied to it in its arguments and the only way it can have an effect on the world is through the values it returns.</p>\n  </blockquote>\n</blockquote>\n'}, {'answer_id': 35744, 'author': 'Jared Updike', 'author_id': 2543, 'author_profile': 'https://Stackoverflow.com/users/2543', 'pm_score': 4, 'selected': False, 'text': '<p>My favorite Monad tutorial:</p>\n\n<p><a href="http://www.haskell.org/haskellwiki/All_About_Monads" rel="noreferrer">http://www.haskell.org/haskellwiki/All_About_Monads</a></p>\n\n<p>(out of 170,000 hits on a Google search for "monad tutorial"!)</p>\n\n<p>@Stu: The point of monads is to allow you to add (usually) sequential semantics to otherwise pure code; you can even compose monads (using Monad Transformers) and get more interesting and complicated combined semantics, like parsing with error handling, shared state, and logging, for example. All of this is possible in pure code, monads just allow you to abstract it away and reuse it in modular libraries (always good in programming), as well as providing convenient syntax to make it look imperative.</p>\n\n<p>Haskell already has operator overloading[1]: it uses type classes much the way one might use interfaces in Java or C# but Haskell just happens to also allow non-alphanumeric tokens like + &amp;&amp; and > as infix identifiers. It\'s only operator overloading in your way of looking at it if you mean "overloading the semicolon" [2]. It sounds like black magic and asking for trouble to "overload the semicolon" (picture enterprising Perl hackers getting wind of this idea) but the point is that without monads <i>there is no semicolon, since purely functional code does not require or allow explicit sequencing.</i></p>\n\n<p>This all sounds much more complicated than it needs to. sigfpe\'s article is pretty cool but uses Haskell to explain it, which sort of fails to break the chicken and egg problem of understanding Haskell to grok Monads and understanding Monads to grok Haskell.</p>\n\n<p>[1] This is a separate issue from monads but monads use Haskell\'s operator overloading feature.</p>\n\n<p>[2] This is also an oversimplification since the operator for chaining monadic actions is >>= (pronounced "bind") but there is syntactic sugar ("do") that lets you use braces and semicolons and/or indentation and newlines.</p>\n'}, {'answer_id': 37039, 'author': 'Scott Wisniewski', 'author_id': 1737192, 'author_profile': 'https://Stackoverflow.com/users/1737192', 'pm_score': 5, 'selected': False, 'text': '<p>A monad is, effectively, a form of "type operator". It will do three things. First it will "wrap" (or otherwise convert) a value of one type into another type (typically called a "monadic type"). Secondly it will make all the operations (or functions) available on the underlying type available on the monadic type. Finally it will provide support for combining its self with another monad to produce a composite monad.</p>\n\n<p>The "maybe monad" is essentially the equivalent of "nullable types" in Visual Basic / C#. It takes a non nullable type "T" and converts it into a "Nullable&lt;T&gt;", and then defines what all the binary operators mean on a Nullable&lt;T&gt;.</p>\n\n<p>Side effects are represented simillarly. A structure is created that holds descriptions of side effects alongside a function\'s return value. The "lifted" operations then copy around side effects as values are passed between functions.</p>\n\n<p>They are called "monads" rather than the easier-to-grasp name of "type operators" for several reasons:</p>\n\n<ol>\n<li>Monads have restrictions on what they can do (see the definiton for details).</li>\n<li>Those restrictions, along with the fact that there are three operations involved, conform to the structure of something called a monad in Category Theory, which is an obscure branch of mathematics.</li>\n<li>They were designed by proponents of "pure" functional languages</li>\n<li>Proponents of pure functional languages like obscure branches of mathematics</li>\n<li>Because the math is obscure, and monads are associated with particular styles of programming, people tend to use the word monad as a sort of secret handshake. Because of this no one has bothered to invest in a better name.</li>\n</ol>\n'}, {'answer_id': 44979, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 2, 'selected': False, 'text': '<p>A monad is a thing used to encapsulate objects that have changing state. It is most often encountered in languages that otherwise do not allow you to have modifiable state (e.g., Haskell).</p>\n\n<p>An example would be for file I/O.</p>\n\n<p>You would be able to use a monad for file I/O to isolate the changing state nature to just the code that used the Monad. The code inside the Monad can effectively ignore the changing state of the world outside the Monad - this makes it a lot easier to reason about the overall effect of your program.</p>\n'}, {'answer_id': 45151, 'author': 'Chris Conway', 'author_id': 1412, 'author_profile': 'https://Stackoverflow.com/users/1412', 'pm_score': 6, 'selected': False, 'text': '<p>A monad is a datatype that has two operations: <code>&gt;&gt;=</code> (aka <code>bind</code>) and <code>return</code> (aka <code>unit</code>). <code>return</code> takes an arbitrary value and creates an instance of the monad with it. <code>&gt;&gt;=</code> takes an instance of the monad and maps a function over it. (You can see already that a monad is a strange kind of datatype, since in most programming languages you couldn\'t write a function that takes an arbitrary value and creates a type from it. Monads use a kind of <a href="http://en.wikipedia.org/wiki/Type_polymorphism" rel="noreferrer"><em>parametric polymorphism</em></a>.)</p>\n\n<p>In Haskell notation, the monad interface is written</p>\n\n<pre><code>class Monad m where\n  return :: a -&gt; m a\n  (&gt;&gt;=) :: forall a b . m a -&gt; (a -&gt; m b) -&gt; m b\n</code></pre>\n\n<p>These operations are supposed to obey certain "laws", but that\'s not terrifically important: the "laws" just codify the way sensible implementations of the operations ought to behave (basically, that <code>&gt;&gt;=</code> and <code>return</code> ought to agree about how values get transformed into monad instances and that <code>&gt;&gt;=</code> is associative).</p>\n\n<p>Monads are not just about state and I/O: they abstract a common pattern of computation that includes working with state, I/O, exceptions, and non-determinism. Probably the simplest monads to understand are lists and option types:</p>\n\n<pre><code>instance Monad [ ] where\n    []     &gt;&gt;= k = []\n    (x:xs) &gt;&gt;= k = k x ++ (xs &gt;&gt;= k)\n    return x     = [x]\n\ninstance Monad Maybe where\n    Just x  &gt;&gt;= k = k x\n    Nothing &gt;&gt;= k = Nothing\n    return x      = Just x\n</code></pre>\n\n<p>where <code>[]</code> and <code>:</code> are the list constructors, <code>++</code> is the concatenation operator, and <code>Just</code> and <code>Nothing</code> are the <code>Maybe</code> constructors. Both of these monads encapsulate common and useful patterns of computation on their respective data types (note that neither has anything to do with side effects or I/O).</p>\n\n<p>You really have to play around writing some non-trivial Haskell code to appreciate what monads are about and why they are useful.</p>\n'}, {'answer_id': 47997, 'author': 'ShreevatsaR', 'author_id': 4958, 'author_profile': 'https://Stackoverflow.com/users/4958', 'pm_score': 5, 'selected': False, 'text': '<p><em>(See also the answers at <strong><a href="https://stackoverflow.com/questions/44965/what-is-a-monad">What is a monad?</a></strong>)</em></p>\n\n<p>A good motivation to Monads is sigfpe (Dan Piponi)\'s <a href="http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html" rel="noreferrer">You Could Have Invented Monads! (And Maybe You Already Have)</a>. There are <a href="http://www.haskell.org/haskellwiki/Monad_tutorials_timeline" rel="noreferrer">a LOT of other monad tutorials</a>, many of which misguidedly try to explain monads in "simple terms" using various analogies: this is the <a href="http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/" rel="noreferrer">monad tutorial fallacy</a>; avoid them.</p>\n\n<p>As DR MacIver says in <em><a href="http://www.drmaciver.com/2008/02/tell-us-why-your-language-sucks/" rel="noreferrer">Tell us why your language sucks</a></em>: <blockquote>\n<P>\n<strong>So, things I hate about Haskell:</strong>\n</p>\n<p>\n    Let’s start with the obvious. Monad tutorials. No, not monads. Specifically the tutorials. They’re endless, overblown and dear god are they tedious. Further, I’ve never seen any convincing evidence that they actually help. Read the class definition, write some code, get over the scary name. </p></blockquote></p>\n\n<p>You say you understand the Maybe monad? Good, you\'re on your way. Just start using other monads and sooner or later you\'ll understand what monads are in general.</p>\n\n<p>[If you are mathematically oriented, you might want to ignore the dozens of tutorials and learn the definition, or follow <a href="http://lambda-the-ultimate.org/node/2455" rel="noreferrer">lectures in category theory</a> :)\nThe main part of the definition is that a Monad M involves a "type constructor" that defines for each existing type "T" a new type "M T", and some ways for going back and forth between "regular" types and "M" types.]</p>\n\n<p>Also, surprisingly enough, one of the best introductions to monads is actually one of the early academic papers introducing monads, Philip Wadler\'s <a href="http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf" rel="noreferrer">Monads for functional programming</a>. It actually has practical, <em>non-trivial</em> motivating examples, unlike many of the artificial tutorials out there.</p>\n'}, {'answer_id': 71579, 'author': 'Benjol', 'author_id': 11410, 'author_profile': 'https://Stackoverflow.com/users/11410', 'pm_score': 2, 'selected': False, 'text': '<p>If I\'ve understood correctly, IEnumerable is derived from monads. I wonder if that might be an interesting angle of approach for those of us from the C# world?</p>\n\n<p>For what it\'s worth, here are some links to tutorials that helped me (and no, I still haven\'t understood what monads are).</p>\n\n<ul>\n<li><a href="http://osteele.com/archives/2007/12/overloading-semicolon" rel="nofollow noreferrer">http://osteele.com/archives/2007/12/overloading-semicolon</a></li>\n<li><a href="http://spbhug.folding-maps.org/wiki/MonadsEn" rel="nofollow noreferrer">http://spbhug.folding-maps.org/wiki/MonadsEn</a></li>\n<li><a href="http://www.loria.fr/~kow/monads/" rel="nofollow noreferrer">http://www.loria.fr/~kow/monads/</a></li>\n</ul>\n'}, {'answer_id': 71697, 'author': 'Arnar', 'author_id': 10442, 'author_profile': 'https://Stackoverflow.com/users/10442', 'pm_score': 8, 'selected': False, 'text': '<p>Actually, contrary to common understanding of Monads, they have nothing to do with state. Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it.</p>\n\n<p>For example, you can create a type to wrap another one, in Haskell:</p>\n\n<pre><code>data Wrapped a = Wrap a\n</code></pre>\n\n<p>To wrap stuff we define</p>\n\n<pre><code>return :: a -&gt; Wrapped a\nreturn x = Wrap x\n</code></pre>\n\n<p>To perform operations without unwrapping, say you have a function <code>f :: a -&gt; b</code>, then you can do this to <em>lift</em> that function to act on wrapped values:</p>\n\n<pre><code>fmap :: (a -&gt; b) -&gt; (Wrapped a -&gt; Wrapped b)\nfmap f (Wrap x) = Wrap (f x)\n</code></pre>\n\n<p>That\'s about all there is to understand. However, it turns out that there is a more general function to do this <em>lifting</em>, which is <code>bind</code>:</p>\n\n<pre><code>bind :: (a -&gt; Wrapped b) -&gt; (Wrapped a -&gt; Wrapped b)\nbind f (Wrap x) = f x\n</code></pre>\n\n<p><code>bind</code> can do a bit more than <code>fmap</code>, but not vice versa. Actually, <code>fmap</code> can be defined only in terms of <code>bind</code> and <code>return</code>. So, when defining a monad.. you give its type (here it was <code>Wrapped a</code>) and then say how its <code>return</code> and <code>bind</code> operations work.</p>\n\n<p>The cool thing is that this turns out to be such a general pattern that it pops up all over the place, encapsulating state in a pure way is only one of them.</p>\n\n<p>For a good article on how monads can be used to introduce functional dependencies and thus control order of evaluation, like it is used in Haskell\'s IO monad, check out <a href="http://www.haskell.org/haskellwiki/IO_inside" rel="noreferrer">IO Inside</a>.</p>\n\n<p>As for understanding monads, don\'t worry too much about it. Read about them what you find interesting and don\'t worry if you don\'t understand right away. Then just diving in a language like Haskell is the way to go. Monads are one of these things where understanding trickles into your brain by practice, one day you just suddenly realize you understand them.</p>\n'}, {'answer_id': 86471, 'author': 'Aristotle Pagaltzis', 'author_id': 9410, 'author_profile': 'https://Stackoverflow.com/users/9410', 'pm_score': 6, 'selected': False, 'text': '<p>[Disclaimer: I am still trying to fully grok monads. The following is just what I have understood so far. If it’s wrong, hopefully someone knowledgeable will call me on the carpet.]</p>\n\n<p>Arnar wrote:</p>\n\n<blockquote>\n  <p>Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it.</p>\n</blockquote>\n\n<p>That’s precisely it. The idea goes like this:</p>\n\n<ol>\n<li><p>You take some kind of value and wrap it with some additional information. Just like the value is of a certain kind (eg. an integer or a string), so the additional information is of a certain kind.</p>\n\n<p>E.g., that extra information might be a <code>Maybe</code> or an <code>IO</code>.</p></li>\n<li><p>Then you have some operators that allow you to operate on the wrapped data while carrying along that additional information. These operators use the additional information to decide how to change the behaviour of the operation on the wrapped value.</p>\n\n<p>E.g., a <code>Maybe Int</code> can be a <code>Just Int</code> or <code>Nothing</code>. Now, if you add a <code>Maybe Int</code> to a <code>Maybe Int</code>, the operator will check to see if they are both <code>Just Int</code>s inside, and if so, will unwrap the <code>Int</code>s, pass them the addition operator, re-wrap the resulting <code>Int</code> into a new <code>Just Int</code> (which is a valid <code>Maybe Int</code>), and thus return a <code>Maybe Int</code>. But if one of them was a <code>Nothing</code> inside, this operator will just immediately return <code>Nothing</code>, which again is a valid <code>Maybe Int</code>. That way, you can pretend that your <code>Maybe Int</code>s are just normal numbers and perform regular math on them. If you were to get a <code>Nothing</code>, your equations will still produce the right result – <em>without you having to litter checks for <code>Nothing</code> everywhere</em>.</p></li>\n</ol>\n\n<p>But the example is just what happens for <code>Maybe</code>. If the extra information was an <code>IO</code>, then that special operator defined for <code>IO</code>s would be called instead, and it could do something totally different before performing the addition. (OK, adding two <code>IO Int</code>s together is probably nonsensical – I’m not sure yet.) (Also, if you paid attention to the <code>Maybe</code> example, you have noticed that “wrapping a value with extra stuff” is not always correct. But it’s hard to be exact, correct and precise without being inscrutable.)</p>\n\n<p>Basically, <strong>“monad” roughly means “pattern”</strong>. But instead of a book full of informally explained and specifically named Patterns, you now have <em>a language construct</em> – syntax and all – that allows you to <strong>declare new patterns as things in your program</strong>. (The imprecision here is all the patterns have to follow a particular form, so a monad is not quite as generic as a pattern. But I think that’s the closest term that most people know and understand.)</p>\n\n<p>And that is why people find monads so confusing: because they are such a generic concept. To ask what makes something a monad is similarly vague as to ask what makes something a pattern.</p>\n\n<p>But think of the implications of having syntactic support in the language for the idea of a pattern: instead of having to read the <i>Gang of Four</i> book and memorise the construction of a particular pattern, you just <em>write code that implements this pattern in an agnostic, generic way</em> once and then you are done! You can then reuse this pattern, like Visitor or Strategy or Façade or whatever, just by decorating the operations in your code with it, without having to re-implement it over and over!</p>\n\n<p>So that is why people who <em>understand</em> monads find them so <em>useful</em>: it’s not some ivory tower concept that intellectual snobs pride themselves on understanding (OK, that too of course, teehee), but actually makes code simpler.</p>\n'}, {'answer_id': 143132, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 6, 'selected': False, 'text': '<p>You should first understand what a functor is. Before that, understand higher-order functions.</p>\n\n<p>A <strong>higher-order function</strong> is simply a function that takes a function as an argument.</p>\n\n<p>A <strong>functor</strong> is any type construction <code>T</code> for which there exists a higher-order function, call it <code>map</code>, that transforms a function of type <code>a -&gt; b</code> (given any two types <code>a</code> and <code>b</code>) into a function <code>T a -&gt; T b</code>. This <code>map</code> function must also obey the laws of identity and composition such that the following expressions return true for all <code>p</code> and <code>q</code> (Haskell notation):</p>\n\n<pre><code>map id = id\nmap (p . q) = map p . map q\n</code></pre>\n\n<p>For example, a type constructor called <code>List</code> is a functor if it comes equipped with a function of type <code>(a -&gt; b) -&gt; List a -&gt; List b</code> which obeys the laws above. The only practical implementation is obvious. The resulting <code>List a -&gt; List b</code> function iterates over the given list, calling the <code>(a -&gt; b)</code> function for each element, and returns the list of the results.</p>\n\n<p>A <strong>monad</strong> is essentially just a functor <code>T</code> with two extra methods, <em><code>join</code></em>, of type <code>T (T a) -&gt; T a</code>, and <code>unit</code> (sometimes called <code>return</code>, <code>fork</code>, or <code>pure</code>) of type <code>a -&gt; T a</code>. For lists in Haskell:</p>\n\n<pre><code>join :: [[a]] -&gt; [a]\npure :: a -&gt; [a]\n</code></pre>\n\n<p>Why is that useful? Because you could, for example, <code>map</code> over a list with a function that returns a list. <code>Join</code> takes the resulting list of lists and concatenates them. <code>List</code> is a monad because this is possible.</p>\n\n<p>You can write a function that does <code>map</code>, then <code>join</code>. This function is called <code>bind</code>, or <code>flatMap</code>, or <code>(&gt;&gt;=)</code>, or <code>(=&lt;&lt;)</code>. This is normally how a monad instance is given in Haskell.</p>\n\n<p>A monad has to satisfy certain laws, namely that <code>join</code> must be associative. This means that if you have a value <code>x</code> of type <code>[[[a]]]</code> then <code>join (join x)</code> should equal <code>join (map join x)</code>. And <code>pure</code> must be an identity for <code>join</code> such that <code>join (pure x) == x</code>.</p>\n'}, {'answer_id': 194207, 'author': 'JacquesB', 'author_id': 7488, 'author_profile': 'https://Stackoverflow.com/users/7488', 'pm_score': 10, 'selected': False, 'text': '<p>First: The term <strong>monad</strong> is a bit vacuous if you are not a mathematician. An alternative term is <strong>computation builder</strong> which is a bit more descriptive of what they are actually useful for.</p>\n<p>They are a pattern for chaining operations. It looks a bit like method chaining in object-oriented languages, but the mechanism is slightly different.</p>\n<p>The pattern is mostly used in functional languages (especially Haskell which uses monads pervasively) but can be used in any language which support higher-order functions (that is, functions which can take other functions as arguments).</p>\n<p>Arrays in JavaScript support the pattern, so let’s use that as the first example.</p>\n<p>The gist of the pattern is we have a type (<code>Array</code> in this case) which has a method which takes a function as argument. The operation supplied must return an instance of the same type (i.e. return an <code>Array</code>).</p>\n<p>First an example of method chaining which does <em>not</em> use the monad pattern:</p>\n<pre><code>[1,2,3].map(x =&gt; x + 1)\n</code></pre>\n<p>The result is <code>[2,3,4]</code>. The code does not conform to the monad pattern, since the function we are supplying as an argument returns a number, not an Array. The same logic in monad form would be:</p>\n<pre><code>[1,2,3].flatMap(x =&gt; [x + 1])\n</code></pre>\n<p>Here we supply an operation which returns an <code>Array</code>, so now it conforms to the pattern. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap" rel="noreferrer"><code>flatMap</code></a> method executes the provided function for every element in the array.  It expects an array as result for each invocation (rather than single values), but merges the resulting set of arrays into a single array. So the end result is the same, the array <code>[2,3,4]</code>.</p>\n<p>(The function argument provided to a method like <code>map</code> or <code>flatMap</code> is often called a &quot;callback&quot; in JavaScript. I will call it the &quot;operation&quot; since it is more general.)</p>\n<p>If we chain multiple operations (in the traditional way):</p>\n<pre><code>[1,2,3].map(a =&gt; a + 1).filter(b =&gt; b != 3)\n</code></pre>\n<p>Results in the array <code>[2,4]</code></p>\n<p>The same chaining in monad form:</p>\n<pre><code>[1,2,3].flatMap(a =&gt; [a + 1]).flatMap(b =&gt; b != 3 ? [b] : [])\n</code></pre>\n<p>Yields the same result, the array <code>[2,4]</code>.</p>\n<p>You will immediately notice that the monad form is quite a bit uglier than the non-monad! This just goes to show that monads are not necessarily “good”. They are a pattern which is sometimes beneficial and sometimes not.</p>\n<p>Do note that the monad pattern can be combined in a different way:</p>\n<pre><code>[1,2,3].flatMap(a =&gt; [a + 1].flatMap(b =&gt; b != 3 ? [b] : []))\n</code></pre>\n<p>Here the binding is nested rather than chained, but the result is the same. This is an important property of monads as we will see later. It means two operations combined can be treated the same as a single operation.</p>\n<p>The operation is allowed to return an array with different element types, for example transforming an array of numbers into an array of strings or something else; as long as it still an Array.</p>\n<p>This can be described a bit more formally using Typescript notation. An array has the type <code>Array&lt;T&gt;</code>, where <code>T</code> is the type of the elements in the array. The method <code>flatMap()</code> takes a function argument of the type <code>T =&gt; Array&lt;U&gt;</code> and returns an <code>Array&lt;U&gt;</code>.</p>\n<p>Generalized, a monad is any type <code>Foo&lt;Bar&gt;</code> which has a &quot;bind&quot; method which takes a function argument of type <code>Bar =&gt; Foo&lt;Baz&gt;</code> and returns a <code>Foo&lt;Baz&gt;</code>.</p>\n<p>This answers <em>what</em> monads are. The rest of this answer will try to explain through examples why monads can be a useful pattern in a language like Haskell which has good support for them.</p>\n<p><strong>Haskell and Do-notation</strong></p>\n<p>To translate the map/filter example directly to Haskell, we replace <code>flatMap</code> with the <code>&gt;&gt;=</code> operator:</p>\n<pre><code>[1,2,3] &gt;&gt;= \\a -&gt; [a+1] &gt;&gt;= \\b -&gt; if b == 3 then [] else [b] \n</code></pre>\n<p>The <code>&gt;&gt;=</code> operator is the bind function in Haskell. It does the same as <code>flatMap</code> in JavaScript when the operand is a list, but it is overloaded with different meaning for other types.</p>\n<p>But Haskell also has a dedicated syntax for monad expressions, the <code>do</code>-block, which hides the bind operator altogether:</p>\n<pre><code> do a &lt;- [1,2,3] \n    b &lt;- [a+1] \n    if b == 3 then [] else [b] \n</code></pre>\n<p>This hides the &quot;plumbing&quot; and lets you focus on the actual operations applied at each step.</p>\n<p>In a <code>do</code>-block, each line is an operation. The constraint still holds that all operations in the block must return the same type. Since the first expression is a list, the other operations must also return a list.</p>\n<p>The back-arrow <code>&lt;-</code> looks deceptively like an assignment, but note that this is the parameter passed in the bind. So, when the expression on the right side is a List of Integers, the variable on the left side will be a single Integer – but will be executed for each integer in the list.</p>\n<p><strong>Example: Safe navigation (the Maybe type)</strong></p>\n<p>Enough about lists, lets see how the monad pattern can be useful for other types.</p>\n<p>Some functions may not always return a valid value. In Haskell this is represented by the <code>Maybe</code>-type, which is an option that is either <code>Just value</code> or <code>Nothing</code>.</p>\n<p>Chaining operations which always return a valid value is of course straightforward:</p>\n<pre><code>streetName = getStreetName (getAddress (getUser 17)) \n</code></pre>\n<p>But what if any of the functions could return <code>Nothing</code>? We need to check each result individually and only pass the value to the next function if it is not <code>Nothing</code>:</p>\n<pre><code>case getUser 17 of\n      Nothing -&gt; Nothing \n      Just user -&gt;\n         case getAddress user of\n            Nothing -&gt; Nothing \n            Just address -&gt;\n              getStreetName address\n</code></pre>\n<p>Quite a lot of repetitive checks! Imagine if the chain was longer. Haskell solves this with the monad pattern for <code>Maybe</code>:</p>\n<pre><code>do\n  user &lt;- getUser 17\n  addr &lt;- getAddress user\n  getStreetName addr\n</code></pre>\n<p>This <code>do</code>-block invokes the bind-function for the <code>Maybe</code> type (since the result of the first expression is a <code>Maybe</code>). The bind-function only executes the following operation if the value is <code>Just value</code>, otherwise it just passes the <code>Nothing</code> along.</p>\n<p>Here the monad-pattern is used to avoid repetitive code. This is similar to how some other languages use macros to simplify syntax, although macros achieve the same goal in a very different way.</p>\n<p>Note that it is the <em>combination</em> of the monad pattern and the monad-friendly syntax in Haskell which result in the cleaner code. In a language like JavaScript without any special syntax support for monads, I doubt the monad pattern would be able to simplify the code in this case.</p>\n<p><strong>Mutable state</strong></p>\n<p>Haskell does not support mutable state. All variables are constants and all values immutable. But the <code>State</code> type can be used to emulate programming with mutable state:</p>\n<pre><code>add2 :: State Integer Integer\nadd2 = do\n        -- add 1 to state\n         x &lt;- get\n         put (x + 1)\n         -- increment in another way\n         modify (+1)\n         -- return state\n         get\n\n\nevalState add2 7\n=&gt; 9\n</code></pre>\n<p>The <code>add2</code> function builds a monad chain which is then evaluated with 7 as the initial state.</p>\n<p>Obviously this is something which only makes sense in Haskell. Other languages support mutable state out of the box. Haskell is generally &quot;opt-in&quot; on language features - you enable mutable state when you need it, and the type system ensures the effect is explicit. IO is another example of this.</p>\n<p><strong>IO</strong></p>\n<p>The <code>IO</code> type is used for chaining and executing “impure” functions.</p>\n<p>Like any other practical language, Haskell has a bunch of built-in functions which interface with the outside world: <code>putStrLine</code>, <code>readLine</code> and so on. These functions are called “impure” because they either cause side effects or have non-deterministic results. Even something simple like getting the time is considered impure because the result is non-deterministic – calling it twice with the same arguments may return different values.</p>\n<p>A pure function is deterministic – its result depends purely on the arguments passed and it has no side effects on the environment beside returning a value.</p>\n<p>Haskell heavily encourages the use of pure functions – this is a major selling point of the language. Unfortunately for purists, you need some impure functions to do anything useful. The Haskell compromise is to cleanly separate pure and impure, and guarantee that there is no way that pure functions can execute impure functions, directly or indirect.</p>\n<p>This is guaranteed by giving all impure functions the <code>IO</code> type. The entry point in Haskell program is the <code>main</code> function which have the <code>IO</code> type, so we can execute impure functions at the top level.</p>\n<p>But how does the language prevent pure functions from executing impure functions? This is due to the lazy nature of Haskell. A function is only executed if its output is consumed by some other function. But there is no way to consume an <code>IO</code> value except to assign it to <code>main</code>. So if a function wants to execute an impure function, it has to be connected to <code>main</code> and have the <code>IO</code> type.</p>\n<p>Using monad chaining for IO operations also ensures that they are executed in a linear and predictable order, just like statements in an imperative language.</p>\n<p>This brings us to the first program most people will write in Haskell:</p>\n<pre><code>main :: IO ()\nmain = do \n        putStrLn ”Hello World”\n</code></pre>\n<p>The <code>do</code> keyword is superfluous when there is only a single operation and therefore nothing to bind, but I keep it anyway for consistency.</p>\n<p>The <code>()</code> type means “void”. This special return type is only useful for IO functions called for their side effect.</p>\n<p>A longer example:</p>\n<pre><code>main = do\n    putStrLn &quot;What is your name?&quot;\n    name &lt;- getLine\n    putStrLn &quot;hello&quot; ++ name\n</code></pre>\n<p>This builds a chain of <code>IO</code> operations, and since they are assigned to the <code>main</code> function, they get executed.</p>\n<p>Comparing <code>IO</code> with <code>Maybe</code> shows the versatility of the monad pattern. For <code>Maybe</code>, the pattern is used to avoid repetitive code by moving conditional logic to the binding function. For <code>IO</code>, the pattern is used to ensure that all operations of the <code>IO</code> type are sequenced and that <code>IO</code> operations cannot &quot;leak&quot; to pure functions.</p>\n<p><strong>Summing up</strong></p>\n<p>In my subjective opinion, the monad pattern is only really worthwhile in a language which has some built-in support for the pattern. Otherwise it just leads to overly convoluted code. But Haskell (and some other languages) have some built-in support which hides the tedious parts, and then the pattern can be used for a variety of useful things. Like:</p>\n<ul>\n<li>Avoiding repetitive code (<code>Maybe</code>)</li>\n<li>Adding language features like mutable state or exceptions for delimited areas of the program.</li>\n<li>Isolating icky stuff from nice stuff (<code>IO</code>)</li>\n<li>Embedded domain-specific languages (<code>Parser</code>)</li>\n<li>Adding GOTO to the language.</li>\n</ul>\n'}, {'answer_id': 364072, 'author': 'jes5199', 'author_id': 13195, 'author_profile': 'https://Stackoverflow.com/users/13195', 'pm_score': 3, 'selected': False, 'text': "<p>I've been thinking of Monads in a different way, lately. I've been thinking of them as abstracting out <i>execution order</i> in a mathematical way, which makes new kinds of polymorphism possible.</p>\n\n<p>If you're using an imperative language, and you write some expressions in order, the code ALWAYS runs exactly in that order.</p>\n\n<p>And in the simple case, when you use a monad, it feels the same -- you define a list of expressions that happen in order. Except that, depending on which monad you use, your code might run in order (like in IO monad), in parallel over several items at once (like in the List monad), it might halt partway through (like in the Maybe monad), it might pause partway through to be resumed later (like in a Resumption monad), it might rewind and start from the beginning (like in a Transaction monad), or it might rewind partway to try other options (like in a Logic monad).</p>\n\n<p>And because monads are polymorphic, it's possible to run the same code in different monads, depending on your needs.</p>\n\n<p>Plus, in some cases, it's possible to combine monads together (with monad transformers) to get multiple features at the same time.</p>\n"}, {'answer_id': 476066, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>In addition to the excellent answers above, let me offer you a link to the following article (by Patrick Thomson) which explains monads by relating the concept to the JavaScript library <em>jQuery</em> (and its way of using "method chaining" to manipulate the DOM):\n<a href="http://importantshock.wordpress.com/2009/01/18/jquery-is-a-monad/" rel="noreferrer" title="jQuery is a Monad">jQuery is a Monad</a></p>\n\n<p>The <a href="http://docs.jquery.com/How_jQuery_Works" rel="noreferrer" title="How jQuery Works">jQuery documentation</a> itself doesn\'t refer to the term "monad" but talks about the "builder pattern" which is probably more familiar.  This doesn\'t change the fact that you have a proper monad there maybe without even realizing it.</p>\n'}, {'answer_id': 872157, 'author': 'cjs', 'author_id': 107294, 'author_profile': 'https://Stackoverflow.com/users/107294', 'pm_score': 3, 'selected': False, 'text': '<p>The two things that helped me best when learning about there were:</p>\n\n<p>Chapter 8, "Functional Parsers," from Graham Hutton\'s book <a href="http://www.cs.nott.ac.uk/~gmh/book.html" rel="noreferrer">Programming in Haskell</a>. This doesn\'t mention monads at all, actually, but if you can work through chapter and really understand everything in it, particularly how a sequence of bind operations is evaluated, you\'ll understand the internals of monads. Expect this to take several tries.</p>\n\n<p>The tutorial <a href="http://www.haskell.org/all_about_monads/html/index.html" rel="noreferrer">All About Monads</a>. This gives several good examples of their use, and I have to say that the analogy in Appendex I worked for me.</p>\n'}, {'answer_id': 885677, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>Monads are to control flow what abstract data types are to data.</p>\n\n<p>In other words, many developers are comfortable with the idea of Sets, Lists, Dictionaries (or Hashes, or Maps), and Trees. Within those data types there are many special cases (for instance InsertionOrderPreservingIdentityHashMap).</p>\n\n<p>However, when confronted with program "flow" many developers haven\'t been exposed to many more constructs than if, switch/case, do, while, goto (grr), and (maybe) closures.</p>\n\n<p>So, a monad is simply a control flow construct. A better phrase to replace monad would be \'control type\'.</p>\n\n<p>As such, a monad has slots for control logic, or statements, or functions - the equivalent in data structures would be to say that some data structures allow you to add data, and remove it.</p>\n\n<p>For example, the "if" monad:</p>\n\n<pre><code>if( clause ) then block\n</code></pre>\n\n<p>at its simplest has two slots - a clause, and a block. The <code>if</code> monad is usually built to evaluate the result of the clause, and if not false, evaluate the block. Many developers are not introduced to monads when they learn \'if\', and it just isn\'t necessary to understand monads to write effective logic.</p>\n\n<p>Monads can become more complicated, in the same way that data structures can become more complicated, but there are many broad categories of monad that may have similar semantics, but differing implementations and syntax.</p>\n\n<p>Of course, in the same way that data structures may be iterated over, or traversed, monads may be evaluated.</p>\n\n<p>Compilers may or may not have support for user-defined monads. Haskell certainly does. Ioke has some similar capabilities, although the term monad is not used in the language.</p>\n'}, {'answer_id': 943568, 'author': 'Benjol', 'author_id': 11410, 'author_profile': 'https://Stackoverflow.com/users/11410', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/users/40516/princess">Princess</a>\'s explanation of <a href="http://en.wikibooks.org/wiki/F_Sharp_Programming/Computation_Expressions" rel="nofollow noreferrer">F# Computation Expressions</a> helped me, though I still can\'t say I\'ve really understood.</p>\n\n<p><strong>EDIT</strong>: this series - explaining monads with javascript - is the one that \'tipped the balance\' for me. </p>\n\n<ul>\n<li><p><a href="http://blog.jcoglan.com/2011/03/05/translation-from-haskell-to-javascript-of-selected-portions-of-the-best-introduction-to-monads-ive-ever-read/" rel="nofollow noreferrer">http://blog.jcoglan.com/2011/03/05/translation-from-haskell-to-javascript-of-selected-portions-of-the-best-introduction-to-monads-ive-ever-read/</a></p></li>\n<li><p><a href="http://blog.jcoglan.com/2011/03/06/monad-syntax-for-javascript/" rel="nofollow noreferrer">http://blog.jcoglan.com/2011/03/06/monad-syntax-for-javascript/</a></p></li>\n<li><p><a href="http://blog.jcoglan.com/2011/03/11/promises-are-the-monad-of-asynchronous-programming/" rel="nofollow noreferrer">http://blog.jcoglan.com/2011/03/11/promises-are-the-monad-of-asynchronous-programming/</a></p></li>\n</ul>\n\n<p>I think that understanding monads is something that creeps up on you. In that sense, reading as many \'tutorials\' as you can is a good idea, but often strange stuff (unfamiliar language or syntax) prevents your brain from concentrating on the essential.</p>\n\n<p>Some things that I had difficulty understanding:</p>\n\n<ul>\n<li>Rules-based explanations never worked for me, because most practical examples actually require <em>more</em> than just return/bind. </li>\n<li>Also, calling them <em>rules</em> didn\'t help. It is more a case of "there are these <em>things</em> that have something in common, let\'s call the things \'monads\', and the bits in common \'rules\'".</li>\n<li>Return (<code>a -&gt; M&lt;a&gt;</code>) and Bind (<code>M&lt;a&gt; -&gt; (a -&gt; M&lt;b&gt;) -&gt; M&lt;b&gt;</code>) are great, but what I could never understand is HOW Bind could extract the <code>a</code> from <code>M&lt;a&gt;</code> in order to pass it into <code>a -&gt; M&lt;b&gt;</code>. I don\'t think I\'ve ever read anywhere (maybe it\'s obvious to everyone else), that the reverse of Return (<code>M&lt;a&gt; -&gt; a</code>) <em>has</em> to exist <em>inside</em> the monad, it just doesn\'t need to be exposed.</li>\n</ul>\n'}, {'answer_id': 1391707, 'author': 'Tony Morris', 'author_id': 132273, 'author_profile': 'https://Stackoverflow.com/users/132273', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://code.google.com/p/monad-tutorial/" rel="nofollow noreferrer">http://code.google.com/p/monad-tutorial/</a> is a work in progress to address exactly this question.</p>\n'}, {'answer_id': 3032186, 'author': 'Alex', 'author_id': 125940, 'author_profile': 'https://Stackoverflow.com/users/125940', 'pm_score': 3, 'selected': False, 'text': "<p>A monad is a way of combining computations together that share a common context.  It is like building a network of pipes.  When constructing the network, there is no data flowing through it.  But when I have finished piecing all the bits together with 'bind' and 'return' then I invoke something like <code>runMyMonad monad data</code> and the data flows through the pipes.</p>\n"}, {'answer_id': 4112577, 'author': 'Breton', 'author_id': 51101, 'author_profile': 'https://Stackoverflow.com/users/51101', 'pm_score': 6, 'selected': False, 'text': "<p>After much striving, I think I finally understand the monad. After rereading my own lengthy critique of the overwhelmingly top voted answer, I will offer this explanation.</p>\n<p>There are three questions that need to be answered to understand monads:</p>\n<ol>\n<li>Why do you need a monad?</li>\n<li>What is a monad?</li>\n<li>How is a monad implemented?</li>\n</ol>\n<p>As I noted in my original comments, too many monad explanations get caught up in question number 3, without, and before really adequately covering question 2, or question 1.</p>\n<p><strong>Why do you need a monad?</strong></p>\n<p>Pure functional languages like Haskell are different from imperative languages like C, or Java in that, a pure functional program is not necessarily executed in a specific order, one step at a time. A Haskell program is more akin to a mathematical function, in which you may solve the &quot;equation&quot; in any number of potential orders. This confers a number of benefits, among which is that it eliminates the possibility of certain kinds of bugs, particularly those relating to things like &quot;state&quot;.</p>\n<p>However, there are certain problems that are not so straightforward to solve with this style of programming. Some things, like console programming, and file i/o, need things to happen in a particular order, or need to maintain state. One way to deal with this problem is to create a kind of object that represents the state of a computation, and a series of functions that take a state object as input, and return a new modified state object.</p>\n<p>So let's create a hypothetical &quot;state&quot; value, that represents the state of a console screen. exactly how this value is constructed is not important, but let's say it's an array of byte length ascii characters that represents what is currently visible on the screen, and an array that represents the last line of input entered by the user, in pseudocode. We've defined some functions that take console state, modify it, and return a new console state.</p>\n<pre><code>consolestate MyConsole = new consolestate;\n</code></pre>\n<p>So to do console programming, but in a pure functional manner, you would need to nest a lot of function calls inside eachother.</p>\n<pre><code>consolestate FinalConsole = print(input(print(myconsole, &quot;Hello, what's your name?&quot;)),&quot;hello, %inputbuffer%!&quot;);\n</code></pre>\n<p>Programming in this way keeps the &quot;pure&quot; functional style, while forcing changes to the console to happen in a particular order. But, we'll probably want to do more than just a few operations at a time like in the above example. Nesting functions in that way will start to become ungainly. What we want, is code that does essentially the same thing as above, but is written a bit more like this:</p>\n<pre><code>consolestate FinalConsole = myconsole:\n                            print(&quot;Hello, what's your name?&quot;):\n                            input():\n                            print(&quot;hello, %inputbuffer%!&quot;);\n</code></pre>\n<p>This would indeed be a more convenient way to write it. How do we do that though?</p>\n<p><strong>What is a monad?</strong></p>\n<p>Once you have a type (such as <code>consolestate</code>) that you define along with a bunch of functions designed specifically to operate on that type, you can turn the whole package of these things into a &quot;monad&quot; by defining an operator like <code>:</code> (bind) that automatically feeds return values on its left, into function parameters on its right, and a <code>lift</code> operator that turns normal functions, into functions that work with that specific kind of bind operator.</p>\n<p><strong>How is a monad implemented?</strong></p>\n<p>See other answers, that seem quite free to jump into the details of that.</p>\n"}, {'answer_id': 4538741, 'author': 'thSoft', 'author_id': 90874, 'author_profile': 'https://Stackoverflow.com/users/90874', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://www.codecommit.com/blog/ruby/monads-are-not-metaphors" rel="noreferrer">Monads Are Not Metaphors</a>, but a practically useful abstraction emerging from a common pattern, as Daniel Spiewak explains.</p>\n'}, {'answer_id': 4688727, 'author': 'wisty', 'author_id': 207028, 'author_profile': 'https://Stackoverflow.com/users/207028', 'pm_score': 2, 'selected': False, 'text': "<p>Explaining monads seems to be like explaining control-flow statements. Imagine that a non-programmer asks you to explain them? </p>\n\n<p>You can give them an explanation involving the theory - Boolean Logic, register values, pointers, stacks, and frames. But that would be crazy.</p>\n\n<p>You could explain them in terms of the syntax. Basically all control-flow statements in C have curly brackets, and you can distinguish the condition and the conditional code by where they are relative to the brackets. That may be even crazier.</p>\n\n<p>Or you could also explain loops, if statements, routines, subroutines, and possibly co-routines.</p>\n\n<p>Monads can replace a fairly large number of programming techniques. There's a specific syntax in languages that support them, and some theories about them. </p>\n\n<p>They are also a way for functional programmers to use imperative code without actually admitting it, but that's not their only use. </p>\n"}, {'answer_id': 5984384, 'author': 'Tormod', 'author_id': 80577, 'author_profile': 'https://Stackoverflow.com/users/80577', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://mikehadlow.blogspot.com/2011/02/monads-in-c-8-video-of-my-ddd9-monad.html" rel="nofollow">http://mikehadlow.blogspot.com/2011/02/monads-in-c-8-video-of-my-ddd9-monad.html</a></p>\n\n<p>This is the video you are looking for. </p>\n\n<p>Demonstrating in C# what the problem is with composition and aligning the types, and then implementing them properly in C#. \nTowards the end he displays how the same C# code looks in F# and finally in Haskell. </p>\n'}, {'answer_id': 10245311, 'author': 'MathematicalOrchid', 'author_id': 1006010, 'author_profile': 'https://Stackoverflow.com/users/1006010', 'pm_score': 10, 'selected': False, 'text': '<p>Explaining "what is a monad" is a bit like saying "what is a number?" We use numbers all the time. But imagine you met someone who didn\'t know anything about numbers. How the <em>heck</em> would you explain what numbers are? And how would you even begin to describe why that might be useful?</p>\n\n<p>What is a monad? The short answer: It\'s a specific way of chaining operations together.</p>\n\n<p>In essence, you\'re writing execution steps and linking them together with the "bind function". (In Haskell, it\'s named <code>&gt;&gt;=</code>.) You can write the calls to the bind operator yourself, or you can use syntax sugar which makes the compiler insert those function calls for you. But either way, each step is separated by a call to this bind function.</p>\n\n<p>So the bind function is like a semicolon; it separates the steps in a process. The bind function\'s job is to take the output from the previous step, and feed it into the next step.</p>\n\n<p>That doesn\'t sound too hard, right? But there is <em>more than one</em> kind of monad. Why? How?</p>\n\n<p>Well, the bind function <em>can</em> just take the result from one step, and feed it to the next step. But if that\'s "all" the monad does... that actually isn\'t very useful. And that\'s important to understand: Every <em>useful</em> monad does something else <em>in addition</em> to just being a monad. Every <em>useful</em> monad has a "special power", which makes it unique.</p>\n\n<p>(A monad that does <em>nothing</em> special is called the "identity monad". Rather like the identity function, this sounds like an utterly pointless thing, yet turns out not to be... But that\'s another story&trade;.)</p>\n\n<p>Basically, each monad has its own implementation of the bind function. And you can write a bind function such that it does hoopy things between execution steps. For example:</p>\n\n<ul>\n<li><p>If each step returns a success/failure indicator, you can have bind execute the next step only if the previous one succeeded. In this way, a failing step aborts the whole sequence "automatically", without any conditional testing from you. (The <strong>Failure Monad</strong>.)</p></li>\n<li><p>Extending this idea, you can implement "exceptions". (The <strong>Error Monad</strong> or <strong>Exception Monad</strong>.) Because you\'re defining them yourself rather than it being a language feature, you can define how they work. (E.g., maybe you want to ignore the first two exceptions and only abort when a <em>third</em> exception is thrown.)</p></li>\n<li><p>You can make each step return <em>multiple results</em>, and have the bind function loop over them, feeding each one into the next step for you. In this way, you don\'t have to keep writing loops all over the place when dealing with multiple results. The bind function "automatically" does all that for you. (The <strong>List Monad</strong>.)</p></li>\n<li><p>As well as passing a "result" from one step to another, you can have the bind function <em>pass extra data</em> around as well. This data now doesn\'t show up in your source code, but you can still access it from anywhere, without having to manually pass it to every function. (The <strong>Reader Monad</strong>.)</p></li>\n<li><p>You can make it so that the "extra data" can be replaced. This allows you to <em>simulate destructive updates</em>, without actually doing destructive updates. (The <strong>State Monad</strong> and its cousin the <strong>Writer Monad</strong>.)</p></li>\n<li><p>Because you\'re only <em>simulating</em> destructive updates, you can trivially do things that would be impossible with <em>real</em> destructive updates. For example, you can <em>undo the last update</em>, or <em>revert to an older version</em>.</p></li>\n<li><p>You can make a monad where calculations can be <em>paused</em>, so you can pause your program, go in and tinker with internal state data, and then resume it.</p></li>\n<li><p>You can implement "continuations" as a monad. This allows you to <em>break people\'s minds!</em></p></li>\n</ul>\n\n<p>All of this and more is possible with monads. Of course, all of this is also perfectly possible <em>without</em> monads too. It\'s just drastically <em>easier</em> using monads.</p>\n'}, {'answer_id': 10567459, 'author': 'bartek', 'author_id': 365670, 'author_profile': 'https://Stackoverflow.com/users/365670', 'pm_score': 2, 'selected': False, 'text': "<p>I'm trying to understand monads as well. It's my version:</p>\n\n<p>Monads are about making abstractions about repetitive things. \nFirstly, monad itself is a typed interface (like an abstract generic class), that has two functions: bind and return that have defined signatures. And then, we can create concrete monads based on that abstract monad, of course with specific implementations of bind and return. Additionally, bind and return must fulfill a few invariants in order to make it possible to compose/chain concrete monads.</p>\n\n<p>Why create the monad concept while we have interfaces, types, classes and other tools to create abstractions? Because monads give more: they enforce rethinking problems in a way that enables to compose data without any boilerplate.</p>\n"}, {'answer_id': 15454893, 'author': 'Dmytro', 'author_id': 2012715, 'author_profile': 'https://Stackoverflow.com/users/2012715', 'pm_score': 3, 'selected': False, 'text': '<p>Monoid appears to be something that ensures that all operations defined on a Monoid and a supported type will always return a supported type inside the Monoid. Eg, Any number + Any number = A number, no errors. </p>\n\n<p>Whereas division accepts two fractionals, and returns a fractional, which defined division by zero as Infinity in haskell somewhy(which happens to be a fractional somewhy)... </p>\n\n<p>In any case, it appears Monads are just a way to ensure that your chain of operations behaves in a predictable way, and a function that claims to be Num -> Num, composed with another function of Num->Num called with x does not say, fire the missiles.</p>\n\n<p>On the other hand, if we have a function which does fire the missiles, we can compose it with other functions which also fire the missiles, because our intent is clear -- we want to fire the missiles -- but it won\'t try printing "Hello World" for some odd reason.</p>\n\n<p>In Haskell, main is of type IO (), or IO [()], the distiction is strange and I will not discuss it but here\'s what I think happens:</p>\n\n<p>If I have main, I want it to do a chain of actions, the reason I run the program is to produce an effect -- usually though IO. Thus I can chain IO operations together in main in order to -- do IO, nothing else.</p>\n\n<p>If I try to do something which does not "return IO", the program will complain that the chain does not flow, or basically "How does this relate to what we are trying to do -- an IO action", it appears to force the programmer to keep their train of thought, without straying off and thinking about firing the missiles, while creating algorithms for sorting -- which does not flow.</p>\n\n<p>Basically, Monads appear to be a tip to the compiler that "hey, you know this function that returns a number here, it doesn\'t actually always work, it can sometimes produce a Number, and sometimes Nothing at all, just keep this in mind". Knowing this, if you try to assert a monadic action, the monadic action may act as a compile time exception saying "hey, this isn\'t actually a number, this CAN be a number, but you can\'t assume this, do something to ensure that the flow is acceptable." which prevents unpredictable program behavior -- to a fair extent.</p>\n\n<p>It appears monads are not about purity, nor control, but about maintaining an identity of a category on which all behavior is predictable and defined, or does not compile. You cannot do nothing when you are expected to do something, and you cannot do something if you are expected to do nothing (visible).</p>\n\n<p>The biggest reason I could think of for Monads is -- go look at Procedural/OOP code, and you will notice that you do not know where the program starts, nor ends, all you see is a lot of jumping and a lot of math,magic,and missiles. You will not be able to maintain it, and if you can, you will spend quite a lot of time wrapping your mind around the whole program before you can understand any part of it, because modularity in this context is based on interdependant "sections" of code, where code is optimized to be as related as possible for promise of efficiency/inter-relation. Monads are very concrete, and well defined by definition, and ensure that the flow of program is possible to analyze, and isolate parts which are hard to analyze -- as they themselves are monads. A monad appears to be a "comprehensible unit which is predictable upon its full understanding" -- If you understand "Maybe" monad, there\'s no possible way it will do anything except be "Maybe", which appears trivial, but in most non monadic code, a simple function "helloworld" can fire the missiles, do nothing, or destroy the universe or even distort time -- we have no idea nor have any guarantees that IT IS WHAT IT IS. A monad GUARANTEES that IT IS WHAT IT IS. which is very powerful.</p>\n\n<p>All things in "real world" appear to be monads, in the sense that it is bound by definite observable laws preventing confusion. This does not mean we have to mimic all the operations of this object to create classes, instead we can simply say "a square is a square", nothing but a square, not even a rectangle nor a circle, and "a square has area of the length of one of it\'s existing dimensions multiplied by itself. No matter what square you have, if it\'s a square in 2D space, it\'s area absolutely cannot be anything but its length squared, it\'s almost trivial to prove. This is very powerful because we do not need to make assertions to make sure that our world is the way it is, we just use implications of reality to prevent our programs from falling off track.</p>\n\n<p>Im pretty much guaranteed to be wrong but I think this could help somebody out there, so hopefully it helps somebody.</p>\n'}, {'answer_id': 15733300, 'author': 'snow', 'author_id': 1065942, 'author_profile': 'https://Stackoverflow.com/users/1065942', 'pm_score': 1, 'selected': False, 'text': "<p>Mathematial thinking</p>\n\n<p>For short: An Algebraic Structure for Combining Computations.</p>\n\n<p><code>return data</code>: create a computation who just simply generate a data in monad world.</p>\n\n<p><code>(return data) &gt;&gt;= (return func)</code>: The second parameter accept first parameter as a data generator and create a new computations which concatenate them.</p>\n\n<p>You can think that <strong>(>>=)</strong> and <strong>return</strong> won't do any computation itself. They just simply combine and create computations.</p>\n\n<p>Any monad computation will be compute if and only if <strong>main</strong> trigs it.</p>\n"}, {'answer_id': 20189228, 'author': 'hawkeye', 'author_id': 15441, 'author_profile': 'https://Stackoverflow.com/users/15441', 'pm_score': 1, 'selected': False, 'text': '<p>In the Coursera <a href="https://accounts.coursera.org/signin?course_id=971465&amp;r=https://class.coursera.org/reactive-001/class&amp;user_action=class&amp;topic_name=Principles%20of%20Reactive%20Programming" rel="nofollow">"Principles of Reactive Programming"</a> training - Erik Meier describes them as:</p>\n\n<pre><code>"Monads are return types that guide you through the happy path." -Erik Meijer\n</code></pre>\n'}, {'answer_id': 20707480, 'author': 'samthebest', 'author_id': 1586965, 'author_profile': 'https://Stackoverflow.com/users/1586965', 'pm_score': 3, 'selected': False, 'text': '<p>In the context of Scala you will find the following to be the simplest definition. Basically flatMap (or bind) is \'associative\' and there exists an identity.</p>\n\n<pre class="lang-scala prettyprint-override"><code>trait M[+A] {\n  def flatMap[B](f: A =&gt; M[B]): M[B] // AKA bind\n\n  // Pseudo Meta Code\n  def isValidMonad: Boolean = {\n    // for every parameter the following holds\n    def isAssociativeOn[X, Y, Z](x: M[X], f: X =&gt; M[Y], g: Y =&gt; M[Z]): Boolean =\n      x.flatMap(f).flatMap(g) == x.flatMap(f(_).flatMap(g))\n\n    // for every parameter X and x, there exists an id\n    // such that the following holds\n    def isAnIdentity[X](x: M[X], id: X =&gt; M[X]): Boolean =\n      x.flatMap(id) == x\n  }\n}\n</code></pre>\n\n<p>E.g.</p>\n\n<pre class="lang-scala prettyprint-override"><code>// These could be any functions\nval f: Int =&gt; Option[String] = number =&gt; if (number == 7) Some("hello") else None\nval g: String =&gt; Option[Double] = string =&gt; Some(3.14)\n\n// Observe these are identical. Since Option is a Monad \n// they will always be identical no matter what the functions are\nscala&gt; Some(7).flatMap(f).flatMap(g)\nres211: Option[Double] = Some(3.14)\n\nscala&gt; Some(7).flatMap(f(_).flatMap(g))\nres212: Option[Double] = Some(3.14)\n\n\n// As Option is a Monad, there exists an identity:\nval id: Int =&gt; Option[Int] = x =&gt; Some(x)\n\n// Observe these are identical\nscala&gt; Some(7).flatMap(id)\nres213: Option[Int] = Some(7)\n\nscala&gt; Some(7)\nres214: Some[Int] = Some(7)\n</code></pre>\n\n<p><strong>NOTE</strong> Strictly speaking the definition of a <a href="http://en.wikipedia.org/wiki/Monad_%28functional_programming%29" rel="nofollow">Monad in functional programming</a> is not the same as the definition of a <a href="http://en.wikipedia.org/wiki/Monad_%28category_theory%29" rel="nofollow">Monad in Category Theory</a>, which is defined in turns of <code>map</code> and <code>flatten</code>.  Though they are kind of equivalent under certain mappings.  This presentations is very good: <a href="http://www.slideshare.net/samthemonad/monad-presentation-scala-as-a-category" rel="nofollow">http://www.slideshare.net/samthemonad/monad-presentation-scala-as-a-category</a></p>\n'}, {'answer_id': 22078646, 'author': 'chenj7', 'author_id': 1003697, 'author_profile': 'https://Stackoverflow.com/users/1003697', 'pm_score': 3, 'selected': False, 'text': '<p>I am still new to monads, but I thought I would share a link I found that felt really good to read (WITH PICTURES!!):\n<a href="http://www.matusiak.eu/numerodix/blog/2012/3/11/monads-for-the-layman/" rel="nofollow">http://www.matusiak.eu/numerodix/blog/2012/3/11/monads-for-the-layman/</a>\n(no affiliation)</p>\n\n<p>Basically, the warm and fuzzy concept that I got from the article was the concept that monads are basically adapters that allow disparate functions to work in a composable fashion, i.e. be able to string up multiple functions and mix and match them without worrying about inconsistent return types and such. So the BIND function is in charge of keeping apples with apples and oranges with oranges when we\'re trying to make these adapters. And the LIFT function is in charge of taking "lower level" functions and "upgrading" them to work with BIND functions and be composable as well.</p>\n\n<p>I hope I got it right, and more importantly, hope that the article has a valid view on monads. If nothing else, this article helped whet my appetite for learning more about monads.</p>\n'}, {'answer_id': 25195169, 'author': 'George', 'author_id': 1612190, 'author_profile': 'https://Stackoverflow.com/users/1612190', 'pm_score': 6, 'selected': False, 'text': '<p>After giving an answer to this question a few years ago, I believe I can improve and simplify that response with...</p>\n<p>A monad is a function composition technique that externalizes treatment for some input scenarios using a composing function, <code>bind</code>, to pre-process input during composition.</p>\n<p>In normal composition, the function, <code>compose (&gt;&gt;)</code>, is use to apply the composed function to the result of its predecessor in sequence. Importantly, the function being composed is required to handle all scenarios of its input.</p>\n<p><code>(x -&gt; y) &gt;&gt; (y -&gt; z)</code></p>\n<p>This design can be improved by restructuring the input so that relevant states are more easily interrogated. So, instead of simply <code>y</code> the value can become <code>Mb</code> such as, for instance, <code>(is_OK, b)</code> if <code>y</code> included a notion of validity.</p>\n<p>For example, when the input is only possibly a number, instead of returning a string which can dutifully contain a number or not, you could restructure the type into a <code>bool</code> indicating the presence of a valid number and a number in tuple such as, <code>bool * float</code>. The composed functions would now no longer need to parse an input string to determine whether a number exists but could merely inspect the <code>bool</code> portion of a tuple.</p>\n<p><code>(Ma -&gt; Mb) &gt;&gt; (Mb -&gt; Mc)</code></p>\n<p>Here, again, composition occurs naturally with <code>compose</code> and so each function must handle all scenarios of its input individually, though doing so is now much easier.</p>\n<p>However, what if we could externalize the effort of interrogation for those times where handling a scenario is routine. For example, what if our program does nothing when the input is not OK as in when <code>is_OK</code> is <code>false</code>. If that were done then composed functions would not need to handle that scenario themselves, dramatically simplifying their code and effecting another level of reuse.</p>\n<p>To achieve this externalization we could use a function, <code>bind (&gt;&gt;=)</code>, to perform the <code>composition</code> instead of <code>compose</code>. As such, instead of simply transferring values from the output of one function to the input of another <code>Bind</code> would inspect the <code>M</code> portion of <code>Ma</code> and decide whether and how to apply the composed function to the <code>a</code>. Of course, the function <code>bind</code> would be defined specifically for our particular <code>M</code> so as to be able to inspect its structure and perform whatever type of application we want. Nonetheless, the <code>a</code> can be anything since <code>bind</code> merely passes the <code>a</code> uninspected to the the composed function when it determines application necessary. Additionally, the composed functions themselves no longer need to deal with the <code>M</code> portion of the input structure either, simplifying them. Hence...</p>\n<p><code>(a -&gt; Mb) &gt;&gt;= (b -&gt; Mc)</code> or more succinctly <code>Mb &gt;&gt;= (b -&gt; Mc)</code></p>\n<p>In short, a monad externalizes and thereby provides standard behaviour around the treatment of certain input scenarios once the input becomes designed to sufficiently expose them. This design is a <code>shell and content</code> model where the shell contains data relevant to the application of the composed function and is interrogated by and remains only available to the <code>bind</code> function.</p>\n<p>Therefore, a monad is three things:</p>\n<ol>\n<li>an <code>M</code> shell for holding monad relevant information,</li>\n<li>a <code>bind</code> function implemented to make use of this shell information in its application of the composed functions to the content value(s) it finds within the shell, and</li>\n<li>composable functions of the form, <code>a -&gt; Mb</code>, producing results that include monadic management data.</li>\n</ol>\n<p>Generally speaking, the input to a function is far more restrictive than its output which may include such things as error conditions; hence, the <code>Mb</code> result structure is generally very useful. For instance, the division operator does not return a number when the divisor is <code>0</code>.</p>\n<p>Additionally, <code>monad</code>s may include wrap functions that wrap values, <code>a</code>, into the monadic type, <code>Ma</code>, and general functions, <code>a -&gt; b</code>, into monadic functions, <code>a -&gt; Mb</code>, by wrapping their results after application. Of course, like <code>bind</code>, such wrap functions are specific to <code>M</code>. An example:</p>\n<pre><code>let return a = [a]\nlet lift f a = return (f a)\n</code></pre>\n<p>The design of the <code>bind</code> function presumes immutable data structures and pure functions others things get complex and guarantees cannot be made. As such, there are monadic laws:</p>\n<p>Given...</p>\n<pre><code>M_ \nreturn = (a -&gt; Ma)\nf = (a -&gt; Mb)\ng = (b -&gt; Mc)\n</code></pre>\n<p>Then...</p>\n<pre><code>Left Identity  : (return a) &gt;&gt;= f === f a\nRight Identity : Ma &gt;&gt;= return    === Ma\nAssociative    : Ma &gt;&gt;= (f &gt;&gt;= g) === Ma &gt;&gt;= ((fun x -&gt; f x) &gt;&gt;= g)\n</code></pre>\n<p><code>Associativity</code> means that <code>bind</code> preserves the order of evaluation regardless of when <code>bind</code> is applied. That is, in the definition of <code>Associativity</code> above, the force early evaluation of the parenthesized <code>binding</code> of <code>f</code> and <code>g</code> will only result in a function that expects <code>Ma</code> in order to complete the <code>bind</code>. Hence the evaluation of <code>Ma</code> must be determined before its value can become applied to <code>f</code> and that result in turn applied to <code>g</code>.</p>\n'}, {'answer_id': 26530696, 'author': 'Eugene Yokota', 'author_id': 3827, 'author_profile': 'https://Stackoverflow.com/users/3827', 'pm_score': 2, 'selected': False, 'text': '<p>What the world needs is another monad blog post, but I think this is useful in identifying existing monads in the wild.</p>\n\n<ul>\n<li><a href="http://eed3si9n.com/monads-are-fractals" rel="nofollow noreferrer">monads are fractals</a></li>\n</ul>\n\n<blockquote>\n  <p><img src="https://i.stack.imgur.com/N2lGd.png" alt="Sierpinski triangle"></p>\n  \n  <p>The above is a fractal called Sierpinski triangle, the only fractal I can remember to draw. Fractals are self-similar structure like the above triangle, in which the parts are similar to the whole (in this case exactly half the scale as parent triangle).</p>\n  \n  <p>Monads are fractals. Given a monadic data structure, its values can be composed to form another value of the data structure. This is why it\'s useful to programming, and this is why it occurrs in many situations.</p>\n</blockquote>\n'}, {'answer_id': 28311329, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>A very simple answer is:</p>\n\n<p>Monads are an <em>abstraction</em> that provide an interface for encapsulating values, for computing new encapsulated values, and for unwrapping the encapsulated value.</p>\n\n<p>What\'s convenient about them in practice is that <em>they provide a uniform interface for creating data types that model state while not being stateful</em>.</p>\n\n<p>It\'s important to understand that a Monad is an <em>abstraction</em>, that is, an abstract interface for dealing with a certain kind of data structure. That interface is then used to build data types that have monadic behavior.</p>\n\n<p>You can find a very good and practical introduction in <em><a href="http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html" rel="nofollow">Monads in Ruby, Part 1: Introduction</a></em>.</p>\n'}, {'answer_id': 28924364, 'author': 'Jordan', 'author_id': 972499, 'author_profile': 'https://Stackoverflow.com/users/972499', 'pm_score': 3, 'selected': False, 'text': '<p>This answer begins with a motivating example, works through the example, derives an example of a monad, and formally defines "monad".</p>\n\n<p>Consider these three functions in pseudocode:</p>\n\n<pre><code>f(&lt;x, messages&gt;) := &lt;x, messages "called f. "&gt;\ng(&lt;x, messages&gt;) := &lt;x, messages "called g. "&gt;\nwrap(x)          := &lt;x, ""&gt;\n</code></pre>\n\n<p><code>f</code> takes an ordered pair of the form <code>&lt;x, messages&gt;</code> and returns an ordered pair. It leaves the first item untouched and appends <code>"called f. "</code> to the second item. Same with <code>g</code>.</p>\n\n<p>You can compose these functions and get your original value, along with a string that shows which order the functions were called in:</p>\n\n<pre><code>  f(g(wrap(x)))\n= f(g(&lt;x, ""&gt;))\n= f(&lt;x, "called g. "&gt;)\n= &lt;x, "called g. called f. "&gt;\n</code></pre>\n\n<p>You dislike the fact that <code>f</code> and <code>g</code> are responsible for appending their own log messages to the previous logging information. (Just imagine for the sake of argument that instead of appending strings, <code>f</code> and <code>g</code> must perform complicated logic on the second item of the pair. It would be a pain to repeat that complicated logic in two -- or more -- different functions.)</p>\n\n<p>You prefer to write simpler functions:</p>\n\n<pre><code>f(x)    := &lt;x, "called f. "&gt;\ng(x)    := &lt;x, "called g. "&gt;\nwrap(x) := &lt;x, ""&gt;\n</code></pre>\n\n<p>But look at what happens when you compose them:</p>\n\n<pre><code>  f(g(wrap(x)))\n= f(g(&lt;x, ""&gt;))\n= f(&lt;&lt;x, ""&gt;, "called g. "&gt;)\n= &lt;&lt;&lt;x, ""&gt;, "called g. "&gt;, "called f. "&gt;\n</code></pre>\n\n<p>The problem is that <em>passing</em> a pair into a function does not give you what you want. But what if you could <em>feed</em> a pair into a function:</p>\n\n<pre><code>  feed(f, feed(g, wrap(x)))\n= feed(f, feed(g, &lt;x, ""&gt;))\n= feed(f, &lt;x, "called g. "&gt;)\n= &lt;x, "called g. called f. "&gt;\n</code></pre>\n\n<p>Read <code>feed(f, m)</code> as "feed <code>m</code> into <code>f</code>". To <em>feed</em> a pair <code>&lt;x, messages&gt;</code> into a function <code>f</code> is to <em>pass</em> <code>x</code> into <code>f</code>, get <code>&lt;y, message&gt;</code> out of <code>f</code>, and return <code>&lt;y, messages message&gt;</code>.</p>\n\n<pre><code>feed(f, &lt;x, messages&gt;) := let &lt;y, message&gt; = f(x)\n                          in  &lt;y, messages message&gt;\n</code></pre>\n\n<p>Notice what happens when you do three things with your functions:</p>\n\n<p>First: if you wrap a value and then <em>feed</em> the resulting pair into a function:</p>\n\n<pre><code>  feed(f, wrap(x))\n= feed(f, &lt;x, ""&gt;)\n= let &lt;y, message&gt; = f(x)\n  in  &lt;y, "" message&gt;\n= let &lt;y, message&gt; = &lt;x, "called f. "&gt;\n  in  &lt;y, "" message&gt;\n= &lt;x, "" "called f. "&gt;\n= &lt;x, "called f. "&gt;\n= f(x)\n</code></pre>\n\n<p>That is the same as <em>passing</em> the value into the function.</p>\n\n<p>Second: if you feed a pair into <code>wrap</code>:</p>\n\n<pre><code>  feed(wrap, &lt;x, messages&gt;)\n= let &lt;y, message&gt; = wrap(x)\n  in  &lt;y, messages message&gt;\n= let &lt;y, message&gt; = &lt;x, ""&gt;\n  in  &lt;y, messages message&gt;\n= &lt;x, messages ""&gt;\n= &lt;x, messages&gt;\n</code></pre>\n\n<p>That does not change the pair.</p>\n\n<p>Third: if you define a function that takes <code>x</code> and feeds <code>g(x)</code> into <code>f</code>:</p>\n\n<pre><code>h(x) := feed(f, g(x))\n</code></pre>\n\n<p>and feed a pair into it:</p>\n\n<pre><code>  feed(h, &lt;x, messages&gt;)\n= let &lt;y, message&gt; = h(x)\n  in  &lt;y, messages message&gt;\n= let &lt;y, message&gt; = feed(f, g(x))\n  in  &lt;y, messages message&gt;\n= let &lt;y, message&gt; = feed(f, &lt;x, "called g. "&gt;)\n  in  &lt;y, messages message&gt;\n= let &lt;y, message&gt; = let &lt;z, msg&gt; = f(x)\n                     in  &lt;z, "called g. " msg&gt;\n  in &lt;y, messages message&gt;\n= let &lt;y, message&gt; = let &lt;z, msg&gt; = &lt;x, "called f. "&gt;\n                     in  &lt;z, "called g. " msg&gt;\n  in &lt;y, messages message&gt;\n= let &lt;y, message&gt; = &lt;x, "called g. " "called f. "&gt;\n  in &lt;y, messages message&gt;\n= &lt;x, messages "called g. " "called f. "&gt;\n= feed(f, &lt;x, messages "called g. "&gt;)\n= feed(f, feed(g, &lt;x, messages&gt;))\n</code></pre>\n\n<p>That is the same as feeding the pair into <code>g</code> and feeding the resulting pair into <code>f</code>.</p>\n\n<p>You have most of a monad. Now you just need to know about the data types in your program.</p>\n\n<p>What type of value is <code>&lt;x, "called f. "&gt;</code>? Well, that depends on what type of value <code>x</code> is. If <code>x</code> is of type <code>t</code>, then your pair is a value of type "pair of <code>t</code> and string". Call that type <code>M t</code>.</p>\n\n<p><code>M</code> is a type constructor: <code>M</code> alone does not refer to a type, but <code>M _</code> refers to a type once you fill in the blank with a type. An <code>M int</code> is a pair of an int and a string. An <code>M string</code> is a pair of a string and a string. Etc.</p>\n\n<p><strong>Congratulations, you have created a monad!</strong></p>\n\n<p>Formally, your monad is the tuple <code>&lt;M, feed, wrap&gt;</code>.</p>\n\n<p>A monad is a tuple <code>&lt;M, feed, wrap&gt;</code> where:</p>\n\n<ul>\n<li><code>M</code> is a type constructor.</li>\n<li><code>feed</code> takes a (function that takes a <code>t</code> and returns an <code>M u</code>) and an <code>M t</code> and returns an <code>M u</code>.</li>\n<li><code>wrap</code> takes a <code>v</code> and returns an <code>M v</code>.</li>\n</ul>\n\n<p><code>t</code>, <code>u</code>, and <code>v</code> are any three types that may or may not be the same. A monad satisfies the three properties you proved for your specific monad:</p>\n\n<ul>\n<li><p><em>Feeding</em> a wrapped <code>t</code> into a function is the same as <em>passing</em> the unwrapped <code>t</code> into the function.</p>\n\n<p>Formally: <code>feed(f, wrap(x)) = f(x)</code></p></li>\n<li><p>Feeding an <code>M t</code> into <code>wrap</code> does nothing to the <code>M t</code>.</p>\n\n<p>Formally: <code>feed(wrap, m) = m</code></p></li>\n<li><p>Feeding an <code>M t</code> (call it <code>m</code>) into a function that</p>\n\n<ul>\n<li>passes the <code>t</code> into <code>g</code></li>\n<li>gets an <code>M u</code> (call it <code>n</code>) from <code>g</code></li>\n<li>feeds <code>n</code> into <code>f</code></li>\n</ul>\n\n<p>is the same as</p>\n\n<ul>\n<li>feeding <code>m</code> into <code>g</code></li>\n<li>getting <code>n</code> from <code>g</code></li>\n<li>feeding <code>n</code> into <code>f</code></li>\n</ul>\n\n<p>Formally: <code>feed(h, m) = feed(f, feed(g, m))</code> where <code>h(x) := feed(f, g(x))</code></p></li>\n</ul>\n\n<p>Typically, <code>feed</code> is called <code>bind</code> (AKA <code>&gt;&gt;=</code> in Haskell) and <code>wrap</code> is called <code>return</code>.</p>\n'}, {'answer_id': 33609881, 'author': 'Mateusz Charytoniuk', 'author_id': 1011156, 'author_profile': 'https://Stackoverflow.com/users/1011156', 'pm_score': 3, 'selected': False, 'text': '<p>In practice, monad is a custom implementation of function composition operator that takes care of side effects and incompatible input and return values (for chaining).</p>\n'}, {'answer_id': 34162489, 'author': 'theoski', 'author_id': 598807, 'author_profile': 'https://Stackoverflow.com/users/598807', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Essentially</strong>, and <strong>Practically</strong>, monads allow callback nesting<br>\n(with a mutually-recursively-threaded state (pardon the hyphens))<br>\n(in a composable (or decomposable) fashion)<br>\n(with type safety (sometimes (depending on the language)))<br>\n)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))</p>\n\n<p>E.G. this is <strong>NOT</strong> a monad:  </p>\n\n<pre class="lang-js prettyprint-override"><code>//JavaScript is \'Practical\'\nvar getAllThree = \n         bind(getFirst, function(first){  \n  return bind(getSecond,function(second){  \n  return bind(getThird, function(third){  \n    var fancyResult = // And now make do fancy \n                      // with first, second,\n                      // and third \n    return RETURN(fancyResult);\n  });});});  \n</code></pre>\n\n<p>But monads enable such code.<br>\nThe monad is actually the set of types for:<br>\n<code>{bind,RETURN,maybe others I don\'t know...}</code>.<br>\nWhich is <em>essentially</em> inessential, and <em>practically</em> impractical.  </p>\n\n<p>So now I can use it:  </p>\n\n<pre class="lang-js prettyprint-override"><code>var fancyResultReferenceOutsideOfMonad =  \n  getAllThree(someKindOfInputAcceptableToOurGetFunctionsButProbablyAString);  \n\n//Ignore this please, throwing away types, yay JavaScript:\n//  RETURN = K\n//  bind = \\getterFn,cb -&gt; \n//    \\in -&gt; let(result,newState) = getterFn(in) in cb(result)(newState)\n</code></pre>\n\n<p>Or Break it up:</p>\n\n<pre class="lang-js prettyprint-override"><code>var getFirstTwo = \n           bind(getFirst, function(first){  \n    return bind(getSecond,function(second){  \n      var fancyResult2 = // And now make do fancy \n                         // with first and second\n      return RETURN(fancyResult2);\n    });})\n  , getAllThree = \n           bind(getFirstTwo, function(fancyResult2){  \n    return bind(getThird,    function(third){  \n      var fancyResult3 = // And now make do fancy \n                         // with fancyResult2,\n                         // and third \n      return RETURN(fancyResult3);\n    });});\n</code></pre>\n\n<p>Or ignore certain results:</p>\n\n<pre class="lang-js prettyprint-override"><code>var getFirstTwo = \n           bind(getFirst, function(first){  \n    return bind(getSecond,function(second){  \n      var fancyResult2 = // And now make do fancy \n                         // with first and second\n      return RETURN(fancyResult2);\n    });})\n  , getAllThree = \n           bind(getFirstTwo, function(____dontCare____NotGonnaUse____){  \n    return bind(getThird,    function(three){  \n      var fancyResult3 = // And now make do fancy \n                         // with `three` only!\n      return RETURN(fancyResult3);\n    });});\n</code></pre>\n\n<p>Or simplify a trivial case from:</p>\n\n<pre class="lang-js prettyprint-override"><code>var getFirstTwo = \n           bind(getFirst, function(first){  \n    return bind(getSecond,function(second){  \n      var fancyResult2 = // And now make do fancy \n                         // with first and second\n      return RETURN(fancyResult2);\n    });})\n  , getAllThree = \n           bind(getFirstTwo, function(_){  \n    return bind(getThird,    function(three){  \n      return RETURN(three);\n    });});\n</code></pre>\n\n<p>To (using <a href="https://wiki.haskell.org/Monad_laws" rel="nofollow">"Right Identity"</a>):</p>\n\n<pre class="lang-js prettyprint-override"><code>var getFirstTwo = \n           bind(getFirst, function(first){  \n    return bind(getSecond,function(second){  \n      var fancyResult2 = // And now make do fancy \n                         // with first and second\n      return RETURN(fancyResult2);\n    });})\n  , getAllThree = \n           bind(getFirstTwo, function(_){  \n    return getThird;\n    });\n</code></pre>\n\n<p>Or jam them back together:</p>\n\n<pre class="lang-js prettyprint-override"><code>var getAllThree = \n           bind(getFirst, function(first_dontCareNow){  \n    return bind(getSecond,function(second_dontCareNow){  \n    return getThird;\n    });});\n</code></pre>\n\n<p>The practicality of these abilities doesn\'t really emerge,<br>\nor become clear until you try to solve really messy problems<br>\nlike parsing, or module/ajax/resource loading.</p>\n\n<p>Can you imagine thousands of lines of indexOf/subString logic?<br>\nWhat if frequent parsing steps were contained in little functions?<br>\nFunctions like <code>chars</code>, <code>spaces</code>,<code>upperChars</code>, or <code>digits</code>?<br>\nAnd what if those functions gave you the result in a callback,<br>\nwithout having to mess with Regex groups, and arguments.slice?<br>\nAnd what if their composition/decomposition was well understood?<br>\nSuch that you could build big parsers from the bottom up?  </p>\n\n<p>So the ability to manage nested callback scopes <em>is incredibly practical</em>,<br>\nespecially when working with monadic parser combinator libraries.<br>\n(that is to say, in my experience)</p>\n\n<p>DON\'T GET HUNG UP ON:<br>\n- CATEGORY-THEORY<br>\n- MAYBE-MONADS<br>\n- MONAD LAWS<br>\n- HASKELL<br>\n- !!!!  </p>\n'}, {'answer_id': 37225431, 'author': 'Simon', 'author_id': 742404, 'author_profile': 'https://Stackoverflow.com/users/742404', 'pm_score': -1, 'selected': False, 'text': "<h2>Explanation</h2>\n\n<p>It's quite simple, when explained in C#/Java terms:</p>\n\n<ol>\n<li><p>A monad is a function that takes arguments and returns a special type. </p></li>\n<li><p>The special type that this monad returns is <strong>also</strong> called monad. (A monad is a combination of #1 and #2)</p></li>\n<li><p>There's some syntactic sugar to make calling this function and conversion of types easier.</p></li>\n</ol>\n\n<h2>Example</h2>\n\n<p>A monad is useful to make the life of the functional programmer easier. The typical example: The <code>Maybe</code> monad takes two parameters, a value and a function. It returns <code>null</code> if the passed value is <code>null</code>. Otherwise it evaluates the function. If we needed a special return type, we would call this return type <code>Maybe</code> as well. A very crude implementation would look like this:</p>\n\n<pre><code>object Maybe(object value, Func&lt;object,object&gt; function)\n{\n    if(value==null)\n        return null;\n\n    return function(value);\n}\n</code></pre>\n\n<p>This is spectacularly useless in C# because this language lacks the required syntactic sugar to make monads useful. But monads allow you to write more concise code in functional programming languages.</p>\n\n<p>Oftentimes programmers call monads in chains, like so:</p>\n\n<pre><code>var x = Maybe(x, x2 =&gt; Maybe(y, y2 =&gt; Add(x2, y2)));\n</code></pre>\n\n<p>In this example the <code>Add</code> method would only be called if <code>x</code> and <code>y</code> are both non-<code>null</code>, otherwise <code>null</code> will be returned.</p>\n\n<h2>Answer</h2>\n\n<p>To answer the original question: A monad is a function AND a type. Like an implementation of a special <code>interface</code>.</p>\n"}, {'answer_id': 42147263, 'author': 'trevor cook', 'author_id': 5198575, 'author_profile': 'https://Stackoverflow.com/users/5198575', 'pm_score': 2, 'selected': False, 'text': '<p>Let the below "<code>{| a |m}</code>" represent some piece of monadic data. A data type which advertises an <code>a</code>:</p>\n\n<pre><code>        (I got an a!)\n          /        \n    {| a |m}\n</code></pre>\n\n<p>Function, <code>f</code>, knows how to create a monad, if only it had an <code>a</code>:</p>\n\n<pre><code>       (Hi f! What should I be?)\n                      /\n(You?. Oh, you\'ll be /\n that data there.)  /\n /                 /  (I got a b.)\n|    --------------      |\n|  /                     |\nf a                      |\n  |--later-&gt;       {| b |m}\n</code></pre>\n\n<p>Here we see function, <code>f</code>, tries to evaluate a monad but gets rebuked.</p>\n\n<pre><code>(Hmm, how do I get that a?)\n o       (Get lost buddy.\no         Wrong type.)\no       /\nf {| a |m}\n</code></pre>\n\n<p>Funtion, <code>f</code>, finds a way to extract the <code>a</code> by using <code>&gt;&gt;=</code>.</p>\n\n<pre><code>        (Muaahaha. How you \n         like me now!?)       \n    (Better.)      \\\n        |     (Give me that a.)\n(Fine, well ok.)    |\n         \\          |\n   {| a |m}   &gt;&gt;=   f\n</code></pre>\n\n<p>Little does <code>f</code> know, the monad and <code>&gt;&gt;=</code> are in collusion.</p>\n\n<pre><code>            (Yah got an a for me?)       \n(Yeah, but hey    | \n listen. I got    |\n something to     |\n tell you first   |\n ...)   \\        /\n         |      /\n   {| a |m}   &gt;&gt;=   f\n</code></pre>\n\n<p>But what do they actually talk about? Well, that depends on the monad. Talking solely in the abstract has limited use; you have to have some experience with particular monads to flesh out the understanding. </p>\n\n<p>For instance, the data type Maybe</p>\n\n<pre><code> data Maybe a = Nothing | Just a\n</code></pre>\n\n<p>has a monad instance which will acts like the following...</p>\n\n<p>Wherein, if the case is <code>Just a</code></p>\n\n<pre><code>            (Yah what is it?)       \n(... hm? Oh,      |\nforget about it.  |\nHey a, yr up.)    | \n            \\     |\n(Evaluation  \\    |\ntime already? \\   |\nHows my hair?) |  |\n      |       /   |\n      |  (It\'s    |\n      |  fine.)  /\n      |   /     /    \n   {| a |m}   &gt;&gt;=   f\n</code></pre>\n\n<p>But for the case of <code>Nothing</code></p>\n\n<pre><code>        (Yah what is it?)       \n(... There      |\nis no a. )      |\n  |        (No a?)\n(No a.)         |\n  |        (Ok, I\'ll deal\n  |         with this.)\n   \\            |\n    \\      (Hey f, get lost.) \n     \\          |   ( Where\'s my a? \n      \\         |     I evaluate a)\n       \\    (Not any more  |\n        \\    you don\'t.    |\n         |   We\'re returning\n         |   Nothing.)   /\n         |      |       /\n         |      |      /\n         |      |     /\n   {| a |m}   &gt;&gt;=   f      (I got a b.)\n                    |  (This is   \\\n                    |   such a     \\\n                    |   sham.) o o  \\\n                    |               o|\n                    |--later-&gt; {| b |m}\n</code></pre>\n\n<p>So the Maybe monad lets a computation continue if it actually contains the <code>a</code> it advertises, but aborts the computation if it doesn\'t. The result, however is still a piece of monadic data, though not the output of <code>f</code>. For this reason, the Maybe monad is used to represent the context of failure. </p>\n\n<p>Different monads behave differently. Lists are other types of data with monadic instances. They behave like the following:</p>\n\n<pre><code>(Ok, here\'s your a. Well, its\n a bunch of them, actually.)\n  |\n  |    (Thanks, no problem. Ok\n  |     f, here you go, an a.)\n  |       |\n  |       |        (Thank\'s. See\n  |       |         you later.)\n  |  (Whoa. Hold up f,      |\n  |   I got another         |\n  |   a for you.)           |\n  |       |      (What? No, sorry.\n  |       |       Can\'t do it. I \n  |       |       have my hands full\n  |       |       with all these "b" \n  |       |       I just made.) \n  |  (I\'ll hold those,      |\n  |   you take this, and   /\n  |   come back for more  /\n  |   when you\'re done   / \n  |   and we\'ll do it   / \n  |   again.)          /\n   \\      |  ( Uhhh. All right.)\n    \\     |       /    \n     \\    \\      /\n{| a |m}   &gt;&gt;=  f  \n</code></pre>\n\n<p>In this case, the function knew how to make a list from it\'s input, but didn\'t know what to do with extra input and extra lists. The bind <code>&gt;&gt;=</code>, helped <code>f</code> out by combining the multiple outputs. I include this example to show that while <code>&gt;&gt;=</code> is responsible for extracting <code>a</code>, it also has access to the eventual bound output of <code>f</code>. Indeed, it will never extract any <code>a</code> unless it knows the eventual output has the same type of context.</p>\n\n<p>There are other monads which are used to represent different contexts. Here\'s some characterizations of a few more. The <code>IO</code> monad doesn\'t actually have an <code>a</code>, but it knows a guy and will get that <code>a</code> for you. The <code>State st</code> monad has a secret stash of <code>st</code> that it will pass to <code>f</code> under the table, even though <code>f</code> just came asking for an <code>a</code>. The <code>Reader r</code> monad is similar to <code>State st</code>, although it only lets <code>f</code> look at <code>r</code>.</p>\n\n<p>The point in all this is that any type of data which is declared itself to be a Monad is declaring some sort of context around extracting a value from the monad. The big gain from all this? Well, its easy enough to couch a calculation with some sort of context. It can get messy, however, when stringing together multiple context laden calculations. The monad operations take care of resolving the interactions of context so that the programmer doesn\'t have to. </p>\n\n<p>Note, that use of the <code>&gt;&gt;=</code> eases a mess by by taking some of the autonomy away from <code>f</code>. That is, in the above case of <code>Nothing</code> for instance, <code>f</code> no longer gets to decide what to do in the case of <code>Nothing</code>; it\'s encoded in <code>&gt;&gt;=</code>. This is the trade off. If it was necessary for <code>f</code> to decide what to do in the case of <code>Nothing</code>, then <code>f</code> should have been a function from <code>Maybe a</code> to <code>Maybe b</code>. In this case, <code>Maybe</code> being a monad is irrelevant.</p>\n\n<p>Note, however, that sometimes a data type does not export it\'s constructors (looking at you IO), and if we want to work with the advertised value we have little choice but to work with it\'s monadic interface.</p>\n'}, {'answer_id': 43565185, 'author': 'icc97', 'author_id': 327074, 'author_profile': 'https://Stackoverflow.com/users/327074', 'pm_score': 2, 'selected': False, 'text': '<p>Another attempt at explaining monads, using just Python lists and the <code>map</code> function. I fully accept this isn\'t a full explanation, but I hope it gets at the core concepts.</p>\n\n<p>I got the basis of this from the <a href="https://www.youtube.com/watch?v=9QveBbn7t_c&amp;list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84&amp;index=12" rel="nofollow noreferrer">funfunfunction video on Monads</a> and the Learn You A Haskell chapter <a href="http://learnyouahaskell.com/for-a-few-monads-more" rel="nofollow noreferrer">\'For a Few Monads More\'</a>. I <em>highly</em> recommend watching the funfunfunction video.</p>\n\n<p>At it\'s very simplest, Monads are objects that have a <code>map</code> and <code>flatMap</code> functions (<code>bind</code> in Haskell). <strong>There are some extra required properties</strong>, but these are the core ones.</p>\n\n<p><code>flatMap</code> \'flattens\' the output of map, for lists this just concatenates the values of the list e.g. </p>\n\n<pre><code>concat([[1], [4], [9]]) = [1, 4, 9]\n</code></pre>\n\n<p>So in Python we can very basically implement a Monad with just these two functions:</p>\n\n\n\n<pre class="lang-python prettyprint-override"><code>def flatMap(func, lst):\n    return concat(map(func, lst))\n\ndef concat(lst):\n    return sum(lst, [])\n</code></pre>\n\n<p><code>func</code> is any function that takes a value and returns a list e.g.</p>\n\n<pre class="lang-python prettyprint-override"><code>lambda x: [x*x]\n</code></pre>\n\n<h2>Explanation</h2>\n\n<p>For clarity I created the <code>concat</code> function in Python via a <a href="https://stackoverflow.com/a/952946/327074">simple function</a>, which sums the lists i.e. <code>[] + [1] + [4] + [9] = [1, 4, 9]</code> (Haskell has a native <code>concat</code> method).</p>\n\n<p>I\'m assuming you know what the <code>map</code> function is e.g.:</p>\n\n<pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; list(map(lambda x: [x*x], [1,2,3]))\n[[1], [4], [9]]\n</code></pre>\n\n<p>Flattening is the key concept of Monads and for each object which is a Monad this flattening allows you to get at the value that is wrapped in the Monad.</p>\n\n<p>Now we can call:</p>\n\n<pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; flatMap(lambda x: [x*x], [1,2,3])\n[1, 4, 9]\n</code></pre>\n\n<p>This lambda is taking a value x and putting it into a list. A monad works with any function that goes from a value to a type of the monad, so a list in this case.</p>\n\n<p><strong>That\'s your monad defined</strong>. </p>\n\n<p>I think the question of why they\'re useful has been answered in other questions. </p>\n\n<h2>More explanation</h2>\n\n<p>Other examples that aren\'t lists are JavaScript Promises, which have the <code>then</code> method and JavaScript Streams which have a <code>flatMap</code> method.</p>\n\n<p>So Promises and Streams use a slightly different function which flattens out a Stream or a Promise and returns the value from within.</p>\n\n<p>The <a href="http://learnyouahaskell.com/a-fistful-of-monads#the-list-monad" rel="nofollow noreferrer">Haskell list monad</a> has the following definition:</p>\n\n<pre class="lang-python prettyprint-override"><code>instance Monad [] where  \n    return x = [x]  \n    xs &gt;&gt;= f = concat (map f xs)  \n    fail _ = [] \n</code></pre>\n\n<p>i.e. there are three functions <code>return</code> (not to be confused with return in most other languages), <code>&gt;&gt;=</code> (the <code>flatMap</code>) and <code>fail</code>.</p>\n\n<p>Hopefully you can see the similarity between:</p>\n\n<pre class="lang-python prettyprint-override"><code>xs &gt;&gt;= f = concat (map f xs)\n</code></pre>\n\n<p>and:</p>\n\n<pre class="lang-python prettyprint-override"><code>def flatMap(f, xs):\n    return concat(map(f, xs))\n</code></pre>\n'}, {'answer_id': 45480927, 'author': 'Jonas', 'author_id': 3741667, 'author_profile': 'https://Stackoverflow.com/users/3741667', 'pm_score': 3, 'selected': False, 'text': '<p>I will try to explain <code>Monad</code> in the context of Haskell.</p>\n\n<p>In functional programming, function composition is important. It allows our program to consist of small, easy-to-read functions.</p>\n\n<p>Let\'s say we have two functions: <code>g :: Int -&gt; String</code> and <code>f :: String -&gt; Bool</code>.</p>\n\n<p>We can do <code>(f . g) x</code>, which is just the same as <code>f (g x)</code>, where <code>x</code> is an <code>Int</code> value.</p>\n\n<p>When doing composition/applying the result of one function to another, having the types match up is important. In the above case, the type of the result returned by <code>g</code> must be the same as the type accepted by <code>f</code>.</p>\n\n<p>But sometimes values are in contexts, and this makes it a bit less easy to line up types. (Having values in contexts is very useful. For example, the <code>Maybe Int</code> type represents an <code>Int</code> value that may not be there, the <code>IO String</code> type represents a <code>String</code> value that is there as a result of performing some side effects.)</p>\n\n<p>Let\'s say we now have <code>g1 :: Int -&gt; Maybe String</code> and <code>f1 :: String -&gt; Maybe Bool</code>. <code>g1</code> and <code>f1</code> are very similar to <code>g</code> and <code>f</code> respectively.</p>\n\n<p>We can\'t do <code>(f1 . g1) x</code> or <code>f1 (g1 x)</code>, where <code>x</code> is an <code>Int</code> value. The type of the result returned by <code>g1</code> is not what <code>f1</code> expects.</p>\n\n<p>We could compose <code>f</code> and <code>g</code> with the <code>.</code> operator, but now we can\'t compose <code>f1</code> and <code>g1</code> with <code>.</code>. The problem is that we can\'t straightforwardly pass a value in a context to a function that expects a value that is not in a context.</p>\n\n<p>Wouldn\'t it be nice if we introduce an operator to compose <code>g1</code> and <code>f1</code>, such that we can write <code>(f1 OPERATOR g1) x</code>? <code>g1</code> returns a value in a context. The value will be taken out of context and applied to <code>f1</code>. And yes, we have such an operator. It\'s <code>&lt;=&lt;</code>.</p>\n\n<p>We also have the <code>&gt;&gt;=</code> operator that does for us the exact same thing, though in a slightly different syntax.</p>\n\n<p>We write: <code>g1 x &gt;&gt;= f1</code>. <code>g1 x</code> is a <code>Maybe Int</code> value. The <code>&gt;&gt;=</code> operator helps take that <code>Int</code> value out of the "perhaps-not-there" context, and apply it to <code>f1</code>. The result of <code>f1</code>, which is a <code>Maybe Bool</code>, will be the result of the entire <code>&gt;&gt;=</code> operation.</p>\n\n<p>And finally, why is <code>Monad</code> useful? Because <code>Monad</code> is the type class that defines the <code>&gt;&gt;=</code> operator, very much the same as the <code>Eq</code> type class that defines the <code>==</code> and <code>/=</code> operators.</p>\n\n<p>To conclude, the <code>Monad</code> type class defines the <code>&gt;&gt;=</code> operator that allows us to pass values in a context (we call these monadic values) to functions that don\'t expect values in a context. The context will be taken care of.</p>\n\n<p>If there is one thing to remember here, it is that <strong><code>Monad</code>s allow function composition that involves values in contexts</strong>. </p>\n'}, {'answer_id': 49086086, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '\n\n<h2>tl;dr</h2>\n\n<pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE InstanceSigs #-}\n\nnewtype Id t = Id t\n\ninstance Monad Id where\n   return :: t -&gt; Id t\n   return = Id\n\n   (=&lt;&lt;) :: (a -&gt; Id b) -&gt; Id a -&gt; Id b\n   f =&lt;&lt; (Id x) = f x\n</code></pre>\n\n<h2>Prologue</h2>\n\n<p>The application operator <code>$</code> of functions</p>\n\n<pre class="lang-hs prettyprint-override"><code>forall a b. a -&gt; b\n</code></pre>\n\n<p>is canonically defined</p>\n\n<pre class="lang-hs prettyprint-override"><code>($) :: (a -&gt; b) -&gt; a -&gt; b\nf $ x = f x\n\ninfixr 0 $\n</code></pre>\n\n<p>in terms of Haskell-primitive function application <code>f x</code> (<code>infixl 10</code>). </p>\n\n<p>Composition <code>.</code> is defined in terms of <code>$</code> as</p>\n\n<pre class="lang-hs prettyprint-override"><code>(.) :: (b -&gt; c) -&gt; (a -&gt; b) -&gt; (a -&gt; c)\nf . g = \\ x -&gt; f $ g x\n\ninfixr 9 .\n</code></pre>\n\n<p>and satisfies the equivalences <code>forall f g h.</code></p>\n\n<pre class="lang-hs prettyprint-override"><code>     f . id  =  f            :: c -&gt; d   Right identity\n     id . g  =  g            :: b -&gt; c   Left identity\n(f . g) . h  =  f . (g . h)  :: a -&gt; d   Associativity\n</code></pre>\n\n<p><code>.</code> is associative, and <code>id</code> is its right and left identity.</p>\n\n<h2>The Kleisli triple</h2>\n\n<p>In programming, a monad is a functor type constructor with an instance of the monad type class. There are several equivalent variants of definition and implementation, each carrying slightly different intuitions about the monad abstraction.</p>\n\n<p>A functor is a type constructor <code>f</code> of kind <code>* -&gt; *</code> with an instance of the functor type class.</p>\n\n<pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE KindSignatures #-}\n\nclass Functor (f :: * -&gt; *) where\n   map :: (a -&gt; b) -&gt; (f a -&gt; f b)\n</code></pre>\n\n<p>In addition to following statically enforced type protocol, instances of the functor type class must obey the algebraic <em>functor laws</em> <code>forall f g.</code></p>\n\n<pre class="lang-hs prettyprint-override"><code>       map id  =  id           :: f t -&gt; f t   Identity\nmap f . map g  =  map (f . g)  :: f a -&gt; f c   Composition / short cut fusion\n</code></pre>\n\n<p>Functor <em>computations</em> have the type</p>\n\n<pre class="lang-hs prettyprint-override"><code>forall f t. Functor f =&gt; f t\n</code></pre>\n\n<p>A computation <code>c r</code> consists in <em>results</em> <code>r</code> within <em>context</em> <code>c</code>.</p>\n\n<p>Unary monadic functions or <em>Kleisli arrows</em> have the type</p>\n\n<pre class="lang-hs prettyprint-override"><code>forall m a b. Functor m =&gt; a -&gt; m b\n</code></pre>\n\n<p>Kleisi arrows are functions that take one argument <code>a</code> and return a monadic computation <code>m b</code>.</p>\n\n<p>Monads are canonically defined in terms of the <em>Kleisli triple</em> <code>forall m. Functor m =&gt;</code></p>\n\n<pre class="lang-hs prettyprint-override"><code>(m, return, (=&lt;&lt;))\n</code></pre>\n\n<p>implemented as the type class</p>\n\n<pre class="lang-hs prettyprint-override"><code>class Functor m =&gt; Monad m where\n   return :: t -&gt; m t\n   (=&lt;&lt;)  :: (a -&gt; m b) -&gt; m a -&gt; m b\n\ninfixr 1 =&lt;&lt;\n</code></pre>\n\n<p>The <em>Kleisli identity</em> <code>return</code> is a Kleisli arrow that promotes a value <code>t</code> into monadic context <code>m</code>. <em>Extension</em> or <em>Kleisli application</em> <code>=&lt;&lt;</code> applies a Kleisli arrow <code>a -&gt; m b</code> to results of a computation <code>m a</code>.</p>\n\n<p><em>Kleisli composition</em> <code>&lt;=&lt;</code> is defined in terms of extension as</p>\n\n<pre class="lang-hs prettyprint-override"><code>(&lt;=&lt;) :: Monad m =&gt; (b -&gt; m c) -&gt; (a -&gt; m b) -&gt; (a -&gt; m c)\nf &lt;=&lt; g = \\ x -&gt; f =&lt;&lt; g x\n\ninfixr 1 &lt;=&lt;\n</code></pre>\n\n<p><code>&lt;=&lt;</code> composes two Kleisli arrows, applying the left arrow to results of the right arrow’s application.</p>\n\n<p>Instances of the monad type class must obey the <em>monad laws</em>, most elegantly stated in terms of Kleisli composition: <code>forall f g h.</code></p>\n\n<pre class="lang-hs prettyprint-override"><code>   f &lt;=&lt; return  =  f                :: c -&gt; m d   Right identity\n   return &lt;=&lt; g  =  g                :: b -&gt; m c   Left identity\n(f &lt;=&lt; g) &lt;=&lt; h  =  f &lt;=&lt; (g &lt;=&lt; h)  :: a -&gt; m d   Associativity\n</code></pre>\n\n<p><code>&lt;=&lt;</code> is associative, and <code>return</code> is its right and left identity.</p>\n\n<h2>Identity</h2>\n\n<p>The identity type</p>\n\n<pre class="lang-hs prettyprint-override"><code>type Id t = t\n</code></pre>\n\n<p>is the identity function on types</p>\n\n<pre class="lang-hs prettyprint-override"><code>Id :: * -&gt; *\n</code></pre>\n\n<p>Interpreted as a functor,</p>\n\n<pre class="lang-hs prettyprint-override"><code>   return :: t -&gt; Id t\n=      id :: t -&gt;    t\n\n    (=&lt;&lt;) :: (a -&gt; Id b) -&gt; Id a -&gt; Id b\n=     ($) :: (a -&gt;    b) -&gt;    a -&gt;    b\n\n    (&lt;=&lt;) :: (b -&gt; Id c) -&gt; (a -&gt; Id b) -&gt; (a -&gt; Id c)\n=     (.) :: (b -&gt;    c) -&gt; (a -&gt;    b) -&gt; (a -&gt;    c)\n</code></pre>\n\n<p>In canonical Haskell, the identity monad is defined</p>\n\n<pre class="lang-hs prettyprint-override"><code>newtype Id t = Id t\n\ninstance Functor Id where\n   map :: (a -&gt; b) -&gt; Id a -&gt; Id b\n   map f (Id x) = Id (f x)\n\ninstance Monad Id where\n   return :: t -&gt; Id t\n   return = Id\n\n   (=&lt;&lt;) :: (a -&gt; Id b) -&gt; Id a -&gt; Id b\n   f =&lt;&lt; (Id x) = f x\n</code></pre>\n\n<h2>Option</h2>\n\n<p>An option type</p>\n\n<pre class="lang-hs prettyprint-override"><code>data Maybe t = Nothing | Just t\n</code></pre>\n\n<p>encodes computation <code>Maybe t</code> that not necessarily yields a result <code>t</code>, computation that may “fail”. The option monad is defined</p>\n\n<pre class="lang-hs prettyprint-override"><code>instance Functor Maybe where\n   map :: (a -&gt; b) -&gt; (Maybe a -&gt; Maybe b)\n   map f (Just x) = Just (f x)\n   map _ Nothing  = Nothing\n\ninstance Monad Maybe where\n   return :: t -&gt; Maybe t\n   return = Just\n\n   (=&lt;&lt;) :: (a -&gt; Maybe b) -&gt; Maybe a -&gt; Maybe b\n   f =&lt;&lt; (Just x) = f x\n   _ =&lt;&lt; Nothing  = Nothing\n</code></pre>\n\n<p><code>a -&gt; Maybe b</code> is applied to a result only if <code>Maybe a</code> yields a result.</p>\n\n<pre class="lang-hs prettyprint-override"><code>newtype Nat = Nat Int\n</code></pre>\n\n<p>The natural numbers can be encoded as those integers greater than or equal to zero.</p>\n\n<pre class="lang-hs prettyprint-override"><code>toNat :: Int -&gt; Maybe Nat\ntoNat i | i &gt;= 0    = Just (Nat i)\n        | otherwise = Nothing\n</code></pre>\n\n<p>The natural numbers are not closed under subtraction.</p>\n\n<pre class="lang-hs prettyprint-override"><code>(-?) :: Nat -&gt; Nat -&gt; Maybe Nat\n(Nat n) -? (Nat m) = toNat (n - m)\n\ninfixl 6 -?\n</code></pre>\n\n<p>The option monad covers a basic form of exception handling.</p>\n\n<pre class="lang-hs prettyprint-override"><code>(-? 20) &lt;=&lt; toNat :: Int -&gt; Maybe Nat\n</code></pre>\n\n<h2>List</h2>\n\n<p>The list monad, over the list type</p>\n\n<pre class="lang-hs prettyprint-override"><code>data [] t = [] | t : [t]\n\ninfixr 5 :\n</code></pre>\n\n<p>and its additive monoid operation “append”</p>\n\n<pre class="lang-hs prettyprint-override"><code>(++) :: [t] -&gt; [t] -&gt; [t]\n(x : xs) ++ ys = x : xs ++ ys\n[]       ++ ys = ys\n\ninfixr 5 ++\n</code></pre>\n\n<p>encodes <em>nonlinear</em> computation <code>[t]</code> yielding a natural amount <code>0, 1, ...</code> of results <code>t</code>.</p>\n\n<pre class="lang-hs prettyprint-override"><code>instance Functor [] where\n   map :: (a -&gt; b) -&gt; ([a] -&gt; [b])\n   map f (x : xs) = f x : map f xs\n   map _ []       = []\n\ninstance Monad [] where\n   return :: t -&gt; [t]\n   return = (: [])\n\n   (=&lt;&lt;) :: (a -&gt; [b]) -&gt; [a] -&gt; [b]\n   f =&lt;&lt; (x : xs) = f x ++ (f =&lt;&lt; xs)\n   _ =&lt;&lt; []       = []\n</code></pre>\n\n<p>Extension <code>=&lt;&lt;</code> concatenates <code>++</code> all lists <code>[b]</code> resulting from applications <code>f x</code> of a Kleisli arrow <code>a -&gt; [b]</code> to elements of <code>[a]</code> into a single result list <code>[b]</code>.</p>\n\n<p>Let the proper divisors of a positive integer <code>n</code> be</p>\n\n<pre class="lang-hs prettyprint-override"><code>divisors :: Integral t =&gt; t -&gt; [t]\ndivisors n = filter (`divides` n) [2 .. n - 1]\n\ndivides :: Integral t =&gt; t -&gt; t -&gt; Bool\n(`divides` n) = (== 0) . (n `rem`)\n</code></pre>\n\n<p>then</p>\n\n<pre class="lang-hs prettyprint-override"><code>forall n.  let { f = f &lt;=&lt; divisors } in f n   =   []\n</code></pre>\n\n<p>In defining the monad type class, instead of extension <code>=&lt;&lt;</code>, the Haskell standard uses its flip, the <em>bind</em> operator <code>&gt;&gt;=</code>.</p>\n\n<pre class="lang-hs prettyprint-override"><code>class Applicative m =&gt; Monad m where\n   (&gt;&gt;=) :: forall a b. m a -&gt; (a -&gt; m b) -&gt; m b\n\n   (&gt;&gt;) :: forall a b. m a -&gt; m b -&gt; m b\n   m &gt;&gt; k = m &gt;&gt;= \\ _ -&gt; k\n   {-# INLINE (&gt;&gt;) #-}\n\n   return :: a -&gt; m a\n   return = pure\n</code></pre>\n\n<p>For simplicity\'s sake, this explanation uses the type class hierarchy</p>\n\n<pre class="lang-hs prettyprint-override"><code>class              Functor f\nclass Functor m =&gt; Monad m\n</code></pre>\n\n<p>In Haskell, the current standard hierarchy is</p>\n\n<pre class="lang-hs prettyprint-override"><code>class                  Functor f\nclass Functor p     =&gt; Applicative p\nclass Applicative m =&gt; Monad m\n</code></pre>\n\n<p>because not only is every monad a functor, but every applicative is a functor and every monad is an applicative, too.</p>\n\n<p>Using the list monad, the imperative pseudocode</p>\n\n<pre class="lang-hs prettyprint-override"><code>for a in (1, ..., 10)\n   for b in (1, ..., 10)\n      p &lt;- a * b\n      if even(p)\n         yield p\n</code></pre>\n\n<p>roughly translates to the <em>do block</em>,</p>\n\n<pre class="lang-hs prettyprint-override"><code>do a &lt;- [1 .. 10]\n   b &lt;- [1 .. 10]\n   let p = a * b\n   guard (even p)\n   return p\n</code></pre>\n\n<p>the equivalent <em>monad comprehension</em>,</p>\n\n<pre class="lang-hs prettyprint-override"><code>[ p | a &lt;- [1 .. 10], b &lt;- [1 .. 10], let p = a * b, even p ]\n</code></pre>\n\n<p>and the expression</p>\n\n<pre class="lang-hs prettyprint-override"><code>[1 .. 10] &gt;&gt;= (\\ a -&gt;\n   [1 .. 10] &gt;&gt;= (\\ b -&gt;\n      let p = a * b in\n         guard (even p) &gt;&gt;       -- [ () | even p ] &gt;&gt;\n            return p\n      )\n   )\n</code></pre>\n\n<p>Do notation and monad comprehensions are syntactic sugar for nested bind expressions. The bind operator is used for local name binding of monadic results.</p>\n\n<pre class="lang-hs prettyprint-override"><code>let x = v in e    =   (\\ x -&gt; e)  $  v   =   v  &amp;  (\\ x -&gt; e)\ndo { r &lt;- m; c }  =   (\\ r -&gt; c) =&lt;&lt; m   =   m &gt;&gt;= (\\ r -&gt; c)\n</code></pre>\n\n<p>where</p>\n\n<pre class="lang-hs prettyprint-override"><code>(&amp;) :: a -&gt; (a -&gt; b) -&gt; b\n(&amp;) = flip ($)\n\ninfixl 0 &amp;\n</code></pre>\n\n<p>The guard function is defined</p>\n\n<pre class="lang-hs prettyprint-override"><code>guard :: Additive m =&gt; Bool -&gt; m ()\nguard True  = return ()\nguard False = fail\n</code></pre>\n\n<p>where the <em>unit type</em> or “empty tuple”</p>\n\n<pre class="lang-hs prettyprint-override"><code>data () = ()\n</code></pre>\n\n<p><em>Additive monads</em> that support <em>choice</em> and <em>failure</em> can be abstracted over using a type class</p>\n\n<pre class="lang-hs prettyprint-override"><code>class Monad m =&gt; Additive m where\n   fail  :: m t\n   (&lt;|&gt;) :: m t -&gt; m t -&gt; m t\n\ninfixl 3 &lt;|&gt;\n\ninstance Additive Maybe where\n   fail = Nothing\n\n   Nothing &lt;|&gt; m = m\n   m       &lt;|&gt; _ = m\n\ninstance Additive [] where\n   fail = []\n   (&lt;|&gt;) = (++)\n</code></pre>\n\n<p>where <code>fail</code> and <code>&lt;|&gt;</code> form a monoid <code>forall k l m.</code></p>\n\n<pre class="lang-hs prettyprint-override"><code>     k &lt;|&gt; fail  =  k\n     fail &lt;|&gt; l  =  l\n(k &lt;|&gt; l) &lt;|&gt; m  =  k &lt;|&gt; (l &lt;|&gt; m)\n</code></pre>\n\n<p>and <code>fail</code> is the absorbing/annihilating zero element of additive monads</p>\n\n<pre class="lang-hs prettyprint-override"><code>_ =&lt;&lt; fail  =  fail\n</code></pre>\n\n<p>If in</p>\n\n<pre class="lang-hs prettyprint-override"><code>guard (even p) &gt;&gt; return p\n</code></pre>\n\n<p><code>even p</code> is true, then the guard produces <code>[()]</code>, and, by the definition of <code>&gt;&gt;</code>, the local constant function</p>\n\n<pre class="lang-hs prettyprint-override"><code>\\ _ -&gt; return p\n</code></pre>\n\n<p>is applied to the result <code>()</code>. If false, then the guard produces the list monad’s <code>fail</code> ( <code>[]</code> ), which yields no result for a Kleisli arrow to be applied <code>&gt;&gt;</code> to, so this <code>p</code> is skipped over.</p>\n\n<h2>State</h2>\n\n<p>Infamously, monads are used to encode stateful computation.</p>\n\n<p>A <em>state processor</em> is a function</p>\n\n<pre class="lang-hs prettyprint-override"><code>forall st t. st -&gt; (t, st)\n</code></pre>\n\n<p>that transitions a state <code>st</code> and yields a result <code>t</code>. The <em>state</em> <code>st</code> can be anything. Nothing, flag, count, array, handle, machine, world.</p>\n\n<p>The type of state processors is usually called</p>\n\n<pre class="lang-hs prettyprint-override"><code>type State st t = st -&gt; (t, st)\n</code></pre>\n\n<p>The state processor monad is the kinded <code>* -&gt; *</code> functor <code>State st</code>. Kleisli arrows of the state processor monad are functions</p>\n\n<pre class="lang-hs prettyprint-override"><code>forall st a b. a -&gt; (State st) b\n</code></pre>\n\n<p>In canonical Haskell, the lazy version of the state processor monad is defined</p>\n\n<pre class="lang-hs prettyprint-override"><code>newtype State st t = State { stateProc :: st -&gt; (t, st) }\n\ninstance Functor (State st) where\n   map :: (a -&gt; b) -&gt; ((State st) a -&gt; (State st) b)\n   map f (State p) = State $ \\ s0 -&gt; let (x, s1) = p s0\n                                     in  (f x, s1)\n\ninstance Monad (State st) where\n   return :: t -&gt; (State st) t\n   return x = State $ \\ s -&gt; (x, s)\n\n   (=&lt;&lt;) :: (a -&gt; (State st) b) -&gt; (State st) a -&gt; (State st) b\n   f =&lt;&lt; (State p) = State $ \\ s0 -&gt; let (x, s1) = p s0\n                                     in  stateProc (f x) s1\n</code></pre>\n\n<p>A state processor is run by supplying an initial state:</p>\n\n<pre class="lang-hs prettyprint-override"><code>run :: State st t -&gt; st -&gt; (t, st)\nrun = stateProc\n\neval :: State st t -&gt; st -&gt; t\neval = fst . run\n\nexec :: State st t -&gt; st -&gt; st\nexec = snd . run\n</code></pre>\n\n<p>State access is provided by primitives <code>get</code> and <code>put</code>, methods of abstraction over <em>stateful</em> monads:</p>\n\n<pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}\n\nclass Monad m =&gt; Stateful m st |\xa0m -&gt; st where\n   get :: m st\n   put :: st -&gt; m ()\n</code></pre>\n\n<p><code>m -&gt; st</code> declares a <em>functional dependency</em> of the state type <code>st</code> on the monad <code>m</code>; that a <code>State t</code>, for example, will determine the state type to be <code>t</code> uniquely.</p>\n\n<pre class="lang-hs prettyprint-override"><code>instance Stateful (State st) st where\n   get :: State st st\n   get = State $ \\ s -&gt; (s, s)\n\n   put :: st -&gt; State st ()\n   put s = State $ \\ _ -&gt; ((), s)\n</code></pre>\n\n<p>with the unit type used analogously to <code>void</code> in C.</p>\n\n<pre class="lang-hs prettyprint-override"><code>modify :: Stateful m st =&gt; (st -&gt; st) -&gt; m ()\nmodify f = do\n   s &lt;- get\n   put (f s)\n\ngets :: Stateful m st =&gt; (st -&gt; t) -&gt; m t\ngets f = do\n   s &lt;- get\n   return (f s)\n</code></pre>\n\n<p><code>gets</code> is often used with record field accessors.</p>\n\n<p>The state monad equivalent of the variable threading</p>\n\n<pre class="lang-hs prettyprint-override"><code>let s0 = 34\n    s1 = (+ 1) s0\n    n = (* 12) s1\n    s2 = (+ 7) s1\nin  (show n, s2)\n</code></pre>\n\n<p>where <code>s0 :: Int</code>, is the equally referentially transparent, but infinitely more elegant and practical</p>\n\n<pre class="lang-hs prettyprint-override"><code>(flip run) 34\n   (do\n      modify (+ 1)\n      n &lt;- gets (* 12)\n      modify (+ 7)\n      return (show n)\n   )\n</code></pre>\n\n<p><code>modify (+ 1)</code> is a computation of type <code>State Int ()</code>, except for its <em>effect</em> equivalent to <code>return ()</code>.</p>\n\n<pre class="lang-hs prettyprint-override"><code>(flip run) 34\n   (modify (+ 1) &gt;&gt;\n      gets (* 12) &gt;&gt;= (\\ n -&gt;\n         modify (+ 7) &gt;&gt;\n            return (show n)\n      )\n   )\n</code></pre>\n\n<p>The monad law of associativity can be written in terms of <code>&gt;&gt;=</code> <code>forall m f g.</code></p>\n\n<pre class="lang-hs prettyprint-override"><code>(m &gt;&gt;= f) &gt;&gt;= g  =  m &gt;&gt;= (\\ x -&gt; f x &gt;&gt;= g)\n</code></pre>\n\n<p>or</p>\n\n<pre class="lang-hs prettyprint-override"><code>do {                 do {                   do {\n   r1 &lt;- do {           x &lt;- m;                r0 &lt;- m;\n      r0 &lt;- m;   =      do {            =      r1 &lt;- f r0;\n      f r0                 r1 &lt;- f x;          g r1\n   };                      g r1             }\n   g r1                 }\n}                    }\n</code></pre>\n\n<p>Like in expression-oriented programming (e.g. Rust), the last statement of a block represents its yield. The bind operator is sometimes called a “programmable semicolon”.</p>\n\n<p>Iteration control structure primitives from structured imperative programming are emulated monadically</p>\n\n<pre class="lang-hs prettyprint-override"><code>for :: Monad m =&gt; (a -&gt; m b) -&gt; [a] -&gt; m ()\nfor f = foldr ((&gt;&gt;) . f) (return ())\n\nwhile :: Monad m =&gt; m Bool -&gt; m t -&gt; m ()\nwhile c m = do\n   b &lt;- c\n   if b then m &gt;&gt; while c m\n        else return ()\n\nforever :: Monad m =&gt; m t\nforever m = m &gt;&gt; forever m\n</code></pre>\n\n<h2>Input/Output</h2>\n\n<pre class="lang-hs prettyprint-override"><code>data World\n</code></pre>\n\n<p>The I/O world state processor monad is a reconciliation of pure Haskell and the real world, of functional denotative and imperative operational semantics. A close analogue of the actual strict implementation:</p>\n\n<pre class="lang-hs prettyprint-override"><code>type IO t = World -&gt; (t, World)\n</code></pre>\n\n<p>Interaction is facilitated by impure primitives</p>\n\n<pre class="lang-hs prettyprint-override"><code>getChar         :: IO Char\nputChar         :: Char -&gt; IO ()\nreadFile        :: FilePath -&gt; IO String\nwriteFile       :: FilePath -&gt; String -&gt; IO ()\nhSetBuffering   :: Handle -&gt; BufferMode -&gt; IO ()\nhTell           :: Handle -&gt; IO Integer\n. . .              . . .\n</code></pre>\n\n<p>The impurity of code that uses <code>IO</code> primitives is permanently protocolized by the type system. Because purity is awesome, what happens in <code>IO</code>, stays in <code>IO</code>.</p>\n\n<pre class="lang-hs prettyprint-override"><code>unsafePerformIO :: IO t -&gt; t\n</code></pre>\n\n<p>Or, at least, should.</p>\n\n<p>The type signature of a Haskell program</p>\n\n<pre class="lang-hs prettyprint-override"><code>main :: IO ()\nmain = putStrLn "Hello, World!"\n</code></pre>\n\n<p>expands to</p>\n\n<pre class="lang-hs prettyprint-override"><code>World -&gt; ((), World)\n</code></pre>\n\n<p>A function that transforms a world.</p>\n\n<h2>Epilogue</h2>\n\n<p>The category whiches objects are Haskell types and whiches morphisms are functions between Haskell types is, “fast and loose”, the category <code>Hask</code>.</p>\n\n<p>A functor <code>T</code> is a mapping from a category <code>C</code> to a category <code>D</code>; for each object in <code>C</code> an object in <code>D</code></p>\n\n<pre class="lang-hs prettyprint-override"><code>Tobj :  Obj(C) -&gt; Obj(D)\n   f :: *      -&gt; *\n</code></pre>\n\n<p>and for each morphism in <code>C</code> a morphism in <code>D</code></p>\n\n<pre class="lang-hs prettyprint-override"><code>Tmor :  HomC(X, Y) -&gt; HomD(Tobj(X), Tobj(Y))\n map :: (a -&gt; b)   -&gt; (f a -&gt; f b)\n</code></pre>\n\n<p>where <code>X</code>, <code>Y</code> are objects in <code>C</code>. <code>HomC(X, Y)</code> is the <em>homomorphism class</em> of all morphisms <code>X -&gt; Y</code> in <code>C</code>. The functor must preserve morphism identity and composition, the “structure” of <code>C</code>, in <code>D</code>.</p>\n\n<pre class="lang-hs prettyprint-override"><code>                    Tmor    Tobj\n\n      T(id)  =  id        : T(X) -&gt; T(X)   Identity\nT(f) . T(g)  =  T(f . g)  : T(X) -&gt; T(Z)   Composition\n</code></pre>\n\n<p>The <em>Kleisli category</em> of a category <code>C</code> is given by a Kleisli triple</p>\n\n<pre class="lang-hs prettyprint-override"><code>&lt;T, eta, _*&gt;\n</code></pre>\n\n<p>of an endofunctor</p>\n\n<pre class="lang-hs prettyprint-override"><code>T : C -&gt; C\n</code></pre>\n\n<p>(<code>f</code>), an identity morphism <code>eta</code> (<code>return</code>), and an extension operator <code>*</code> (<code>=&lt;&lt;</code>).</p>\n\n<p>Each Kleisli morphism in <code>Hask</code></p>\n\n<pre class="lang-hs prettyprint-override"><code>      f :  X -&gt; T(Y)\n      f :: a -&gt; m b\n</code></pre>\n\n<p>by the extension operator</p>\n\n<pre class="lang-hs prettyprint-override"><code>   (_)* :  Hom(X, T(Y)) -&gt; Hom(T(X), T(Y))\n  (=&lt;&lt;) :: (a -&gt; m b)   -&gt; (m a -&gt; m b)\n</code></pre>\n\n<p>is given a morphism in <code>Hask</code>’s Kleisli category</p>\n\n<pre class="lang-hs prettyprint-override"><code>     f* :  T(X) -&gt; T(Y)\n(f =&lt;&lt;) :: m a  -&gt; m b\n</code></pre>\n\n<p>Composition in the Kleisli category <code>.T</code> is given in terms of extension</p>\n\n<pre class="lang-hs prettyprint-override"><code> f .T g  =  f* . g       :  X -&gt; T(Z)\nf &lt;=&lt; g  =  (f =&lt;&lt;) . g  :: a -&gt; m c\n</code></pre>\n\n<p>and satisfies the <em>category axioms</em></p>\n\n<pre class="lang-hs prettyprint-override"><code>       eta .T g  =  g                :  Y -&gt; T(Z)   Left identity\n   return &lt;=&lt; g  =  g                :: b -&gt; m c\n\n       f .T eta  =  f                :  Z -&gt; T(U)   Right identity\n   f &lt;=&lt; return  =  f                :: c -&gt; m d\n\n  (f .T g) .T h  =  f .T (g .T h)    :  X -&gt; T(U)   Associativity\n(f &lt;=&lt; g) &lt;=&lt; h  =  f &lt;=&lt; (g &lt;=&lt; h)  :: a -&gt; m d\n</code></pre>\n\n<p>which, applying the equivalence transformations</p>\n\n<pre class="lang-hs prettyprint-override"><code>     eta .T g  =  g\n     eta* . g  =  g               By definition of .T\n     eta* . g  =  id . g          forall f.  id . f  =  f\n         eta*  =  id              forall f g h.  f . h  =  g . h  ==&gt;  f  =  g\n\n(f .T g) .T h  =  f .T (g .T h)\n(f* . g)* . h  =  f* . (g* . h)   By definition of .T\n(f* . g)* . h  =  f* . g* . h     . is associative\n    (f* . g)*  =  f* . g*         forall f g h.  f . h  =  g . h  ==&gt;  f  =  g\n</code></pre>\n\n<p>in terms of extension are canonically given</p>\n\n<pre class="lang-hs prettyprint-override"><code>               eta*  =  id                 :  T(X) -&gt; T(X)   Left identity\n       (return =&lt;&lt;)  =  id                 :: m t -&gt; m t\n\n           f* . eta  =  f                  :  Z -&gt; T(U)      Right identity\n   (f =&lt;&lt;) . return  =  f                  :: c -&gt; m d\n\n          (f* . g)*  =  f* . g*            :  T(X) -&gt; T(Z)   Associativity\n(((f =&lt;&lt;) . g) =&lt;&lt;)  =  (f =&lt;&lt;) . (g =&lt;&lt;)  :: m a -&gt; m c\n</code></pre>\n\n<p>Monads can also be defined in terms not of Kleislian extension, but a natural transformation <code>mu</code>, in programming called <code>join</code>. A monad is defined in terms of <code>mu</code> as a triple over a category <code>C</code>, of an endofunctor</p>\n\n<pre class="lang-hs prettyprint-override"><code>     T :  C -&gt; C\n     f :: * -&gt; *\n</code></pre>\n\n<p>and two natural tranformations</p>\n\n<pre class="lang-hs prettyprint-override"><code>   eta :  Id -&gt; T\nreturn :: t  -&gt; f t\n\n    mu :  T . T   -&gt; T\n  join :: f (f t) -&gt; f t\n</code></pre>\n\n<p>satisfying the equivalences</p>\n\n<pre class="lang-hs prettyprint-override"><code>       mu . T(mu)  =  mu . mu               :  T . T . T -&gt; T . T   Associativity\n  join . map join  =  join . join           :: f (f (f t)) -&gt; f t\n\n      mu . T(eta)  =  mu . eta       =  id  :  T -&gt; T               Identity\njoin . map return  =  join . return  =  id  :: f t -&gt; f t\n</code></pre>\n\n<p>The monad type class is then defined</p>\n\n<pre class="lang-hs prettyprint-override"><code>class Functor m =&gt; Monad m where\n   return :: t -&gt; m t\n   join   :: m (m t) -&gt; m t\n</code></pre>\n\n<p>The canonical <code>mu</code> implementation of the option monad:</p>\n\n<pre class="lang-hs prettyprint-override"><code>instance Monad Maybe where\n   return = Just\n\n   join (Just m) = m\n   join Nothing  = Nothing\n</code></pre>\n\n<p>The <code>concat</code> function</p>\n\n<pre class="lang-hs prettyprint-override"><code>concat :: [[a]] -&gt; [a]\nconcat (x : xs) = x ++ concat xs\nconcat []       = []\n</code></pre>\n\n<p>is the <code>join</code> of the list monad.</p>\n\n<pre class="lang-hs prettyprint-override"><code>instance Monad [] where\n   return :: t -&gt; [t]\n   return = (: [])\n\n   (=&lt;&lt;) :: (a -&gt; [b]) -&gt; ([a] -&gt; [b])\n   (f =&lt;&lt;) = concat . map f\n</code></pre>\n\n<p>Implementations of <code>join</code> can be translated from extension form using the equivalence</p>\n\n<pre class="lang-hs prettyprint-override"><code>     mu  =  id*           :  T . T -&gt; T\n   join  =  (id =&lt;&lt;)      :: m (m t) -&gt; m t\n</code></pre>\n\n<p>The reverse translation from <code>mu</code> to extension form is given by</p>\n\n<pre class="lang-hs prettyprint-override"><code>     f*  =  mu . T(f)     :  T(X) -&gt; T(Y)\n(f =&lt;&lt;)  =  join . map f  :: m a -&gt; m b\n</code></pre>\n\n<hr>\n\n<ul>\n<li><p>Philip Wadler: <em><a href="http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf" rel="noreferrer">Monads for functional programming</a></em></p></li>\n<li><p>Simon L Peyton Jones, Philip Wadler: <em><a href="https://www.microsoft.com/en-us/research/wp-content/uploads/1993/01/imperative.pdf" rel="noreferrer">Imperative functional programming</a></em></p></li>\n<li><p>Jonathan M. D. Hill, Keith Clarke: <em><a href="https://www.researchgate.net/publication/2701808_An_Introduction_to_Category_Theory_Category_Theory_Monads_and_Their_Relationship_to_Functional_Programming" rel="noreferrer">An introduction to category theory, category theory monads, and their relationship to functional programming</a></em>\n´</p></li>\n<li><p><a href="https://en.wikipedia.org/wiki/Kleisli_category" rel="noreferrer">Kleisli category</a></p></li>\n<li><p>Eugenio Moggi: <em><a href="https://core.ac.uk/download/pdf/21173011.pdf" rel="noreferrer">Notions of computation and monads</a></em></p></li>\n<li><p><a href="https://wiki.haskell.org/What_a_Monad_is_not" rel="noreferrer">What a monad is not</a></p></li>\n</ul>\n\n<blockquote>\n  <p>But why should a theory so abstract be of any use for programming?</p>\n  \n  <p>The answer is simple: as computer scientists, we <em>value abstraction</em>! When we design the interface to a software component, we <em>want</em> it to reveal as little as possible about the implementation. We want to be able to replace the implementation with many alternatives, many other ‘instances’ of the same ‘concept’. When we design a generic interface to many program libraries, it is even more important that the interface we choose have a variety of implementations. It is the generality of the monad concept which we value so highly, it is <em>because</em> category theory is so abstract that its concepts are so useful for programming.</p>\n  \n  <p>It is hardly suprising, then, that the generalisation of monads that we present below also has a close connection to category theory. But we stress that our purpose is very practical: it is not to ‘implement category theory’, it is to find a more general way to structure combinator libraries. It is simply our good fortune that mathematicians have already done much of the work for us!</p>\n</blockquote>\n\n<p>from <em>Generalising Monads to Arrows</em> by John Hughes</p>\n'}, {'answer_id': 49341047, 'author': 'Regis Kuckaertz', 'author_id': 2631185, 'author_profile': 'https://Stackoverflow.com/users/2631185', 'pm_score': 0, 'selected': False, 'text': '<p>If you are asking for a succinct, practical explanation for something so abstract, then you can only hope for an abstract answer:</p>\n\n<pre><code>a -&gt; b\n</code></pre>\n\n<p>is one way of representing a computation from <code>a</code>s to <code>b</code>s. You can chain computations, aka <em>compose</em> them together:</p>\n\n<pre><code>(b -&gt; c) -&gt; (a -&gt; b) -&gt; (a -&gt; c)\n</code></pre>\n\n<p>More complex computations demand more complex types, e.g.:</p>\n\n<pre><code>a -&gt; f b\n</code></pre>\n\n<p>is the type of computations from <code>a</code>s to <code>b</code>s that are into <code>f</code>s. You can also compose them:</p>\n\n<pre><code>(b -&gt; f c) -&gt; (a -&gt; f b) -&gt; (a -&gt; f c)\n</code></pre>\n\n<p>It turns out this pattern appears literally everywhere and has the same properties as the first composition above (associativity, right- and left-identity).</p>\n\n<p>One had to give this pattern a name, but then would it help to know that the first composition is formally characterised as a <em>Semigroupoid</em>?</p>\n\n<p><em>"Monads are just as interesting and important as parentheses"</em> (Oleg Kiselyov)</p>\n'}, {'answer_id': 50564327, 'author': 'lsmor', 'author_id': 9271266, 'author_profile': 'https://Stackoverflow.com/users/9271266', 'pm_score': -1, 'selected': False, 'text': '<p>following your brief, succinct, practical indications:</p>\n\n<p>The easiest way to understand a monad is as a way to apply/compose functions within a context. Let\'s say you have two computations which both can be seen as two mathematical functions <code>f</code> and <code>g</code>. </p>\n\n<ul>\n<li><code>f</code> takes a String and produces another String (take the first two letters)</li>\n<li><code>g</code> takes a String and produces another String (upper case transformation)</li>\n</ul>\n\n<p>So in any language the transformation "take the first two letter and convert them to upper case" would be written g(f("some string")). So, in the  world of pure perfect functions, composition is just: do one thing and then do the other. </p>\n\n<p>But let\'s say we live in the world of functions which can fail. For example: the input string might be one char long so f would fail. So in this case </p>\n\n<ul>\n<li><code>f</code> takes a String and produces a String or Nothing. </li>\n<li><code>g</code> produces a String only if f hasn\'t failed. Otherwise, produces Nothing </li>\n</ul>\n\n<p>So now, g(f("some string")) needs some extra checking: "Compute <code>f</code>, if it fails then <code>g</code> should return Nothing, else compute g"</p>\n\n<p>This idea can be applied to any parametrized type as follows:</p>\n\n<p>Let Context[Sometype] be a computation of <em>Sometype</em> within a <em>Context</em>. Considering functions </p>\n\n<ul>\n<li><code>f:: AnyType -&gt; Context[Sometype]</code></li>\n<li><code>g:: Sometype -&gt; Context[AnyOtherType]</code></li>\n</ul>\n\n<p>the composition g(f()) should be readed as "compute f. Within this context do some extra computations and then compute g if it has sense within the context"</p>\n'}, {'answer_id': 51680729, 'author': 'schuelermine', 'author_id': 8025936, 'author_profile': 'https://Stackoverflow.com/users/8025936', 'pm_score': 0, 'selected': False, 'text': '<p>A Monad is a box with a special machine attached that allows you to make one normal box out of two nested boxes - but still retaining some of the shape of both boxes.</p>\n\n<p>Concretely, it allows you to perform <code>join</code>, of type <code>Monad m =&gt; m (m a) -&gt; m a</code>.</p>\n\n<p>It also needs a <code>return</code> action, which just wraps a value. <code>return :: Monad m =&gt; a -&gt; m a</code><br>\nYou could also say <code>join</code> unboxes and <code>return</code> wraps - but <code>join</code> is <strong>not</strong> of type <code>Monad m =&gt; m a -&gt; a</code> (It doesn\'t unwrap all Monads, it unwraps Monads with Monads inside of them.)</p>\n\n<p>So it takes a Monad box (<code>Monad m =&gt;</code>, <code>m</code>) with a box inside it (<code>(m a)</code>) and makes a normal box (<code>m a</code>).</p>\n\n<p>However, usually a Monad is used in terms of the <code>(&gt;&gt;=)</code> (spoken "bind") operator, which is essentially just <code>fmap</code> and <code>join</code> after each other. Concretely,</p>\n\n<pre><code>x &gt;&gt;= f = join (fmap f x)\n(&gt;&gt;=) :: Monad m =&gt; (a -&gt; m b) -&gt; m a -&gt; m b\n</code></pre>\n\n<p>Note here that the function comes in the second argument, as opposed to <code>fmap</code>.</p>\n\n<p>Also, <code>join = (&gt;&gt;= id)</code>.</p>\n\n<p>Now why is this useful? Essentially, it allows you to make programs that string together actions, while working in some sort of framework (the Monad).</p>\n\n<p>The most prominent use of Monads in Haskell is the <code>IO</code> Monad.<br>\nNow, <code>IO</code> is the type that classifies an <em>Action</em> in Haskell. Here, the Monad system was the only way of preserving (big fancy words):</p>\n\n<ul>\n<li>Referential Transparency</li>\n<li>Lazyness</li>\n<li>Purity</li>\n</ul>\n\n<p>In essence, an IO action such as <code>getLine :: IO String</code> can\'t be replaced by a String, as it always has a different type. Think of <code>IO</code> as a sort of magical box that teleports the stuff to you.<br>\nHowever, still just saying that <code>getLine :: IO String</code> and all functions accept <code>IO a</code> causes mayhem as maybe the functions won\'t be needed. What would <code>const "üp§" getLine</code> do? (<code>const</code> discards the second argument. <code>const a b = a</code>.) The <code>getLine</code> doesn\'t need to be evaluated, but it\'s supposed to do IO! This makes the behaviour rather unpredictable - and also makes the type system less "pure", as all functions would take <code>a</code> and <code>IO a</code> values.</p>\n\n<p>Enter the <code>IO</code> Monad.</p>\n\n<p>To string to actions together, you just flatten the nested actions.<br>\nAnd to apply a function to the output of the IO action, the <code>a</code> in the <code>IO a</code> type, you just use <code>(&gt;&gt;=)</code>.</p>\n\n<p>As an example, to output an entered line (to output a line is a function which produces an IO action, matching the right argument of <code>&gt;&gt;=</code>):</p>\n\n<pre><code>getLine &gt;&gt;= putStrLn :: IO ()\n-- putStrLn :: String -&gt; IO ()\n</code></pre>\n\n<p>This can be written more intuitively with the <code>do</code> environment:</p>\n\n<pre><code>do line &lt;- getLine\n   putStrLn line\n</code></pre>\n\n<p>In essence, a <code>do</code> block like this:</p>\n\n<pre><code>do x &lt;- a\n   y &lt;- b\n   z &lt;- f x y\n   w &lt;- g z\n   h x\n   k &lt;- h z\n   l k w\n</code></pre>\n\n<p>... gets transformed into this:</p>\n\n<pre><code>a     &gt;&gt;= \\x -&gt;\nb     &gt;&gt;= \\y -&gt;\nf x y &gt;&gt;= \\z -&gt;\ng z   &gt;&gt;= \\w -&gt;\nh x   &gt;&gt;= \\_ -&gt;\nh z   &gt;&gt;= \\k -&gt;\nl k w\n</code></pre>\n\n<p>There\'s also the <code>&gt;&gt;</code> operator for <code>m &gt;&gt;= \\_ -&gt; f</code> (when the value in the box isn\'t needed to make the new box in the box)\nIt can also be written <code>a &gt;&gt; b = a &gt;&gt;= const b</code> (<code>const a b = a</code>)</p>\n\n<p>Also, the <code>return</code> operator is modeled after the IO-intuituion - it returns a value with <em>minimal context</em>, in this case <em>no IO</em>. Since the <code>a</code> in <code>IO a</code> represents the returned type, this is similar to something like <code>return(a)</code> in imperative programming languages - but it does <strong>not</strong> stop the chain of actions! <code>f &gt;&gt;= return &gt;&gt;= g</code> is <em>the same</em> as <code>f &gt;&gt;= g</code>. It\'s only useful when the term you return has been created earlier in the chain - see above.</p>\n\n<p>Of course, there are other Monads, otherwise it wouldn\'t be called Monad, it\'d be called somthing like "IO Control".</p>\n\n<p>For example, the List Monad (<code>Monad []</code>) flattens by concatenating - making the <code>(&gt;&gt;=)</code> operator perform a function on all elements of a list. This can be seen as "indeterminism", where the List is the many possible values and the Monad Framework is making all the possible combinations.</p>\n\n<p>For example (in GHCi):</p>\n\n<pre><code>Prelude&gt; [1, 2, 3] &gt;&gt;= replicate 3  -- Simple binding\n[1, 1, 1, 2, 2, 2, 3, 3, 3]\nPrelude&gt; concat (map (replicate 3) [1, 2, 3])  -- Same operation, more explicit\n[1, 1, 1, 2, 2, 2, 3, 3, 3]\nPrelude&gt; [1, 2, 3] &gt;&gt; "uq"\n"uququq"\nPrelude&gt; return 2 :: [Int]\n[2]\nPrelude&gt; join [[1, 2], [3, 4]]\n[1, 2, 3, 4]\n</code></pre>\n\n<p>because:</p>\n\n<pre><code>join a = concat a\na &gt;&gt;= f = join (fmap f a)\nreturn a = [a]  -- or "= (:[])"\n</code></pre>\n\n<p>The Maybe Monad just nullifies all results to <code>Nothing</code> if that ever occurs.\nThat is, binding auto-checks if the function (<code>a &gt;&gt;=</code> <code>f</code>) returns or the value (<code>a</code> <code>&gt;&gt;= f</code>) is <code>Nothing</code> - and then returns <code>Nothing</code> as well.</p>\n\n<pre><code>join       Nothing  = Nothing\njoin (Just Nothing) = Nothing\njoin (Just x)       = x\na &gt;&gt;= f             = join (fmap f a)\n</code></pre>\n\n<p>or, more explicitly:</p>\n\n<pre><code>Nothing  &gt;&gt;= _      = Nothing\n(Just x) &gt;&gt;= f      = f x\n</code></pre>\n\n<p>The State Monad is for functions that also modify some shared state - <code>s -&gt; (a, s)</code>, so the argument of <code>&gt;&gt;=</code> is <code>:: a -&gt; s -&gt; (a, s)</code>.<br>\nThe name is a sort of misnomer, since <code>State</code> really is for state-modifying functions, not for the state - the state itself really has no interesting properties, it just gets changed.</p>\n\n<p>For example:</p>\n\n<pre><code>pop ::       [a] -&gt; (a , [a])\npop (h:t) = (h, t)\nsPop = state pop   -- The module for State exports no State constructor,\n                   -- only a state function\n\npush :: a -&gt; [a] -&gt; ((), [a])\npush x l  = ((), x : l)\nsPush = state push\n\nswap = do a &lt;- sPop\n          b &lt;- sPop\n          sPush a\n          sPush b\n\nget2 = do a &lt;- sPop\n          b &lt;- sPop\n          return (a, b)\n\ngetswapped = do swap\n                get2\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>Main*&gt; runState swap [1, 2, 3]\n((), [2, 1, 3])\nMain*&gt; runState get2 [1, 2, 3]\n((1, 2), [1, 2, 3]\nMain*&gt; runState (swap &gt;&gt; get2) [1, 2, 3]\n((2, 1), [2, 1, 3])\nMain*&gt; runState getswapped [1, 2, 3]\n((2, 1), [2, 1, 3])\n</code></pre>\n\n<p>also:</p>\n\n<pre><code>Prelude&gt; runState (return 0) 1\n(0, 1)\n</code></pre>\n'}, {'answer_id': 51768485, 'author': 'Joakim Ahnfelt-Rønne', 'author_id': 4506902, 'author_profile': 'https://Stackoverflow.com/users/4506902', 'pm_score': 3, 'selected': False, 'text': '<p>A <code>Monad</code> is an <code>Applicative</code> (i.e. something that you can <em>lift</em> binary -- hence, "<em>n</em>-ary" -- functions to,<sup>(1)</sup> and inject pure values into<sup>(2)</sup>) <code>Functor</code> (i.e. something that you can <em>map</em> over,<sup>(3)</sup> i.e. lift <em>unary</em> functions to<sup>(3)</sup>) with the added ability to <em>flatten the nested datatype</em> (with each of the three notions following its corresponding set of <em>laws</em>). In Haskell, this flattening operation is called <code>join</code>. </p>\n\n<p>The general (generic, parametric) <em>type</em> of this <em>"<code>join</code>"</em> operation is:</p>\n\n\n\n<pre class="lang-hs prettyprint-override"><code>join  ::  Monad m  =&gt;  m (m a)  -&gt;  m a\n</code></pre>\n\n<p>for any monad <code>m</code> (NB all <code>m</code>s in the type are the same!). </p>\n\n<p>A specific <code>m</code> monad defines its specific version of <code>join</code> working for any value type <code>a</code> "carried" by the monadic values of type <code>m a</code>. Some specific types are:</p>\n\n<pre class="lang-hs prettyprint-override"><code>join  ::  [[a]]           -&gt; [a]         -- for lists, or nondeterministic values\njoin  ::  Maybe (Maybe a) -&gt; Maybe a     -- for Maybe, or optional values\njoin  ::  IO    (IO    a) -&gt; IO    a     -- for I/O-produced values\n</code></pre>\n\n<p>The <code>join</code> operation converts an <code>m</code>-computation producing <em>an <code>m</code>-computation of <code>a</code>-type values</em> into one combined <code>m</code>-computation of <code>a</code>-type values. This allows for combination of computation steps into one larger computation.</p>\n\n<p>This <em>computation steps</em>-combining <em>"bind"</em> (<code>&gt;&gt;=</code>) operator simply uses <code>fmap</code> and <code>join</code> together, i.e. </p>\n\n<pre class="lang-hs prettyprint-override"><code>(ma &gt;&gt;= k)  ==  join (fmap k ma)\n{-\n  ma        :: m a            -- `m`-computation which produces `a`-type values\n  k         ::   a -&gt; m b     --  create new `m`-computation from an `a`-type value\n  fmap k ma :: m    ( m b )   -- `m`-computation of `m`-computation of `b`-type values\n  (m &gt;&gt;= k) :: m        b     -- `m`-computation which produces `b`-type values\n-}\n</code></pre>\n\n<p>Conversely, <code>join</code> can be defined via bind, <code>join mma == join (fmap id mma) == mma &gt;&gt;= id</code> where <code>id ma = ma</code> -- whichever is more convenient for a given type <code>m</code>.</p>\n\n<p>For monads, both the <em><code>do</code></em>-notation  and its equivalent <em>bind</em>-using code,</p>\n\n<pre class="lang-hs prettyprint-override"><code>do { x &lt;- mx ; y &lt;- my ; return (f x y) }        --   x :: a   ,   mx :: m a\n                                                 --   y :: b   ,   my :: m b\nmx &gt;&gt;= (\\x -&gt;                                    -- nested\n            my &gt;&gt;= (\\y -&gt;                        --  lambda\n                         return (f x y) ))       --   functions\n</code></pre>\n\n<p>can be read as </p>\n\n<blockquote>\n  <p><em>first "do" <code>mx</code>, and when it\'s done, get its "result" as <code>x</code> and let me use it to "do" something else.</em></p>\n</blockquote>\n\n<p>In a given <code>do</code> block, each of the values to the right of the binding arrow <code>&lt;-</code> is of type <code>m a</code> for some type <code>a</code> and the same monad <code>m</code> throughout the <code>do</code> block. </p>\n\n<p><code>return x</code> is a neutral <code>m</code>-computation which just produces the pure value <code>x</code> it is given, such that binding any <code>m</code>-computation with <code>return</code> does not change that computation at all.</p>\n\n<hr>\n\n<p><sup>(1)</sup> with <code>liftA2 :: Applicative m =&gt; (a -&gt; b -&gt; c) -&gt; m a -&gt; m b -&gt; m c</code></p>\n\n<p><sup>(2)</sup> with <code>pure   :: Applicative m =&gt;  a -&gt; m a</code></p>\n\n<p><sup>(3)</sup> with <code>fmap   :: Functor m     =&gt; (a -&gt; b)      -&gt; m a -&gt; m b</code> </p>\n\n<p>There\'s also the equivalent Monad methods,</p>\n\n<pre class="lang-hs prettyprint-override"><code>liftM2 :: Monad m =&gt; (a -&gt; b -&gt; c) -&gt; m a -&gt; m b -&gt; m c\nreturn :: Monad m =&gt;  a            -&gt; m a\nliftM  :: Monad m =&gt; (a -&gt; b)      -&gt; m a -&gt; m b\n</code></pre>\n\n<p>Given a monad, the other definitions could be made as</p>\n\n<pre class="lang-hs prettyprint-override"><code>pure   a       = return a\nfmap   f ma    = do { a &lt;- ma ;            return (f a)   }\nliftA2 f ma mb = do { a &lt;- ma ; b &lt;- mb  ; return (f a b) }\n(ma &gt;&gt;= k)     = do { a &lt;- ma ; b &lt;- k a ; return  b      }\n</code></pre>\n'}, {'answer_id': 56037990, 'author': 'michid', 'author_id': 402428, 'author_profile': 'https://Stackoverflow.com/users/402428', 'pm_score': 1, 'selected': False, 'text': '<p>According to <a href="https://arxiv.org/ftp/arxiv/papers/1803/1803.10195.pdf" rel="nofollow noreferrer">What we talk about when we talk about monads</a> the question &quot;What is a monad&quot; is wrong:</p>\n<blockquote>\n<p>The short answer to the question &quot;What is a monad?&quot; is that it is a monoid in the category of endofunctors or that it is a generic data type equipped with two operations that satisfy certain laws. This is correct, but it does not reveal an important bigger picture. This is because the question is wrong. In this paper, we aim to answer the right question, which is &quot;What do authors really say when they talk about monads?&quot;</p>\n</blockquote>\n<p>While that paper does not directly answer what a monad is it helps understanding what people with different backgrounds mean when they talk about monads and why.</p>\n'}, {'answer_id': 70008789, 'author': 'einnocent', 'author_id': 538222, 'author_profile': 'https://Stackoverflow.com/users/538222', 'pm_score': 2, 'selected': False, 'text': '<p>A monad is a container, but for data. A special container.</p>\n<p>All containers can have openings and handles and spouts, but these containers are all guaranteed to have certain openings and handles and spouts.</p>\n<p>Why? Because these guaranteed openings and handles and spouts are useful for picking up and linking together the containers in specific, common ways.</p>\n<p>This allows you to pick up different containers without having to know much about them. It also allows different kinds of containers to link together easily.</p>\n'}, {'answer_id': 72264847, 'author': 'Srivathsa Harish Venkataramana', 'author_id': 1301703, 'author_profile': 'https://Stackoverflow.com/users/1301703', 'pm_score': 0, 'selected': False, 'text': '<p>For people coming from the imperative background (c# specifically),</p>\n<p>consider the following code</p>\n<pre><code>bool ReturnTrueorFalse(SomeObject input)\n{\n    if(input.Property1 is invalid)\n    {\n        return false;\n    }\n\n    if(input.Property2 is invalid)\n    {\n        return false;\n    }\n\n    DoSomething();\n    return true;\n}\n</code></pre>\n<p>You would have seen lots of code like this, you would have even seen no early returns but all the checks are done nested. Now, Monad is a pattern where this can be flattened like below</p>\n<pre><code>Monad&lt;bool&gt; ReturnTrueorFalse(SomeObject input) =&gt;\n    from isProperty1Valid in input.Property1\n    from isProperty2Valid in input.Property2\n    select Monad.Create(isProperty1Valid &amp;&amp; isProperty2Valid);\n</code></pre>\n<p>There are a few things to note here. First, the function\'s return value is changed. Second, both the properties of input have to be Monad. Next, Monad should implement SelectMany(LINQ\'s flattening operator). Since SelectMany is implemented for that type, the statements can be written using the query syntax</p>\n<p>So, what is a Monad? It is a structure that flattens expressions that return the same type in a composable way. This is particularly useful in functional programming because most functional applications tend to keep the state and IO at the edge layer of the application (eg: Controllers) and return Monad based return values throughout the call stack until the value is required to be unwrapped. The biggest plus for me when I first saw this was it was so easy on the eyes as it was so declarative.</p>\n<p>The best example of a Monad that every c# (these days almost everyone) developer can immediately recognize is async/await. Before.Net4.5 we had to write Task-based statements using ContinueWith for handling callbacks, after async/await we started using synchronous syntax for asynchronous syntax. This is possible because Task is a &quot;monad&quot;.</p>\n<p>Refer to <a href="https://blog.ploeh.dk/2022/03/28/monads/" rel="nofollow noreferrer">this</a> for a detailed explanation, <a href="https://mikhail.io/2018/07/monads-explained-in-csharp-again/" rel="nofollow noreferrer">this</a> for simple implementation and <a href="https://github.com/louthy/language-ext" rel="nofollow noreferrer">language-ext</a> for lots of awesome Monads and tons of information about functional programming in general for an OOP developer</p>\n'}]
['https://Stackoverflow.com/questions/44965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3394/']