Talk:Monad (functional programming)

From Wikipedia, the free encyclopedia
Jump to: navigation, search
WikiProject Computer science (Rated B-class, Mid-importance)
WikiProject icon This article is within the scope of WikiProject Computer science, a collaborative effort to improve the coverage of Computer science related articles on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.
B-Class article B  This article has been rated as B-Class on the project's quality scale.
 Mid  This article has been rated as Mid-importance on the project's importance scale.
WikiProject Computing (Rated C-class, Low-importance)
WikiProject icon This article is within the scope of WikiProject Computing, a collaborative effort to improve the coverage of computers, computing, and information technology on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.
C-Class article C  This article has been rated as C-Class on the project's quality scale.
 Low  This article has been rated as Low-importance on the project's importance scale.


Please remember to sign your post with 4 tildes (~~~~).

If you are adding a new talk thread, please append your contribution to the foot (the bottom) of this talk page; just click the "new section" tab to start. (This practice helps us when an editor is searching for content in a thread of discussion. This is a reason to keep the threads in temporal order, for ease of archiving and retrieval.)

If you are posting to a specific thread, then click the "edit" link on the upper right of that section. (It is customary to keep individual editor's contributions unaltered; thus standard wikipedia practice is to indent talk as if one were coding. For more information see Wikipedia:Cheatsheet for examples.)

Merging articles and the name of the article[edit]

This is actually the same as Monad (category theory). These should be merged. —Ashley Y 22:19, 2004 May 31 (UTC)

They're not really the same thing: an explanation of Haskell's IO monad doesn't belong in an article on category theory, and a detailed explanation of monads in category theory isn't relavent to the average Haskell programmer. In addition, many standard Haskell monads aren't strictly speaking monads at all. I think it's probably best to keep the articles separate. Cadr 22:28, 31 May 2004 (UTC)
Which Haskell monads are not monads in the CT sense? —Ashley Y 09:58, 2004 Jun 1 (UTC)
The IO monad is one example (see [1]). Cadr 11:08, 1 Jun 2004 (UTC)
It's not clear, actually, since the difference is only visible with the 'seq' function, which is considered slightly dubious anyway. More importantly, these are Haskell's monad laws that IO may or may not be properly living up to: the sense in which "monad" is used in Haskell is precisely the CT sense.
If you think this should be a separate article, rename it "Monads in functional programming", rather than the () notation which suggests that it's a separate sense of the word.—Ashley Y 02:49, 2004 Jun 2 (UTC)
OK, but it's still the case that the two articles cover very different information. I'm fine with it being renamed to Monads in functional programming. Cadr 14:15, 2 Jun 2004 (UTC)

Rename (from "Monad (functional programming)") done. —Ashley Y 23:27, 2004 Jun 2 (UTC)

Er, the first sentence of the second para (and possibly more) looks like a copyvio from --- I don't know the topic well enough to rephrase to eliminate this. Could someone who knows the topic look into this? thanks, jdb ❋ 06:00, 27 Jan 2005 (UTC)

The // causes me no discomfort despite C being my first language. It's really obvious that it is an operator, especially given the text defining it as an operator... at least for me. However I *did* get confused by "par" (is it relevant to learning about Monads? oh no, it's an example taken from electrical engineering that I've seen before; it deserved a comment defining it) —Preceding unsigned comment added by (talk) 23:56, 4 May 2009 (UTC)

par function[edit]

Why is the function called par? --MarSch 11:06, 25 October 2005 (UTC)

At least that's the function for total resistance of two resistors in parallel coupling. --TuukkaH 16:14, 25 October 2005 (UTC)

For people used to reading C++ all day, "//" is a very difficult operator name to read. It looks like the start of a comment, and it's almost painful to have to ignore such "comments". Perhaps it could be renamed to "./." or even "///"? Kimbly 02:52, 10 January 2006 (UTC)

What about "::", "->", and "--"? (and "|", ">>=", ">>" and "++", further down the page.) Like "//", they all have specific, and entirely different, meanings in C++. Beyond C++ and Haskell, you'll find yet other meanings for them. What makes C++'s "//" special enough to avoid?
Besides, it's fairly clear that the examples are not in C++, so i don't see how it could cause more than momentary confusion, at worst. --Piet Delport 04:34, 10 January 2006 (UTC)
In most grammars, comment signs are special: // and /* in C++, Java etc., # in Python etc., ; in Lisp, -- and {- in Haskell. I noticed I've special-cased them too and skip text in them automatically. C++ programmers are used to << etc. meaning many things because they are overloaded already in the standard and most every language has operator overloading. Of course you can get accustomed to any a syntax, but do we want to make it as hard as possible for people to read this article? It's not like // would be an integral part of the Haskell syntax. --TuukkaH 09:19, 10 January 2006 (UTC)
Personally, i've been using C, Java, and Javascript for at least a couple of years (with // comments wherever possible; i'm not fond of /**/), but the example still doesn't cause me any discomfort. Besides, even if you limit the symbols to comments, what about Forth (and Forth-like) programmers, who use parentheses for comments (like in English)? The curly brace programming languages are very important and influential, but they're not special enough to start imposing their syntactical meaning on innocent bystanders.
Besides all that, i want to note that // already has an established meaning of "modified/alternate division" in several languages (including Python): something that thousands of people can recognize immediately. This alone should make it an obvious winner over inventions as novel as /// and ./.. --Piet Delport 19:51, 10 January 2006 (UTC)
I know what you mean, I've had the same problem with people using # or ## as an operator, while in Python, shell etc. they are used to start comments. As this page isn't strictly about Haskell, if we want to use Haskell as an example, we could still try to remove unnecessary readability problems from the article. --TuukkaH 05:50, 10 January 2006 (UTC)


I guess my scam is up. I haven't really used Haskell any significant amount, and I barely understand this monad stuff. I just hoped I might be able to push this article away from the two mistakes so many monad tutorials make—presenting them as "how you do I/O" or completely neglecting to give any intuition to the general concept of a monad. I did my rewrite with a copy of Wadler's "Comprehending Monads" in hand, but since I made so many mistakes I'll tag the article for verification. TuukaH is correct above about the naming of par. Gazpacho 04:13, 29 October 2005 (UTC)


This page really seems to be more about monads in Haskell, rather than in a generic programming language. The examples given seem to be in Haskell, which for non haskell programmers (i.e. me) are really hard to follow.

Shouldn't this either be renamed to something like "Monads in Haskell" with a link to understanding Haskell, or have the equations written in a common mathematical way?

If I understand correctly, monads are containers for values: for example, a monad value like "Just 5" contains the value 5. The return function "wraps" a value inside a monad, the fmap function allows another function to "look inside" a monad value, and it looks like join turns a value like Just (Just 5) into Just 5, or [[3]] into [3]. A few examples:
return 3 = either [3] or Just 3 -- "Wrap" the value 3 with a monad
fmap (+1) [3,2,4] = [4,3,5] -- (+1) is the incrementor function, and it is allowed to "peek inside" this list to increment everything inside it.
fmap (+1) (Just 5) = Just 6 -- Peeking inside a "Just" value.
join Maybe (Maybe 7) = Maybe 7 -- "Joining" these two Maybe's into one
join [[2]] = [2] -- Joining a listifier with a listifier
Is this clear enough? -- 02:09, 3 December 2005 (UTC)
Kind of. Monads are types with associated functions (bind (written >>=) and return). These are sometimes containers in a naive way — the List monad and Maybe monad. But monads like CPS "contain" something, but it's not directly accessible in any way. More complicated monads do even crazier things: threaded coroutines can be expressed as a monad. Taking an example from a tutorial site (sorry, can't find the URL), a monad could keep a value corresponding to the remaining number of steps to allow in the computation; when this counter reaches zero, all binds just return the value computed up to that point. None of these are "containers for values" in any sensible way.
I don't think moving to "Monads in Haskell" is appropriate. It begins by describing everything abstractly, but eventually we need to discuss monads in practice. Our choices are limited to Haskell, Clean, and MirandaTM. Every other programming page just picks a language, so why not here? If another language you know of uses monads in an interesting way and with a different syntax, by all means add it in!
I think the current explanation is fine. In that sense the "cite" tag is inappropriate, but it would be nice to cite some source on monads anyway. --Mgreenbe 10:00, 4 January 2006 (UTC)
I'm finding the haskell-centricity of this pretty rough to follow too. Unfortunately I don't think these examples are terribly useful in their current form for non-Haskell programmers. The syntax is a little exotic, and it'd be better translated into a less symbol-heavy pseudocode. —Preceding unsigned comment added by (talk) 13:20, 13 September 2007 (UTC)

To be useful, (I concur that) this article should be relieved of its Haskell-centricity. This problem appears to have been lost or ignored; however the importance of the article itself should give some priority to fixing it. Timlevin (talk) 21:15, 28 November 2008 (UTC)

I think Haskell-centricity is a good thing. It means the article is talking about a real programming language that you can try out and use, and an appropriate one for the subject, to boot. I don't like pseudocode - pseudocode tends to have its own conventions, which then have to be documented - so why not just use a real programming language? And I don't think it makes sense to use a language like Java, in which monads would not typically be used - besides, not everyone knows Java anyway.—greenrd (talk) 22:00, 28 November 2008 (UTC)
Indeed. I wonder if we even could replace the Haskell code with Java. Even if it were possible, I suspect that the circumlocutions and monstrosities that would result would impede understanding far more than Haskell examples ever could. --Gwern (contribs) 03:05 29 November 2008 (GMT)
I would like to concur that the article should be stripped of its Haskell-centricity. I think that the points by Greenrd and Gwern miss the point a little. It's not that the Haskell notation should be replaced by some other programming language notation. The idea would be to replace it with something like standard mathematical notation in key parts. Not that there can't be Haskell examples, but it would be helpful to make it clear when you are talking about Haskell, and when you are talking about monads as abstract things. So, for example, axioms about monads should be presented in mathematical notation and not in Haskell notation, but it would be great to present examples in Haskell notation. By comparison, in an algorithms book we give the graph theory background using mathematical notation, and then we give the algorithms themselves either in pseudocode, or in a particular programming language. It would confuse things to try to present axioms about bi-connected components, for example, as C source code. Similarly here it obscures the presentation of monad axioms to present them in Haskell. I'd urge that the page be reviewed and a distinction made between the mathematical framework, the examples, and the program constructs, and appropriate notation used in each place. --Rpgoldman (talk) 22:44, 15 April 2009 (UTC)
From my readings, it seems Haskell was one of the first programming languages to include the concept of monads, so I think discussion of Haskell has its place, if in no other place than in History and Examples sections, but I would also vote that the rest of the article be expressed in language neutral terms. To start, I think "(bind and return)" should be changed to "(bind and unit)". From what I've read elsewhere, "unit" is the original wording used in category theory and "return" is the operator that Haskell uses to express the unit transformation. Since the notion of a return has a different meaning for imperative programming languages, most have taken to using "unit" to express this operation when introducing monads in other languages. —Preceding unsigned comment added by Derekgreer (talkcontribs) 20:37, 10 October 2010 (UTC)

Just markup issue[edit]

The cleanup tag really only refers to the fact that the first line is not rendered as the following lines are, and despite my attempts to fix it, it stubbornly remained the same... perhaps this is trivial, but still visually not pleasing. The preceding unsigned comment was added by Laddiebuck (talk • contribs) 02:52, March 2, 2006 (UTC).

The rendering is different because the line doesn't contain any non-standard characters, and is thus rendered in HTML instead of LaTeX. If you set your user preferences to "always render PNG", all lines will be the same. —donhalcon 03:03, 2 March 2006 (UTC)
I have adjusted the markup to use <code> tags instead of <math> tags and HTML entities instead of PNGs. Should look ok now regardless of settings. —donhalcon 03:34, 2 March 2006 (UTC)
This fragment is almost unreadable due to formatting:
(//) :: Maybe a -> Maybe a -> Maybe a
_ // Nothing = Nothing
Nothing // _  = Nothing
_ // Just 0 = Nothing
Just x // Just y = Just (x / y)

The wildcard underscores end up directly on top of N and J and visually disappear from the lines they logically belong to (in fact they look like C++/Java comments). Is there a way to increase vertical spacing? Maybe double space it like this?

(//) :: Maybe a -> Maybe a -> Maybe a

_ // Nothing = Nothing

Nothing // _  = Nothing

_ // Just 0 = Nothing

Just x // Just y = Just (x / y)  

Bartosz (talk) 20:48, 27 October 2010 (UTC)

Monad and sequencing[edit]

The article states that "Since the bind operator is non-associative, this constrains the sequence of execution." Is this really correct? The monad laws require that bind be associative, and the sequencing effect is due to the non-commutative properties of the bind operator. Chuan-kai Lin 17:26, 3 April 2006 (UTC)

I agree. I changed it to read "Since the bind operator is associative and non-commutative, this constrains the execution into a sequence." Because of associativity there is no hierarchy and because of lack of commutativity the operations must act in the given order. --TuukkaH 06:21, 4 April 2006 (UTC)
Except this isn't correct. Using the continuation monad, one can have the sub-expressions to "bind" executed in whatever order you want, even in non-deterministic fashion if one so desires. Fortunately, it appears that this text has been removed Obscuranym (talk) 18:32, 4 December 2008 (UTC)

Rewrite on 2006-05-08[edit]

I rewrote large sections of this article because I cited it for someone who wanted to know what monads are, he told me it didn't make any sense, and I agreed. Mainly, I made it less heavy on mathematical formulas. It's now heavy on Haskell, but I think that's appropriate because Haskell is the main promoter of monads, and this lets people download a Haskell system and try the code. Gazpacho 03:59, 9 May 2006 (UTC)

I don't think this was a good idea. Mathematics is universal across languages. Haskell is not. Perhaps a little bit of explanation of Haskell's syntax would be in order, or else just use pseudocode. Also, since you do say that there exist formulations in Scheme and Perl, perhaps a reference to those formulations would be nice. The section that existed previous to your edit which defined for instance the bind operator is much more clear than the current version. Please re-add a section describing the notation used, because unless you already know Haskell, it doesn't currently make a lick of sense.

The current version of the article is extremely Haskell-centric. There are plenty of tutorials on Haskell monads on the web. There's no need for the Wikipedia article to be one as well.

Just to be clear, I don't have a problem with the use of Haskell as the language to illustrate monad concepts. But the current presentation is very much "here's how to use monads in Haskell". In particular, phrases like "To define a monad in Haskell...", and the discussion of Haskell's do-notation seem more appropriate for a Haskell article than a general article on monads in FP. --Allan McInnes (talk) 20:22, 22 June 2006 (UTC)

Unfortunately, I agree that if it's too abstract people won't actually be able to learn from it. For people coming from a CS rather than a maths background, Monads are rather tricky.—The preceding unsigned comment was added by (talkcontribs) .

I agree too. I'm trying to completely grasp continuations as monads so I can add them to this. In the papers I've looked at thus far, most of them use Haskell. It'd probably be best to keep the explanation here as is, but move some of the Haskell-centric stuff (like the do-notation stuff) to another page --NotQuiteEXPComplete 12:25, 3 August 2006 (UTC)

Editorial wish-list[edit]

I wish there was a way to include comments right in the article on Wikipedia, but we don't have that, so I'll try to explain where I want changes. My comments refere to the version as of

Section Motivation: the first code example: I think this is Haskell code, but it's not apparent that it really is. Please be explicit about that. "par" is a bad function name; it isn't obvious that it has anything to do with parallel connection of resistors. Better to call it foo, or something. The syntax of the two lines of code is not obvious. The meanings of :: and -> are non-obvious.

Second code example: Is ... a part of the code? The meaning of :: and -> are again non-obvious. In an electrical engineering program, I'd like to use // as an operator means 1(1/x + 1/y), i.e., parallel connection, since the operator consists of two parallel lines. Therefore it's a bad choice for the meaning here; a new form of division.

The last sentence of the code example suggest that the example is wrong. Is it?

Section Definition: Shouldn't this be a definition of monads in functional programming, rather than monads in Haskell?

What does | (vertical bar) mean?

Are the words "data", "Just", "Nothing", parts of the Haskell language?

Is the character a part of the Haskell language?

Section Failure: Is the word "mzero" a part of the Haskell language, or of functional programming vocabulary?

The Maybe monad example: What does "'", "in" and "let" mean?

The rest of the article is left for a later time.

You can include comments just fine. "<!-- Comment on FOO -->" does it just fine inline. --Gwern (contribs) 21:00 27 November 2006 (GMT)


Shouldn't Monad (functional programming) be the main name of this article? The discussion above doesn't really explain the reason for the name. --Bkkbrad 01:44, 26 December 2006 (UTC)

Yeah, it probably should be. — Matt Crypto 17:34, 26 October 2007 (UTC)
Oh, but see Talk:Monads_in_functional_programming#Merging_articles_and_the_name_of_the_article. — Matt Crypto 13:32, 29 November 2007 (UTC)

Haskell code correct?[edit]

My haskell is a bit rusty, but it seems to me that
(return x) >>= f ≡ f x
should be
(return x) >>= f ≡ return (f x)
—The preceding unsigned comment was added by (talk) 13:16, 27 March 2007 (UTC).

I don't think so...if x has type a, and f has type a -> m b, then return x >>= f will have type m b, the same as f x. return (f x), on the other hand, will have type m (m b), since return has type a -> m a. Nick8325 14:52, 27 March 2007 (UTC)
Nick8325 is definitely correct on this count. (talk) 17:42, 15 February 2009 (UTC)


So I don't understand what Monads are, and after reading the article twice, I still don't know. The opening of the article explains what they are used for, but not what they are. The 'maybe' example is semi-understandable, but nothing explicitly states what problem Monads are solving. The definition given is nice and formal but totally inaccessible to anyone that doesn't already know what's being talked about. Is there some analogy that might be used to explain it? I haven't written a lot of code in functional languages (although I have written a little), never used Haskell, but I do have a Ph.D. in software engineering. 17:38, 10 June 2007 (UTC)

Wikipedia is not a tutorial. The article links to the Haskell Wikibook's Understanding monads section; failing that, the Haskell wiki has a diverse list of other monad tutorials. --Piet Delport 04:55, 11 June 2007 (UTC)
Ah, so it's not the purpose of Wikipedia (supposedly an encyclopedia) to explain something so that it's minimally understood. Gotcha. Gazpacho 16:54, 9 August 2007 (UTC)
No need to be snarky. The purpose of Wikipedia is to explain, but not to teach. Less textbook, more summary and reference. Piet Delport 2007-08-09 19:49
Nonsense. Definition that define terms recursively fail the philosophy 101 test. "Monads are objects that have a lot of monadic flavor to them." is not a valid definition of what a monad is. I wish I could get close to such faux intellectuals such as yourself and punch you in the face, because you don't understand logic and reason. There is no real difference between teaching and explaining. If an explanation fails to elucidate the matter, it is not an explanation at all. What is teaching besides elucidation? The only thing that teaching can add on top of elucidation is memorization and rote practice, but elucidation is an essential element in teaching. So to say that because Wikipedia does not aim to teach it no longer needs to be lucid is pure nonsense. To philosophy 101 with all you idiots. You don't deserve respect or politeness. You offend my faculties of mind, foul pseudo-fiends that you are. Ptoooey. "Will someone please respect me.... whaaaaaa!!!! I am so smart, I can write things that no one can understand!!! waaaaaa!!!" Enough of this. Is it any wonder that functional programming fails to take root? It's all thanks to arrogant and ignorant bastards that write articles like these. -- Someone who took Philo 101. (I'm not Matt, the guy below)
Axioms are not circular. You accuse others of being faux intellectuals but you're the one bragging about taking a philosophy class as if it means anything. Anyone can take a class, but you don't appear to have learned anything from it. Whole books have been written to teach monads ("Learn you a haskell..." takes you from not knowing any Haskell to monads). They contain a lot of background material and exercises for a reason, because monads won't make sense without them. If you can write a better explanation, then go ahead and do so but this could simply be the Monad Fallacy (talk) 14:44, 6 April 2014 (UTC)
The problem is that Wikipedia didn't explain it that well either.-- 02:47, 11 October 2007 (UTC)
To be fair, monads can be a tricky thing for most people to get their heads round. As a result, it's not straightforward to explain it in a very accessible way without it becoming a lengthy tutorial. I reckon we could still do better though. — Matt Crypto 17:32, 26 October 2007 (UTC)
exactly. This article doesn't seem to explain what monads are, but how they work.-- (talk) 09:32, 29 November 2007 (UTC)
I agree with the dude that took Philo 101. If you don't think wikipedia's goal is to teach people, you're sorely mistaken. I believe snarkyness was well in order. (talk) 01:34, 14 January 2011 (UTC)

5 years and this is still impossible to understand. I've been a programmer my entire life. This article barley explains, and certainly does not teach, anybody what *monads* are. I'm adding the 'Too Technical' template. I'll try to clean it up soon. nezZario (talk) 21:36, 21 February 2016 (UTC)

Do you have specific ideas about the improvements that you'd want to see? I'd expanded the lede with a code example, so that programmers can see what monadic code looks like - and have a specific (yet incomplete) instance of how the mentioned "pipeline" is built. What other explanations would you like to see? Diego (talk) 10:15, 22 February 2016 (UTC)

Fourth reference of article is outdated[edit]

The reference "The three fundamental laws of Monad" does not exists anymore. Is the content at a new spot on the net? 09:15, 27 July 2007 (UTC)

"All About Monads" now resides at [2]. -- 09:18, 3 August 2007 (UTC)

"Maybe" Example and 4 Stages of Binding[edit]

First off, whoever wrote the "Maybe" example, thanks; it's been really helpful in getting my head around this. :) That said, there's something in there that doesn't seem right, and I think it may be an error. Specifically, it looks to me like

(Just x) >>= f = Just (f x)

should be

(Just x) >>= f = f x

f should be of type a -> Maybe b; Just (f x) would be of type Maybe Maybe b, which wouldn't be right. (The standard prelude has (Just x) >>= k defined as k x.)

This also makes the "4 stages of binding" bit that precedes it seems a little misleading. I don't think the "piercing" of the result of the function being bound happens in Haskell unless you explicitly ask for it to (by, say, pattern-matching the result of the function being bound). In the case of Maybe, it's simply returning the function result straightaway.

I'd love to get some other thoughts on this, since I'm just getting started with Haskell!

Ngroot 19:44, 8 September 2007 (UTC)

Ironically, I came here to make an edit because the "Just" is missing. Recall that the result value should be of type "M u". I've added the clarification "(and wrapping the result in the monad type)"; i.e. what is done is this: "(Maybe x)" =extract_value=> "x" =apply_function=> "(f x)" =wrap_into_monad_type=> "Just (f x)". It has to be done this way, because at any moment, the computation could fail, resulting in "Nothing". All successful results are wrapped in "Just". ToolmakerSteve (talk) 21:00, 19 April 2008 (UTC)

I've now also changed 'A Maybe type is just the underlying type' to read 'A Maybe type is the underlying type wrapped with "Just"'. I am hoping this helps clarify that inside the Maybe monad, all values that aren't Nothing are wrapped in "Just". At each computation step, there is a simple test for "Just" or "Nothing". ToolmakerSteve (talk) 21:36, 19 April 2008 (UTC)

I'm experimenting with the equivalent of monads in F#; now I understand what Ngroot was saying. This needs to be rewritten, as it is unclear whether the "f" here is referring to a function returning a monad type, (which is why Ngroot saw the result as becoming "Just (Just ...)" as written), or the underlying function operating on the underlying value. ToolmakerSteve I am attempting to rewrite by introducing "f'", which is the monadic function that applies the underlying "f" and wraps it with "Just" on success, or returns "Nothing" on failure. (talk) 23:15, 19 April 2008 (UTC)

Importance as per Computer Science project[edit]

I've changed the Importance level to Mid. This subject is central to current practice in functional languages, at the same level than Design Patterns in OOP. But feel free to discuss. Diego (talk) 07:35, 26 June 2008 (UTC)

Unclear and unencyclopedic[edit]

I can't understand what monads are from this article.

The first paragraph describes what monads are used for instead of describing what they are, contrary to Wikipedia guidelines. The rest of the articles then constantly mixes definitions referencing unexplained terms, like 'monadic type' with examples written exclusively in Haskell. —Preceding unsigned comment added by (talk) 10:03, 6 July 2008 (UTC)

Absolutely agreed. "Here's a bit of code in a pseudo-language lacking any referents you'll recognise. To add confusion, we use a custom operator, //, which we have to define in detail. The Maybe monad doesn't appear in this code and is only mentioned briefly at the end of the description. From this you can deduce what a monad is, despite the fact that we've not explained what the Maybe monad is, what makes it a monad, why it's appropriate, and why we chose not to define it here." Better still, go to the Maybe monad section for enlightenment, and it says "The Maybe monad has already been defined above". So by implication I have to read 2/3 of the article to understand the lead-in paragraphs. Must Try Harder. -- (talk) 12:21, 27 October 2009 (UTC)
Some of the shortcomings in the grandparent comment were already addressed. I agree that the Maybe monad definition spread all over the article is not a good idea.
The lead example, though, is a valid one: it's easier to understand a monad through an usage example like the one provided, than with the definition example you're asking for. To understand the definition of monads one really should be looking at the Monad (category theory) article; this one is for their usage in programming, and as such their purpose is best explained by how it applies to common programming practices, so there's where the lead is focusing in. I've expanded the rationale for this example. Diego (talk) 11:18, 23 November 2009 (UTC)
I've also reworked the example structure, moving it to the body article and placing all the bits of the Maybe monad definition together. Is it clearer now? Diego (talk) 11:38, 23 November 2009 (UTC)


I just removed the following from the article: A "monad" should not be defined in terms of itself. That's bullshit (philosophy 101?). Please define what "monad" is without using the term "monad" to define it. If you cannot, I venture to say you don't understand it yourself and shouldn't be writing Wikipedia entries. I pray to God whoever wrote this were not a University professor, for it would indicate a sorry state of our education. (by User:

It *is* definitely inappropriate to have a "definition" section that uses "monadic" without first defining what it means, even if the definition occurs later. shreevatsa (talk) 22:31, 15 July 2008 (UTC)

I have done some working on the leading paragraph, I hope this provides a more clear definition and some insights in what monads are used for. Although the complaint was rude, their point was valid. Diego (talk) 08:13, 16 July 2008 (UTC)
Great work, the lead looks much more clear and encyclopaedic now. The "definition" section could use some improvement though. Even simply renaming a part of it to something other than "definition" would be an improvement :) shreevatsa (talk) 12:07, 16 July 2008 (UTC)
I agree the introductory paragraph (the definition) which is apt to be picked up by itself and reused as "quick information" by the major search engines is too reliant on additional knowledge, not well known to a reader arriving at the article hoping to learn. The reader is subjected to numerous GOTO like references, making it eerily similar to spaghetti code; that scratching sound at a disco, or a disk drive forced to do multiple seeks when attempting to recover data from a defective sector.
In functional programming, a monad is a structure that represents computations defined as sequences of steps: a type with a monad structure defines what it means to chain operations, or nest functions of that type together. This allows the programmer to build pipelines that process data in a series of steps (also called actions), in which each action is decorated with additional processing rules provided by the monad.[1]

functional programming -> uses monads (what is "functional" vs. other types of programming? Is "functional programming" defined fully by the use of monads or the opposite?)
monad -> is a structure (in context, what is a "structure"?)
mondad -> represents computations defined as sequences of steps (What makes "a sequence of computation steps" called a mondad different from any "computer program")
type -> may have a monad structure (what is a type? And specifically here in context, what is a type?)
type.monadStructure -> a monad defines what it means to (what is the "what" here as in "what it means". How does this work?)
chain operations (how is a "chain operation" any different from a "computer program")
type.nestedFunction -> a monad defines what it means to (what is type.nestedFunction? What does "define what it means" actually mean? How does this "define what it means" work?)
pipelines -> process data in a series of steps (how is this any different from a "computer program")
series of steps -> is a action (how is that different from a function, or just a "computer program")
series of steps (aka action) -> are decorated (what is "decorated")
action -> can be decorated with additional processing rules (how?)
monad -> provides additional process rules (to action via "decoration") (how?)
— Preceding unsigned comment added by (talk) 15:46, 22 June 2016 (UTC)

At some level, you must rely on the meaning of the words to convey the meaning of the sentence that uses them. The words used in the introductory are either plain English (computations, sequences, steps, structure) or basic programming terms (types, functions), which the opening "In functional programing..." puts in context. The few that have a specific technical meaning (pipelines, decorated) have a related common meaning, and are accompanied in context by an in-place clarification, as recommended by WP:JARGON ("a pipeline processes data in steps"; "a decoration adds processing rules").
The point of that first sentence is to put emphasis on the fact that monads are a way to structure programs, which is different to other classic ways. The way in which a monad "defines what it means" to compose operations is explained in the rest of the article; I couldn't find a way to crunch as much detail in the first sentence (although, the following part about decorations explains how this is done). The way that the structure of monads differs from other kinds of programs is explained in the sentence: it allows the programmer to decorate each action, i.e. to include "additional processing rules" at each step of the sequence (which typical sequencing doesn't allow). The way in which this decoration happens is explained further in the lede with the "safe division" example.
If you have specific ways in which to improve this first sentence please suggest them, I'd like to collaborate in improving it. Thank you for the feedback of how the sentence reads to a mind other than mine. ;-)
For what it's worth, the original lede introduction before having this definition was this: "Some functional programming languages make use of monads to structure programs that include operations that are sequenced. The name monad derives from category theory, a branch of mathematics that describes patterns applicable to many mathematical fields. (As a minor terminological mismatch, the term "monad" in functional programming contexts is usually used with a meaning corresponding to that of the term "strong monad" in category theory, a specific kind of category theoretical monad.[citation needed])". Diego (talk) 10:29, 23 June 2016 (UTC)
Actually, you've found a source of ambiguity. Actions in the paragraph refers to steps, not series of steps. I'll try to rewrite it to remove the ambiguity. Diego (talk) 10:46, 23 June 2016 (UTC)

Diego - thanks very much for your effort here to wrestle with the concept of Monad (and Functional Programming) and make knowledge of it accessible to the non academic. In my case I only know VBA (via Excel and Word, including basic reuse of other Windows componentry. Lots of lines of BASIC code; Sub and Function. "Pipes" I remember from UNIX at the command line. That's about the extent of my knowledge. I remember looking at an 8080 instruction set in the 70's and programming a HP calculator with registers (push and pop those stacks), using reverse Polish notation (RPN), etc. I have ZERO training in assembly language, compilers, language design, compile to psudo code / intermediate machine code, common language run times, how garbage collection really works, etc. Have some exposure to "build any logic you want with just a bucket of NAND gates", HTML, CSS, Javascript, RDMS, Prolog (a long time ago, but I couldn't at that time make it do anything useful for me), SED, AWK, daemons, message cuing, basic networking, some elementary Microsoft OOP as seen through VBA. So in my mind (coming from too much VBA) we have already been "functional programming" as in lines of BASIC code inside a function, that returns a value to the Excel grid. More recently I've been probing around the foothills of linked data (parsing and linking: people, places, time/date, organizations), RDF, SPARQL, etc.

How did I get to this the Monad? Excel -> Power Query -> M language -> based on F# -> based on Ocaml [wow, an investment firm that also used VBA extensively; tried Java and hated it...] -> based on ML -> Robin Milner early 1970s at the University of Edinburgh [WOW, I'm back to a home of Prolog and AI! Topics I have already deeply wanted to revisit for a while now, cool!]

So it looks like the cat is out of the bag on Monads and its high time for the masses to really understand them (trust me there are a lot of Excel users out there!) Hence a need to make the definition accessible and inviting to learn more, achieving a reasonable understanding after a relatively brief period of concentrated mental investment. I tried to "map my mind" a bit for you above so you could easily see where I went off the path to understanding. Perhaps too much time spent with BASIC and VBA may be counter intuitive to grasping Monads? However if you have a continuing interest in "grinding away ignorance" I'm happy to further map mine. BTW send your consulting fee to Bill @ M$FT who seems to be (at least partially) betting the farm on F#. [speaker grants] — Preceding unsigned comment added by (talk) 16:43, 23 June 2016 (UTC)

+1 to your comment.
Monads is a kind of design pattern, so it's a moderately advanced concept; one should first grasp the basics of functional programming before learning them. I don't think users of Excel-like software need to grasp it, though developers who create Excel-like software and programming languages will benefit from understanding the concept.
And yes, knowing any kind of imperative programming is a hindrance to understanding any declarative language. PROLOG and SQL would be the closest thing to functional languages in your reported experience, as well as macro-less Excel. Diego (talk) 17:05, 23 June 2016 (UTC)

Diego - thanks for the info. At last some context I can grasp. Of course a few more questions. When you say Design Patterns do you mean things like: Head First Design Patterns or something at a lower level? If that Head First book is way far off the mark do you have a good, thorough seminal level textbook that more or less covers the Design Patterns waterfront?

I would also be very curious to see if you felt Power Query Formula Language (a/k/a "M", which appears to me to be closely aligned to F#, OCaml, ML...] is actually a clean implementation of functional programming? You could probably get a feel for it in just a few of intro pages (7-14 in the PDF) in the language spec. If that strikes you as functional programming I'd like to invest the time to understand that design pattern and would be grateful for any solid introductory textbook(s) references on it.

What M is advertised to do (mash up divergent data sources more or less "on the fly") is exactly what I have to do every day for work. Power Query (and M functions) initially struck me as "yet another SQL front end trying to be easier to use but in the long run just trouble".

Ultimately I need to marry RDF linked type data into the analysis mix. SPARQL strikes me as very important for analysis work, but left out of the domain of F#, M, Power Query, etc. R is another big player in the investment analysis space. Excel and VBA have been remarkably durable for quick and dirty (and constantly changing) on-the-fly financial analysis, but I admit it appears its model seems pretty "entrapped" and somewhat dated in its roots as a two dimensional spreadsheet. Bottom line, are you aware of any good "mashup environment" that can grind relational data, R style data, and linked (RDF) style data. Perform intelligent or "assisted" Extract, Transform, Load functions? Then spin the data around and reduce it? Here is and example of a difficult aspect of data "mashup" in my financial/economics world: aligning identifiers across databases. It seems ultra "mundane" from a data science / language designer prospective initially, but is actually a huge impediment to better analysis. — Preceding unsigned comment added by (talk) 21:00, 23 June 2016 (UTC)

Developers typically understand design patterns as a particular practice in object oriented programming, popularized in the Gang of Four book. I use the term here in a loose way, meaning a particular abstract way to structure programs (but unrelated to the tradition in OOP).
According to that PDF, PowerQuery is a "mostly pure, higher-order, dynamically typed, partially lazy functional language"; with immutable values. So yes, you get a good feeling of how data transformations are done in a functional style: a spreadsheet-like model, where many nested expressions are evaluated to produce a final value. For programming more complex systems, though, you have to learn how to define machine states, which in functional style is quite different than in imperative style.
The essence of functional programming is using functions without side effects, which communicate only through their input parameters and return values. Pure functional programming forbids any kind of assignments; data structured are never modified in place, instead you build a new changed data structure by copying or linking parts of the old one.
This radical departure from imperative programming carries a lot of idioms that you have to learn to be fluent in this paradigm; most of them involve ways to handle complex accumulator parameters in the interface of your recursive functions (in short, any side-effect that you would accomplish with a method call or assignment to a global variable must now be declared in the function parameters). I would start with a good tutorial of recursive programming in your preferred functional language, be it F#, Haskell or Lisp. The Little Schemer is a good resource for an in-depth view.
For data transformation, I've heard of NoFlo JS; I haven't used it, but I've used a similar language in the past. Or you could learn a simple dataflow programming language like Elm (programming language). Diego (talk) 09:23, 24 June 2016 (UTC)
And if you want a cleanup application rather than a programming language, you have OpenRefine (formerly known as Google Refine). Diego (talk) 14:36, 24 June 2016 (UTC)

Diego, Can't thank you enough for the really great references! Excellent! I'm starting with The Little Schemer and very much look forward to a trip back to the 70's for and updated visit to LISP and PROLOG. I obtained the book and read the preface:

In fact, The Little Schemer is based on lecture notes from a two-week "quickie" introduction to Scheme for students with no previous programming experience and an admitted dislike for anything mathematical. Many of these students were preparing for careers in public affairs. on!

I looked at noflojs but my VC investment background haunts me, and I'm not sure that particular entity is viable? From the point of funding these things typically follow a 5 year "J" curve. First "down" for a few years (into the pit "heavy lifting" and despair), having underestimated the effort they blow through the VC cash and unless they are very slick salesmen and can sell their souls and raise more cash (and that follow on / rescue equity comes "priced" including several offspring, fingers and toes!) they are SOL. So far as a "proxy" for excitement and buzz I read the number of comments: 40,16,8,0 for 2013,2014,2015,2016. That (admittedly very limited solo) indicator is clearly flashing crash and burn. Videos struck me as Millennials off in the weeds, a few bright bulbs for the future but far from a cohesive product development team. I do however get and like the concept. Reminds me a little of ApGen - a program generator that hooked things together visually, however when it screwed up it was more effort to figure out where, vs using much more conventional programming from the ground up. While the overall concept was seductive the reality was it wasn't actually productive.

Will pass on Elm (Excel/VBA runs counter to Javascript in my mind, no fault of JavaScript - and I wish VBA would transition to it, but that isn't going to happen). Python is also real popular in the GIS world - a key input to financial analysis and wouldn't it be great to have one quick and dirty script language that did it all and hooked to all?

Will take an intense look at OpenRefine. The features look really nice, especially: moving semi-structured data-to cleanly structured, normalizing, DOM, json, and especially RDF triples. Its been surprising in my work (investment analysis) that 80% of my day is consumed just as a data plumber - hooking up the "pipes" to innumerable and constantly changing data sources (always striving to plumb to the "gold copy" of data i.e. the ultimate source, the one that is most authoritative, and most frequently accurate and updated).

Major worldwide events occur (very unpredictable) and many of the primary data sources suddenly change. So, its a quick learn, and quick pipe hookup - all to change in a few months. I take a "dumbbell" approach to it - on one end try to spend some time on the "theory end", understanding the vocabulary and concepts, and design patterns. Skip everything in between. Then, on the other end, just apply very quickly any application that delivers "close" to what you want and be quick about it! Don't get too embedded in those aps and data sources. If there is an application that takes you "close" that is already written and reasonably tested, just use that. This is probably why Excel has remained entrenched. As long as its a quick and dirty tool that works, it will likely remain popular.

I wonder why Google took OpenRefine off their list of technologies they want to invest heavily in, and possibly control? Surely they have "data mashup" high on the list of internal to do's? I'd assume its desperately and constantly needed to support many departmental objectives at Google. I can't really imagine them going with M$FT's F#.

Hopefully our discussion here is illuminating to an article on Functional Programming for beginners like me (which I assume there are and will be many. Perhaps too, observing people "struggle" with the concepts is also stimulating in thinking up ways to make it more accessible and less "math like" lol.

Thanks again for the terrific references, very much appreciated. — Preceding unsigned comment added by (talk) 19:52, 28 June 2016 (UTC)

2016 lead paragraph[edit]

The lead paragraph was too much focused on the practical/engineering side of the monads. I tried to make the presentation more rigorous and accessible, taking a more abstract perspective and using basic concepts (property, instance, data type, etc). Nxavar (talk) 14:04, 8 September 2016 (UTC)

Thanks, Nxavar. I feel that your new introduction fails to provide an accessible overview for a general audience, and in particular it fails the requirement that the first sentence describes the topic for a nonspecialist reader without being too specific. Starting with the practical side is a way to make the article understandable; IMHO an abstract approach should appear later in the lead section, since most people will not have the knowledge required to ground those abstract terms into their everyday experience. See the guideline Wikipedia:Make technical articles understandable, and in particular "The lead of the article should tell a general reader the field of study of the topic, the place the topic holds in its field of study, what (if anything) the topic is good for, and what needs to be learned first in order to understand the article"; I find it easier to convey the gist of the article to the general reader by explaining what monads are good for, rather than how they are programmatically constructed, since most of our readers will have no knowledge of programming languages theory, even those with a programming background.
I've tried to move your abstract description further down in the lead paragraph, although I'm not sure it's entirely correct; I've never heard monads being described as properties of polymorphic types (and "polymorphic type" is anything but a basic concept). In particular I find the following sentence unreadable: "...a series of steps which result in applying in an ordered fashion the additional processing defined in a series of monad data type instances, without violating the referential transparency and lazy evaluation principles" - even though I know what are the referential transparency and lazy evaluation principles, which most readers won't. I've restored most of the previous version and tried to include your definition in it. Diego (talk) 15:49, 8 September 2016 (UTC)
Thank you for the constructive feedback and editing on my rewrite. On second thought, I don't think it's important to describe the pipeline using CS terminology. I was trying to highlight how the use of monads can bring ordered computation and state in a paradigm that actively avoids them.
Although particular monads such as "Either" and "Option" are straightforward, monads are certainly an advanced concept in functional programming. Doing a search in google books, neither Odersky's "Programming in Scala" or the apparently advanced "Scala in Depth" from Manning, define what a monad is in rigorous terms. They treat it from a software engineering perspective, which is understandable. However, not knowing how monads are defined means a) you have to take by the argument from authority of the authors that this and that are monads and b) you cannot build you own monads. The obstacle to being rigorous about monads is that they are quite sophisticated, and you need some theoretical background for a formal description.
However, I think the lead paragraph and the lead sentence in particular were problematic since they gave a software engineering assessment to a rigorously defined PL construct. I believe that in Wikipedia we should give the scientific description, even a general one, before going to the engineering significance, as is normally done in mathematics and physics. The monad is more of a scientific term rather than a technical concept as it originated from CS academics instead of SE academics or programming practice. The situation is better now though. Nxavar (talk) 07:30, 9 September 2016 (UTC)

merge from bind[edit]

I removed the following from the bind disambiguation page, so it can be merged with (say) this article. Please feel free to merge.

  • When using monads in functional programming, bind is an operation of monads. A simple example (enabled by the fact that sets can be regarded as monads as well): Let A be a set, , , then , thus, f is applied pointwise and the union of the intermediate results is returned.

Widefox (talk) 10:38, 7 November 2008 (UTC)


Moving this comment from the article's body so that it can be discussed..Diego (talk) 18:13, 6 December 2008 (UTC)

"to define arbitrary control flows (like handling concurrency, continuations, or exceptions)." Are they really that general? What, then, are monoids and arrows for? My understanding was that they described more general computations but had fewer laws one could reason with.

Monads support some arbitrary control flows, not all them. Arrows allow some more flows (for example, non-deterministic concurrency) which is not supported by monads Diego (talk) 13:46, 19 October 2009 (UTC)

Haskell Syntax?[edit]

One problem I had reading this was that the article seemed to assume familiarity with Haskell syntax. In particular, unless you know something about the precedence and associativity of the Haskell operators used in the code, then some of the discussion can be unnecessarily confusing. For example, is -> left-associative? commutative? what about >>=? The use of parentheses in the binding axiom seems to suggest that these issues are important, but the reader has no way of determining the answer. I am not entirely sure how to fix this problem, since certainly this is the most comfortable notation for most of the authors of this page. On the other hand, it runs the risk of being a page that can only be read by people who don't need it. Perhaps I'm over-thinking this and just adding a bunch of extra parentheses would solve the problem (even if the added parentheses would be non-idiomatic in normal use of Haskell). --Rpgoldman (talk) 22:17, 15 April 2009 (UTC)

I agree: the use of Haskell notation is OK, but it would hell if the notation used was defined as part of the article so as to make it self-contained for people who don't know Haskell but still want to know what all the fuss is about. --DamianCugley (talk) 14:04, 16 January 2010 (UTC)
DaminCugley, my guess is that the 'hell' above really means 'help'. True? --Ancheta Wis (talk) 12:37, 17 January 2010 (UTC)

Binding example and axioms[edit]

I found the initial description of the binding operation, with its four stages very intuitively appealing, but as I carried on in the article, I became confused. The problem for me is that in the third clause of the definition, binding is defined as taking a monad of underlying type t and a function t(M u) and returning a value of type (M u). This seems clear enough. However, in the axioms section, all of a sudden we are told about binding two functions in succession, without any explanation of what this means. It may be that the use of Haskell notation here is just confusing me --- I would be happier if the axioms were presented in familiar mathematical notation instead of unfamiliar Haskell notation (see my remarks earlier on this page). I may further be confused by the (to me) very odd use of the term "binding," which I am familiar with from other functional programming contexts as being something that happens to variables... Quite possibly a concrete example would make this all crystal clear. --Rpgoldman (talk) 22:29, 15 April 2009 (UTC)

Very difficult to understand[edit]

Even for someone with a bachelor's in computer science/informatics, this information is prohibitively difficult to understand. Yes, it is true that Monads are a difficult concept. However even if one can understand everything this article is saying (bind/>>=, return), the big picture just isn't presented in this article. It is full of convoluted examples.

Some important questions that need to be addressed early and in their own sections:

  • Why do people think Monads are so important? What wouldn't you be able to do without Monads
  • What are the thing Monads can be used for? e.g. common examples: IO, nondeterminism via lists, etc.
  • Do Monads have analogs in other functional languages? LISP?
  • In the definition of a Monad, is the overlay of types one-to-one? For example, is it okay not define Monad(Type) for some Type? Or must it work for all types Type?
  • This article should use less single-letter variables and more variables with actual names. This is not abstract math that needs tons of footnotes to define variable meanings, even though it is linked to category theory.
  • There is always a tradeoff in defining something. What advantages does defining a type as a Monad give one, as opposed to just defining a generic type-constructor. What are the nifty things one can do? For example, what would happen if Bind did not exist? If Return did not exist? Without return, there would be no way to link the new monadic types with the previous types you've defined... right? Or maybe wrong...? What about Bind? —Preceding unsigned comment added by (talk) 23:52, 4 May 2009 (UTC)

Someone should really add this article to some list of articles needing revision, or email the Haskell mailing list.

Agree - this needs a rewrite with better examples - the current examples, which keep referencing stuff that will be defined "below", don't make sense. —Preceding unsigned comment added by (talk) 15:18, 22 November 2009 (UTC)

User:Diego Moya has kindly addressed some of your concerns. Please read the Moggi citation for more information and motivation. You might also read Andrew D. Gordon, Functional Programming And Input/output. See for example Gordon's pages 2-5 for a summary.

(Additional note added 22:48, 16 January 2010 (UTC)) Andrew Gordon has noted that Lisp 1.5 categorized its I/O as "pseudo-functions". Gordon documents that Moggi solved this problem 20 years ago, which is critical for functional programming, using the Monad machinery, as detailed in the links above. Gordon's thesis demonstrates how this can be done. These comments are properly part of the history of Haskell.

Please add your comments to the foot of the page so that talk can be read in temporal order. --Ancheta Wis (talk) 12:42, 24 November 2009 (UTC) Reiterated this request. --Ancheta Wis (talk) 12:37, 17 January 2010 (UTC)

Axioms section[edit]

The "mathematical notation" definition of the axioms had "lift" instead of "return". If my hazy recollection of the monad rules is correct, then the two should be the same, but return is used in the rest of the article, while lift is not, so I edited it. If this is mistaken, could we explain what lift is instead of simply using it?

See Lift (mathematics): " In the branch of mathematics called category theory, given a morphism f from an object X to an object Y, and a morphism g from an object Z to Y, a lift (or lifting) of f to Z is a morphism h from X to Z such that gh = f ". Apparently the discipline owes more to Andrew Gordon's Ph.D. thesis (1992) than is currently acknowledged by the article. You can search for "lift" in the link above, which has been recognized as a distinguished dissertation in CS. --Ancheta Wis (talk) 04:57, 17 January 2010 (UTC)

The axioms section states that "return must preserve all information about its argument." By the axioms given, I don't think this is strictly true. For example, the monad with zero where return x = mzero, i.e. the trivial monad where everything is mapped to the zero value is still a valid monad, but clearly return preserves no information at all. (talk) 04:31, 11 June 2010 (UTC)

Yeah. Very bad wording. Perhaps it could make sense to formalize the axioms using
>=> :: Monad m => (a->m b) -> (b->m c) -> (a->m c).
We'd then have f >=> return == f, and return >=> g == g. I.e. return is just extactly a neutral element of >=>. Next, we'd have to say that >=>, with the type argument a specialized to (), is the same as >>=. (Well, almost.) --Daniel5Ko (talk) 21:29, 21 June 2010 (UTC)
I've always thought >=> is better for intuition of the idea behind monads than >>=. Notice that the two are equivalent, since f >=> g = \x -> f x >>= g and m >>= f = (id >=> f) m -- benmachine (talk) 16:24, 15 February 2011 (UTC)

Notes on introduction[edit]

The second sentence in the introduction is not grammatically correct. I'm inclined to delete the entire sentence because the remainder of the paragraph is clearer without it. If necessary the notation introduced could be introduced in the following paragraph where a formal definition is proffered.

If  is a monad, element of  is a computation of a value of type . (talk) 22:28, 20 July 2010 (UTC)

After removing the offending sentence from the first paragraph, how about using something in the following paragraph like:
"If m is a monad, a computation of a value of type a could be represented by m a."
--Ancheta Wis (talk) 00:02, 21 July 2010 (UTC)

Section 3.1, item 1, gives the same definition, so I don't think we need to have it in the introduction at all since the notation isn't used in the intro. (talk) 16:05, 22 July 2010 (UTC)

mBind instead of >>= ?[edit]

The whole article uses >>= for the binding operator, except in this example:

mBind :: Maybe a -> (a -> Maybe b) -> Maybe b
(Just x) `mBind` f = f x
Nothing `mBind` f = Nothing

Is there a reason for that?

Bartosz (talk) 20:46, 27 October 2010 (UTC)

AFAICT, no. One could think that this stems from the fact that in order to use/define the normal >>= in Haskell, one has to declare a class instance. So, if you want to define that function without the type class instance distraction, you have to use a different name.
But, the other examples don't follow that reasoning and pretend that a simple definition of >>= works. So should the Maybe-example, I think (after all, we are trying not to talk specifically about Haskell). Feel free to modify it. --Daniel5Ko (talk) 21:55, 27 October 2010 (UTC)

Haskell formatting[edit]

I started re-formatting Haskell code samples using the <source lang="haskell"> tags, but the result is pretty disgusting. Are these colors picked randomly from some hideous palette? Would it make sense for the Haskell formatter to replace ASCII symbols, such as -> => \ (lambda) with the more math-like notation?

Bartosz (talk) 21:01, 6 November 2010 (UTC)

Do Haskell programmers actually use the unicode symbols much in practice? --Cybercobra (talk) 21:31, 6 November 2010 (UTC)

Dead link: reference 3: A physical analogy for monads[edit]

Reference 3, "A physical analogy for monads, explains monads as assembly lines." points to

which is a dead link (2011/11/15). — Preceding unsigned comment added by (talk) 19:08, 15 November 2011 (UTC)

Suggestions for making article clearer[edit]

Speaking as someone who understands monads and monad transformers, I have to say that this article makes the concept far more difficult to understand than it needs to be. Specific issues include:

  • The introductory examples come after the formal definition, rather than before, which drives off readers and loses motivation for defining such an elaborate structure.
  • The first actual example on the page uses the Maybe monad, rather than the IO monad, which, while more complicated to implement, is very easy to describe in terms of sequencing actions.
  • The definition section mentions object oriented programming and callbacks, which have nothing to do with monads. The general concept of a monad cannot even be expressed in most OO languages, because they don't have higher-kinded type variables.

I might get the chance to work on the article later. « Aaron Rotenberg « Talk « 13:37, 25 May 2012 (UTC)

Ironically, I felt less intimidated after reading the comments by people complaining they couldn't understand the article. What I thought I was reading, and perhaps I can be forgiven for this, is yet another Wikipedia computer article which made perfect sense to people who knew and loved the topic, but was full of off-topic details, and arcane vocabulary. Now, having read the comments, I realized what had been accomplished. Having invested now 5 minutes in trying to understand the concept I now believe a monad is used as a skeleton to define program control structures. Whether that is "exactly" true or not, I still want to know two other things in the opening paragraphs. (And I absolutely do not want to hear about someone's idea of what "formally" is, which in a computer context immediately says to me: uber-geeks only need apply.) What I want to know is: What does a monad stand in lieu of? A program specificiation? A flowchart? And if, indeed monads are used to structure procedures, how do they make the transition into code? Or is this whole thing basically handwaving along the lines of "try thinking in this frame of reference, 'cause we think it has a lot of advantages?" (talk) 11:38, 3 June 2012 (UTC)
Actually, your comment does a great job of revealing what the fundamental problem with most explanations of monads is. Most descriptions try to assert thast monads are a control structure, or something that can be expressed in imperative terms. These descriptions aren't really helpful. Here's the thing: fundamentally, the concept of a "monad" means nothing whatsover. There's a reason category theory is called abstract nonsense—you're finding and describing commonalities and abstractions between things that have no intuitive connection.
Saying that a particular type is a monad (that is, has a canonical monad structure) means about as much as saying that a particular relation is associative or commutative. Actually, a much closer analogy is saying that a set is a group under some particular operation. It tells you that the type has a certain structure, and that it has some useful properties with respect to that operation. But it doesn't tell you anything beyond that.
The best analogy I've found for explaining monads is that a type with a monad structure behaves like an "action" that produces a value. Not (necessarily) an "action" in the imperative sense, or an "action" in the object-oriented sense, or an "action" in any sense that is otherwise familiar. It just satisfies certain properties that you would intuitively expect anything called an "action" to have. Two such properties are:
  1. For any value, you can always get an action that does nothing and returns that value.
  2. For any action that produces a value of type A, and any function which takes a value of type A and chooses an action that returns a value of type B, you can get an action that returns a value of type B. This action sequences the two together by performing the first action, passing its result to the function, performing whatever second action it spits back, and returning the final value.
Another thing that helped me was an example that is rarely brought up: the "set" monad. This is the monad of nondeterministic computation, where a computation results not in a single concrete value, but in many possible "parallel universe" paths, some of which may branch more deeply, and others of which may fail and result in no possible subsequent paths at all. As the article notes in passing, this is not technically a monad in Haskell, because we need an instance of the Ord typeclass to have a set. But it is a monad in pure mathematics, since every mathematical type has an equality operation defined on it. If you've learned about DFAs and NFAs in an automata theory class, you will immediately grasp the concept of this monad.
(I'm still threatening to work on this article at some point...) « Aaron Rotenberg « Talk « 05:09, 4 June 2012 (UTC)
Also, your description of monads as "try thinking in this frame of reference, 'cause we think it has a lot of advantages" is actually spot-on. It is not, however, mutually exclusive with transitioning the style of thinking into code. That's the entire point of type classes, and of abstraction in general—taking things with certain common properties or structures, and allowing you to define additional structure on top of the common properties rather than redefining it for every place where it occurs. « Aaron Rotenberg « Talk « 05:21, 4 June 2012 (UTC)

The state monad is, technically, not a monad in the sense of the definition. This has to be cleaned up. — Preceding unsigned comment added by (talk) 18:31, 26 August 2012 (UTC)

Alternative formulation[edit]

Just in case - all statements in this post should be read as if they were preceded by an implicit "I think that...", especially so if you feel they are too extreme.

The main reasons why anyone would read an article like this are - 1. to learn how monads are used in functional programming, 2. to use as a resource to give to someone interested in (1). Furthermore, a presentation of how monads specifically are used in functional programming is not terribly useful if it does not convey the message that not just monads but many algebraic structures are incredibly useful as building blocks for programs. Unfortunately, the presentation of monads in this article is not very elegant, and is thus likely to give the reader the impression that learning monads (and algebraic structures in general) is not worth the hassle. In order to fix this, I propose two changes.

The first change is defining the signature for monads in terms of pure/return and join:

class Functor f where
    map :: (a -> b) -> f a -> f b

class (Functor f) => Applicative f where
    pure :: a -> f a
    ap   :: f (a -> b) -> f a -> f b

class (Applicative m) => Monad m where
    join :: m (m a) -> m a

While bind is certainly more useful than join in actual programming, join is conceptually a more "atomic" operation - it just allows for escaping a nested monadic context. On the other hand, bind is weird, because it actually does two things - it lets values escape a monadic context, but only for the purpose of feeding them to a function that returns a monadic context of the same type (constructor). Just spitting this out made my head hurt, so let us not talk about actually understanding it.

Of course, after we are done defining monads, we can define bind:

-- See below for the definition of Kleisli.
(>>=) :: m a -> Kleisli m a b -> m b
f >>= g = join (map g f)

The second change is defining the monad laws in terms of Kleisli arrows, rather than in terms of monads themselves. Kleisli arrows have the advantage of making it obvious why the monad laws are called "left identity", "right identity", and "associativity" - the formulation in terms of monads makes this less easy to immediately see.

-- WARNING: This snippet is actually not legal Haskell.
-- But I would rather be truer to the actual mathematical definition,
-- so I have attached the (Monad m) constraint to Kleisli's definition,
-- rather than to every function taking or returning Kleisli arrows.
type (Monad m) => Kleisli m a b = a -> m b

(>=>) :: Kleisli m a b -> Kleisli m b c -> Kleisli m a c
f >=> g = join . map g . f

(<=<) = flip (>=>)

-- Now the monad laws are trivially
--               f = f >=> pure
-- pure      >=> f = f
-- (f >=> g) >=> h = f >=> (g >=> h)

But we can go one step further! Kleisli arrows are actually the arrows of a category whose objects are Haskell types. In order words, what we have is a legitimate Category structure:

class Category arr where
    id  :: arr a a
    (.) :: arr b c -> arr a b -> arr a c

instance Category (Kleisli m) where
    id  = pure
    (.) = (<=<)

And we have finally arrived to the simplest possible formulation of the monad laws - one must be able to build a Kleisli category from them. Now, it is no surprise that the monad laws and the category laws have the same names: "left identity", "right identity", and "associativity"! --Eduardo León (talk) 21:48, 6 January 2013 (UTC)

I respectfully disagree. This article should primarily be target at (functional) programmers and, as you yourself note, when using monads in a programming situation it is rarely more convenient to define your monad in terms of fmap and join instead of return and bind. It think using a non-standard signature would only end up confusing the reader, if he or she already has some background knowledge or when trying to apply the material learned here. That said, I do think the "fmap and join" section could use some improvement and expansion. —Ruud 15:08, 6 January 2013 (UTC)
The main purpose of my formulation is to make it easier for the reader to understand what monads (in platonic Hask) are. The formulation in terms of pure/return and join makes this easier - no surprise, because it is actually mathematically more elegant. The formulation in terms of pure/return and bind is an optimization - useful for people who already understand monads and want to avoid creating nested nested monadic contexts, but not very helpful to people who do not yet know what monads are. Let me give an analogy: If you perform a non-obvious optimization in your code, you should write in a comment the more evident non-optimized version, and then explain how to derive the optimize version from it, by applying correct program transformations. This very concept could be applied to this article as well. --Eduardo León (talk) 21:48, 6 January 2013 (UTC)
Yes, but I think most readers of this article are primarily interested in what they can do with monads—we already have Monad (category theory) for those who prefer a theoretical description over a practical one. I also think that the bind operator, as a "programmable semicolon" appeals more to the intuition of the average programmer than the fairly abstract join operation. Finally, I've defined many monads in terms of bind and return in production code, while definitions in terms of join and fmap never went beyond tinkering; the former is the definition the reader is most likely to encounter in the wild. —Ruud 19:38, 7 January 2013 (UTC)

This one link is 100x better at explaining monads than all of the gobbledygook in this article[edit]

Doubledork (talk) 19:50, 1 February 2013 (UTC)

Agreed --Surturz (talk) 22:41, 21 February 2013 (UTC)

Monads as Modular denotational semantics[edit]

This page don't have the original meaning of monad by Eugenio Moggi. Moggi proposed a method of implementation of language with modularity in the monads theory. For example,

In the monad theory, the special feature is regarding "programs" as arrows of Kleisli category. I would like to write these description --I.hidekazu (talk) 02:35, 18 May 2013 (UTC)

Writer monad in Javascript[edit]

While it think this new section is a very good idea in principle (both using the Writer monad as a motivational example, as well as using a language that is not Haskell to state it), I think the current implementation should be substantially improved:

  1. The section is mostly code, and is missing any kind of useful explanation around it.
  2. tell is not defined anywhere, missing the opportunity to introduce Kleisli arrows.
  3. squared and halved are not really monadic functions, as they construct their results directly instead of using a monadic interface (unit and tell).
  4. I think the pipeline function just obscures things. I would at least move both its definition and use to the end of the section and give an example that uses bind directly before it.
  5. It would probably be nicer to use an objects with two fields instead of an array to model the monadic value.

Ruud 21:18, 4 July 2013 (UTC)

You're welcome to expand the section in those directions. Note though that the implementation follows the one available in the reference, which provides a good introduction to the topic as it introduces the 'bind' and 'unit' operators in a simple way, and that the Javascript example is intended for programmers less experienced in functional style. Any addition for clarity should be provided as an expansion to the current code, not replacing it. Let's the desire for strictness not hurt the need for clarity. (And I'm not sure how you can create the type constructor in Javascript?). Diego (talk) 21:27, 4 July 2013 (UTC)

bind example looks more like fmap ((a -> b) -> f a -> f b) than bind (m a -> (a -> m b) -> m b) —Ungzd (talk) 00:25, 8 November 2014 (UTC)

tell is not a part of monad definition. Kleisli category does not have any 'tell' either. Arrows definitely deserve a separate article (with a link from here).

Monad vs continuation and function composition[edit]

I feel continuation and function composition was there before monads was. May the article is missing something about how monad and continuation relates.

This excerpt, looks dubious to me:

Many common programming concepts can be described in terms of a monad structure, including side effects such as input/output, variable assignment, exception handling, parsing, nondeterminism, concurrency, and continuations. This allows these concepts to be defined in purely functional manner, without major extensions to the language's semantics.

Isn't it the other way? Aren't monad a particular application of continuations and function compositions? --Hibou57 (talk) 21:23, 5 September 2013 (UTC)

I'm in no way an expert, but that continuations existed first doesn't make that assertion false. A monad is a mathematical construct, and it can be used to implement continuations in a domain-specific language. Conversely, you can implement monadic do-blocks using continuations. This only means that both programming structures are fairly expressive, not that one is always the foundation of the other by definition. Diego (talk) 23:00, 5 September 2013 (UTC)

This article is useless to people who do not already know haskell. — Preceding unsigned comment added by (talk) 15:27, 11 September 2015 (UTC)

We should dehaskelize it[edit]

There's a big problem with this article. It's all Haskell. That's not good. We have to be more abstract. Maybe write a bunch of paragraphs regarding how a monad looks like in Scala, Java, JavaScript, C++, Rust, C#, etc. Vlad Patryshev (talk) 19:27, 4 January 2017 (UTC)

Haskell is a huge contributor to the use of monads in functional programming, so it's logical that many sections are based on documentation written in it. (Some may say that writing in Haskell is being "more abstract"). We have examples in Javascript and F#. If you know of references that document the usage of monads in those other languages, by all means bring them here and we'll figure out the best way to include them in the article. Diego (talk) 09:55, 5 January 2017 (UTC)
A Haskell-oriented explanation would be OK if it also explained enough Haskell details used so readers needn't already know Haskell to follow along. Grokking monads is difficult so we can't really expect readers to simultaneously make lots of successful inferences about Haskell. This is doubly important since you can't get far in Haskell in turn without understanding monads.
Please explain the syntax used, also its precedence (or use enough parentheses to avoid that). Are newlines significant? What determines which monadic type's Just, return, or >>= get called in presented example expressions such as Just 10 // Just 5? Type classes, parameterized types, operator overloading, type inference, (), ... What's the relationship between Just, unit, and return? When the article says “a monadic value: M a”, is that really a variable, a type, or both?
An alternate way to explain monads would be in a more familiar programming language. Using an object oriented language would answer the question of which Just and bind get called, but it ought to be a language where types are first class values like JavaScript, Ruby, or Smalltalk.
That said, this page has improved dramatically over the last few years. (talk) 01:55, 12 January 2017 (UTC)
I'm afraid explaining the syntax of Haskell is outside the scope of this article. What it could do is better identify what features of the language are used in each example (enumerated types, pattern matching, etc).
Adding examples in imperative languages wouldn't be a good idea, methinks; monads and object-orientation don't mix well, as the contrived Javascript example shows. IMHO one should have at least a basic grasp of functional programming before trying to understand monads; this is the scope where they are more useful anyway.
In imperative languages you can use mutable state, so one of the main selling points of monads for strict functional languages is not needed there. And the other uses, for handling data structures and control threads, would require a syntax in an imperative language too awkward to be useful. Diego (talk) 13:29, 12 January 2017 (UTC)

External links modified[edit]

Hello fellow Wikipedians,

I have just modified one external link on Monad (functional programming). Please take a moment to review my edit. If you have any questions, or need the bot to ignore the links, or the page altogether, please visit this simple FaQ for additional information. I made the following changes:

When you have finished reviewing my changes, you may follow the instructions on the template below to fix any issues with the URLs.

You may set the |checked=, on this template, to true or failed to let other editors know you reviewed the change. If you find any errors, please use the tools below to fix them or call an editor by setting |needhelp= to your help request.

  • If you have discovered URLs which were erroneously considered dead by the bot, you can report them with this tool.
  • If you found an error with any archives or the URLs themselves, you can fix them with this tool.

If you are unable to use these tools, you may set |needhelp=<your help request> on this template to request help from an experienced user. Please include details about your problem, to help other editors.

Cheers.—InternetArchiveBot (Report bug) 19:46, 5 April 2017 (UTC)

More Haskell and the image in the lead[edit]

Sixth root as a composite function of cbrt and sqrt.svg

The structure that defines the input type and how to compose the different actions together is a monad.

The complex multivalued square and cube root functions may be composed with the "bind" operator "•" so they produce the sixth root function. Here z is a complex number, and the square brackets denote an array.
  • unit(z) := [ z ]
  • (fg)(z) := append(map(f,g(z)))
  • lift(f) =  := unitf = funit
  • sqrt°(z) =
  • = append(map(unit,sqrt(z)))
  • = append(map(sqrt,unit(z)))
  • sxrt(z) = (cbrt°sqrt°)(z) = append(map(cbrt°,sqrt°(z)))

@Diego Moya: you wrote about the lead image It doesn't say how the structure correlates to the monad's return and bind operators. That's true; monads aren't just a concept in Haskell and that diagram represents a monad that's not in Haskell... Now I'm not going to suggest splitting the article into Monad (Haskell), but the lead has to acknowledge that Haskell's operators aren't the definition of a monad, and if the diagram describes a monad without relating it to Haskell it shouldn't be ruled out... Bright☀ 15:05, 9 May 2017 (UTC)

The bind and return operators are the name of the monad-defining operators in Haskell, but they are not exclusive from Haskell. The section Formal definition defines a monad with a type constructor, unit function and binding operation. The structure in the image should be explained in terms of these mathematical constructs for relating it to monads in functional programming. I reiterate here my concerns that, without a proper explanation, the image looks like an arbitrary selection of mathematical formulas, and it remains unclear how these relate to the topic of the article. How do we know the image represent a monad and not, say, a set, a lattice, or a directed graph? Diego (talk) 15:47, 9 May 2017 (UTC)
How do we know the image represent a monad and not, say, a set, a lattice, or a directed graph? 'cause the description says "The structure that defines the inputs, outputs, and how to compose the different actions together, is a monad." Bright☀ 20:09, 9 May 2017 (UTC)
Well yes, but then we need to trust the editor saying so, and we can't verify it by ourselves. It doesn't improve our understanding of what a monad is. Diego (talk) 05:40, 10 May 2017 (UTC)
It improves the reader's understanding since it gives a concrete (visual) example of what monads "do". It's not a standalone replacement for the entire article... Let me give you different examples. What the hell is the diagram on the left for? It's just a couple of ellipses and horizontal lines and three arrows. But if you throw in a description, "The bar and ring paradox is an example of the relativity of simultaneity. Both ends of the bar pass through the ring simultaneously in the rest frame of the ring (left), but the ends of the bar pass one after the other in the rest frame of the bar (right)", it becomes an example of the relativity of simultaneity. You can't verify it without the description because it's just a bunch of symbols, but that doesn't mean it doesn't improve the reader's understanding. For all of this, a reader who's never seen an apple can't verify that a photo of an apple is a photo of an apple if it doesn't have a description saying that it's a photo of an apple, accompanied by an article that describes what is an apple.
Anyway I'm not going to pursue it further. Bright☀ 06:17, 10 May 2017 (UTC)
The key in that second example is that it contains the sentence "ends of the bar pass through the ring simultaneously in the rest frame of the ring (left), but the ends of the bar pass one after the other in the rest frame of the bar (right)". I.e. it explains the parts of the image in terms ot the topic. I agree it would be useful having a visual example of the monad, but it needs to be explained with a similar sentence detailing the elements in the image. (The current explanation mentions inputs and outputs, but those are not part of the monad). Diego (talk) 06:24, 10 May 2017 (UTC)
@Diego Moya: I've tried making the structure of the monad explicit, please inspect. Bright☀ 16:51, 11 May 2017 (UTC)

──────────────────────────────────────────────────────────────────────────────────────────────────── Thanks, that's the kind of detail I was talking about. Something similar to that image could be a good addition to the lede.

I still don't understand how the structure is a monad from that image, though. The binding operation is a binary function that returns one value, though the arrows for bind in the image make it have one input and two outputs. Is this an instance of currying? In the same way, the unit function return takes on parameter, yet the box in the image takes two inputs. Could you make the labelled boxes map to the parameters in the formal definition of the monad? Diego (talk) 07:55, 12 May 2017 (UTC)

Sorry, I put bind and return instead of map and append... I'll fix it. Bright☀ 16:04, 12 May 2017 (UTC)
Made the description explicit, but now it's very long. Bright☀ 21:32, 12 May 2017 (UTC)