First: The term monad is a bit vacuous if you are not a mathematician. An alternative term is computation builder which is a bit more descriptive of what they are actually useful for.
First: The term monad is a bit vacuous if you are not a mathematician. An alternative term is computation builder which is a bit more descriptive of what they are actually useful for. You ask for practical examples: Example 1: List comprehension: x*2 | x>= operator.
A monad is basically just a type that supports the >>= operator. Example 3: A parser This is a very simple parser which parses either a quoted string or a number: parseExpr = parseString parseNumber parseString = do char '"' x >= in Haskell). Since the bind operation combines functions, it can execute them as it sees fit: sequentially, multiple times, in reverse, discard some, execute some on a separate thread when it feels like it and so on.As an example, this is the expanded version of the IO-code from example 2: putStrLn "What is your name?
" >>= (\_ -> getLine) >>= (\name -> putStrLn ("Welcome, " ++ name ++ "! ")) This is uglier, but it's also more obvious what is actually going on. The >>= operator is the magic ingredient: It takes a value (one the left side) and combines it with a function (on the right side), to produce a new value.
This new value is then taken by the next >>= operator and again combined with a function to produce a new value. >>= can be viewed as a mini-evaluator. Note that >>= is overloaded for different types, so every monad has its own implementation of >>=.
(All the operations in the chain have to be of the type of the same monad though, otherwise the >>= operator won't work. ) The simplest possible implementation of >>= just takes the value on the left and applies it to the function on the right and returns the result, but as said before, what makes the whole pattern useful is when there is something extra going on in the monads implementation of >>=. There is some additional cleverness in how the values are passed from one operation to the next, but this requires a deeper explanation of the Haskell type system.
Summing up In Haskell-terms a monad is a parameterized type which is an instance of the Monad type class, which defines >>= along with a few other operators. In layman's terms, a monad is just a type for which the >>= operation is defined.In itself >>= is just a cumbersome way of chaining functions, but with the presence of the do-notation which hides the "plumbing", the monadic operations turns out to be a very nice and useful abstraction, useful many places in the language, and useful for creating your own mini-languages in the language. Why are monads hard?
For many Haskell-learners, monads are an obstacle they hit like a brick wall.It's not that monads themselves are complex, but that the implementation relies on many other advanced Haskell features like parameterized types, type classes, and so on. The problem is that Haskell IO is based on monads, and IO is probably one of the first things you want to understand when learning a new language - after all, its not much fun to create programs which doesn't produce any output. I have no immediate solution for this chicken-and-egg problem, except treating IO like "magic happens here" until you have enough experience with other parts of language.Sorry.
1 Thanks for the very thorough answer. I've been trying (and thus far failing) to learn about monads for a long time now, and this has done a lot to clear up several concepts. In particular, the concept of >>= being a shortcut to chain functions is much clearer to me now.
– friedo Mar 15 '09 at 3:26 8 Really, really helpful answer! I wish I could upvote it twice. – jetxee Apr 15 '09 at 19:29 3 As someone who has had a great deal of problems understanding monads, I can say that this answer helped.. a little.
However, there's still some things that I don't understand. In what way is the list comprehension a monad? Is there an expanded form of that example?
Another thing that really bothers me about most monad explanations, including this one- Is that they keep mixing up "what is a monad? " with "what is a monad good for? " and "How is a monad implemented?".
You jumped that shark when you wrote "A monad is basically just a type that supports the >>= operator. " Which just had me... – Breton Aug 10 '09 at 2:00 1 Scratching my head. That seems like an implementation detail, and it doesn't really help me answer the question "Why should I use a monad".
It may be true, but the explanation up until that point didn't prepare me for it. I wasn't thinking " Why that's a tricky problem indeed, why, what I would need for that is some kind of type which supports the >>= operator. Oh hey, turns out that's what a monad is!
" nope, that wasn't running through my head, because I didn't know what a >>= operator was, or what THAT's good for, nor was I presented with a problem that it solves. – Breton Aug 10 '09 at 2:04 1 Also I disagree with your conclusion about why monads are hard. If monads themselves aren't complex, then you should be able to explain what they are without a bunch of baggage.
I don't want to know about the implementation when I ask the question "What is a monad", I want to know what itch it's meant to be scratching. So far it seems like the answer is "Because the authors of haskell are sadomasochists and decided that you should do something stupidly complex to accomplish simple things, so you HAVE to learn monads to use haskell, not because they're in any way useful in themselves"... – Breton Aug 10 '09 at 2:08.
But, You could have invented Monads! Sigfpe says: 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.
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.
) 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.
3 Sigfpe's post is THE best way to learn monads I've found in the internet. +1 for the suggestion. – Rafael S.
Calsaverini Jan 23 '11 at 22:55 2 …best way not only on the internet, but anywhere. (Wadler's original paper Monads for functional programming that I mentioned in my answer below is also good. ) None of the zillions of tutorials-by-analogy come close.
– ShreevatsaR Apr 30 '11 at 15:14.
A monad is a datatype that has two operations: >>= (aka bind) and return (aka unit). Return takes an arbitrary value and creates an instance of the monad with it. >>= 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 parametric polymorphism. ) In Haskell notation, the monad interface is written class Monad m where return :: a -> m a (>>=) :: forall a be . M a -> (a -> m b) -> m be 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 >>= and return ought to agree about how values get transformed into monad instances and that >>= is associative).
Monads are not just about state and IO: they abstract a common pattern of computation that includes working with state, IO, exceptions, and non-determinism. Probably the simplest monads to understand are lists and option types: instance Monad where >>= k = (x:xs) >>= k = k x ++ (xs >>= k) return x = x instance Monad Maybe where Just x >>= k = k x Nothing >>= k = Nothing return x = Just x where and : are the list constructors, ++ is the concatenation operator, and Just and Nothing are the Maybe 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 IO).
You really have to play around writing some non-trivial Haskell code to appreciate what monads are about and why they are useful.
– Casebash Mar 14 '10 at 6:24 Casebash, I'm being deliberately informal in the introduction. See the examples near the end to get a sense of what "mapping a function" entails. – Chris Conway Mar 14 '10 at 14:54.
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. For example, you can create a type to wrap another one, in Haskell: data Wrapped a = Wrap a To wrap stuff we define return :: a -> Wrapped a return x = Wrap x To perform operations without unwrapping, say you have a function f :: a -> b, then you can do this to lift that function to act on wrapped values: fmap :: (a -> b) -> (Wrapped a -> Wrapped b) fmap f (Wrap x) = Wrap (f x) That's about it there is to understand.
However, it turns out that there is a more general function to do this lifting, which is bind: bind :: (a -> Wrapped b) -> (Wrapped a -> Wrapped b) bind f (Wrap x) = f x bind can do a bit more than fmap, but not vice versa. Actually, fmap can be defined only in terms of bind and return. So, when defining a monad.. you give its type (here it was Wrapped a) and then say how its return and bind operations work.
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. 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 IO Inside. 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.
Is right-associative, mirroring function application, which is left-associative, so leaving the parentheses out doesn't make a difference here. – Matthias Benkard Oct 11 '08 at 16:06 Your explanation did the trick for me. I would have added though a limited summing of some standard monads (reader, state, maybe, ...) to illustrate some practical uses and wrappings – Rabarberski Apr 27 '09 at 8:36 That's the best short explanation I seen so far ;) – Alex Yakunin Oct 26 '09 at 7:23 I don't think this is a very good explanation at all.
Monads are simply A way? Okay, which way? Why wouldn't I encapsulate using a class instead of a monad?
– Breton Nov 6 '10 at 22:14.
You should first understand what a functor is. Before that, understand higher-order functions. A higher-order function is simply a function that takes a function as an argument.
A functor is any type construction T for which there exists a higher-order function, call it map, that transforms a function of type a -> be (given any two types a and b) into a function T a -> T b. This map function must also obey the laws of identity and composition such that the following expressions return true for all x, p, and q (Haskell notation): map (\x -> x) x == x map (p . Q) x == map p (map q x) For example, a type constructor called List is a functor if it comes equipped with a function of type (a -> b) -> List a -> List be which obeys the laws above.
The only practical implementation is obvious. The resulting List a -> List be function iterates over the given list, calling the (a -> b) function for each element, and returns the list of the results. A monad is essentially just a functor T with two extra methods, join, of type T (T a) -> T a, and unit (sometimes called return, fork, or pure) of type a -> T a.
For lists in Haskell: join :: a -> a pure :: a -> a Why is that useful? Because you could, for example, map over a list with a function that returns a list. Join takes the resulting list of lists and concatenates them.
List is a monad because this is possible. You can write a function that does map, then join. This function is called bind, or flatMap, or (>>=), or (=This is normally how a monad instance is given in Haskell.
A monad has to satisfy certain laws, namely that join must be associative. This means that if you have a value x of type a then join (join x) should equal join (map join x). And pure must be an identity for join such that join (pure x) == x.
Slight addition to def of 'higher order function': they can take OR RETURN functions. That's why they are 'higher' 'cos they do things with themselves. – Kevin Won Jan 30 '10 at 6:31 2 By that definition, addition is a higher-order function.It takes a number and returns a function that adds that number to another.
So no, higher order functions are strictly functions whose domain consists of functions. – Apocalisp Jan 30 '10 at 16:58.
This video is one of the clearest and most concise explanation of monads that I have come across: Brian Beckman: Don't fear the Monads.
Great video, very nice link. – Stephan202 May 16 '09 at 21:44 2 If someone else is getting the mp3 only since they don't have silverlight, the url is mms://mschnlnine.wmod.llnwd.net/a1809/d1/ch9/0..._OnMonoids_NoFear_s_ch9. Wm?
V – Alexander Torstling Jul 7 '10 at 17:44 That was a good video; for those who watch it and are still a little confused, make sure to read Sylvan's post in the comments on that page, which gives some useful C# code that may be of help in understanding Brian's great but otherwise terse explanation. – Jared Updike Jul 20 '10 at 23:32 2 I watched the whole thing twice. Up until the point where he introduced the bind operator, he wasn't telling me anything I didn't already know.
From that point hence, it was completely incomprehensible. – recursive May 5 '11 at 19:02.
A good motivation to Monads is sigfpe(Dan Piponi)'s You Could Have Invented Monads! (And Maybe You Already Have). There are a LOT of other monad tutorials, many of which misguidedly try to explain monads in "simple terms" using various analogies: this is the monad tutorial fallacy; avoid them.
As DR MacIver says in Tell us why your language sucks: So, things I hate about Haskell: 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.
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.
If you are mathematically oriented, you might want to ignore the dozens of tutorials and learn the definition, or follow lectures in category theory :) The 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. Also, surprisingly enough, one of the best introductions to monads is actually one of the early academic papers introducing monads, Philip Wadler's Monads for functional programming. It actually has practical, non-trivial motivating examples, unlike many of the artificial tutorials out there.
1 The only problem with Wadler's paper is the notation is different but I agree that the paper is pretty compelling and a clear concise motivation for applying monads. – Jared Updike Jul 31 '09 at 22:34 +1 for the "monad tutorial fallacy". Tutorials on monads are akin to having several tutorials trying to explain the concept of integer numbers.
One tutorial would say, "1 is similar to an apple"; another tutorial says, "2 is like a pear"; a third one says, "3 is basically an orange". But you never get the whole picture from any single tutorial. What I've taken from that is that monads are an abstract concept which can be used for many quite different purposes.
– stakx Jan 14 '11 at 7:30 @stakx: Yes, true. But I didn't mean that monads are an abstraction that you cannot learn or shouldn't learn; only that it's best to learn it after you've seen enough concrete examples to perceive a single underlying abstraction. See my other answer here.
– ShreevatsaR Jan 14 '11 at 12:22 1 Sometimes I feel that there are so many tutorials that try to convince the reader that monads are useful by using code that do complicated or useful stuff. That hindered my understanding for months. I don't learn that way.
I prefer to see extremely simple code, doing something stupid that I can mentally go through and I couldn't find this kind of example. I can't learn if the first example is a monad to parse a complicate grammar. I can learn if it's a monad to sum integers.
– Rafael S. Calsaverini Jan 23 '11 at 23:11.
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. The "maybe monad" is essentially the equivalent of "nullable types" in VB / C#.
It takes a non nullable type "T" and converts it into a "Nullable", and then defines what all the binary operators mean on a Nullable. Side effects are represented simillarly. A structure is created that holds descriptions of side effects along side a function's return value.
The "lifted" operations then copy around side effects as values are passed between functions. The are called "monads" rather than the easier to grasp name of "type operators" for several reasons: Monads have restrictions on what they can do (see the definiton for details). Those restrictions, along with the fact that there are 3 operations involved, conform to the structure of something called a monad in Category Theory, which is an obscure branch of mathematics.
They were designed by proponents of "pure" functional languages Proponents of pure functional languages like obscure branches of mathematics 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.
3 This is quite inaccurate... but I can't fit everything in the 300-character comment box :P – Porges Mar 17 '09 at 10:52 4 But you can post answer indicating what's wrong with my post. – Scott Wisniewski Mar 17 '09 at 15:31 7 Re: 4, 5: The "Secret handshake" thing is a red herring. Programming is full of jargon.
Haskell just happens to call stuff what it is without pretending to rediscover something. If it exists in mathematics already, why make up a new name for it? The name is really not the reason people don't get monads; they are a subtle concept.
The average person probably understands addition and multiplication, why don't they get the concept of an Abelian Group? Because it is more abstract and general and that person hasn't done the work to wrap their head around the concept. A name change wouldn't help.
– Jared Updike Jul 31 '09 at 22:53 8 Sigh... I'm not making an attack on Haskell ... I was making a joke. So, I don't really get the bit about being "ad hominem". Yes, the calculus was "designed".
That's why, for example, calculus students are taught the Leibniz notation, rather than the icky stuff Netwton used. Better design. Good names help understanding a lot.
If I called Abelian Groups "distended wrinkle pods", you may have trouble understanding me. You might be saying "but that name is nonsense", no one would ever call them that. To people who have never heard of category theory "monad" sounds like nonsense.
– Scott Wisniewski Aug 1 '09 at 1:21 3 @Scott: sorry if my extensive comments made it seem I was getting defensive about Haskell. I enjoy your humor about the secret handshake and you will note I said it is more or less true. :-) If you called Abelian Groups "distended wrinkle pods" you would be making the same mistake of trying to give monads a "better name" (cf.
F# "computation expressions"): the term exists and people who care know what monads are, but not what "warm fuzzy things" are (or "computation expressions"). If I understand your use of the term "type operator" correctly there are lots of other type operators than monads. – Jared Updike Aug 3 '09 at 23:27.
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.
Arnar wrote: Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it. That’s precisely it. The idea goes like this: 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. E.g.
, that extra information might be a Maybe or an IO. 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.E.g.
, a Maybe Int can be a Just Int or Nothing. Now, if you add a Maybe Int to a Maybe Int, the operator will check to see if they are both Just Ints inside, and if so, will unwrap the Ints, pass them the addition operator, re-wrap the resulting Int into a new Just Int (which is a valid Maybe Int), and thus return a Maybe Int. But if one of them was a Nothing inside, this operator will just immediately return Nothing, which again is a valid Maybe Int.
That way, you can pretend that your Maybe Ints are just normal numbers and perform regular math on them. If you were to get a Nothing, your equations will still produce the right result – without you having to litter checks for Nothing everywhere. But the example is just what happens for Maybe.
If the extra information was an IO, then that special operator defined for IOs would be called instead, and it could do something totally different before performing the addition. (OK, adding two IO Ints together is probably nonsensical – I’m not sure yet.) (Also, if you paid attention to the Maybe 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.
) Basically, “monad” roughly means “pattern”. But instead of a book full of informally explained and specifically named Patterns, you now have a language construct – syntax and all – that allows you to declare new patterns as things in your program. (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.) 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. But think of the implications of having syntactic support in the language for the idea of a pattern: instead of having to read the Gang of Four book and memorise the construction of a particular pattern, you just write code that implements this pattern in an agnostic, generic way 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! So that is why people who understand monads find them so useful: 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.
1 Sometimes an explanation from a "learner" (like you) is more relevant to another learner than an explanation coming from an expert. Learners think alike :) – Adrian Dec 7 '10 at 18:48.
This excellent video with Brian Beckman explains monads 'in terms you already know' and Brian assures you don't have to be scared by monads because of the way they look, because they are easy. I found his approach very educating and a good introduction to monads. Check it out.
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 jQuery (and its way of using "method chaining" to manipulate the DOM): jQuery is a Monad The jQuery documentation 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.
If you use jQuery, this explanation can be very helpful, especially if your Haskell isn't strong – byteclub Dec 15 '10 at 16:16.
My favorite Monad tutorial: haskell.org/haskellwiki/All_About_Monads (out of 170,000 hits on a Google search for "monad tutorial"! ) @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.
Haskell already has operator overloading1: 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 + && 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 there is no semicolon, since purely functional code does not require or allow explicit sequencing.
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. 1 This is a separate issue from monads but monads use Haskell's operator overloading feature.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.
As soon as you understand Monads, you will understand that this is a Monad, too. Xkcd:248 Hypotheticals {{alt: What if someone broke out of a hypothetical situation in your room right now? }}.
Monads Are Not Metaphors, but a practically useful abstraction emerging from a common pattern, as Daniel Spiewak explains.
Excellent explanation! – Bolo Dec 27 '10 at 21:52.
I've been thinking of Monads in a different way, lately. I've been thinking of them as abstracting out execution order in a mathematical way, which makes new kinds of polymorphism possible. If you're using an imperative language, and you write some expressions in order, the code ALWAYS runs exactly in that order.
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). And because monads are polymorphic, it's possible to run the same code in different monads, depending on your needs.
Plus, in some cases, it's possible to combine monads together (with monad transformers) to get multiple features at the same time.
The two things that helped me best when learning about there were: Chapter 8, "Functional Parsers," from Graham Hutton's book Programming in Haskell. 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.
The tutorial All About Monads. This gives several good examples of their use, and I have to say that the analogy in Appendex I worked for me.
code.google.com/p/monad-tutorial/ is a Work In Progress to address exactly this question.
But it looks abandoned now.. – Roman Plášil Oct 27 '09 at 22:33 It's not. Only on hold. – Tony Morris Dec 22 '09 at 2:02 3 See if this helps projects.tmorris.net/public/what-does-mo....1/… – Tony Morris Sep 9 '10 at 22:17.
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). An example would be for file IO.
You would be able to use a monad for file IO 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.
As I understand, monads are more than that. Encapsulating mutable state in a "pure" functional languages is only one application of monads. – thSoft Dec 30 '10 at 2:17.
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? For what it's worth, here are some links to tutorials that helped me (and no, I still haven't understood what monads are).
osteele.com/archives/2007/12/overloading... spbhug.folding-maps.org/wiki/MonadsEn loria.fr/~kow/monads.
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 runMyMonad monad data and the data flows through the pipes.
That is more like Applicative than Monad. With Monads, you have to get data from the pipes before you can choose the next pipe to connect. – Peaker Jul 22 '10 at 23:33.
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. There are three questions that need to be answered to understand monads: Why do you need a monad?
What is a monad? How is a monad implemented? 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.
Why do you need a monad? 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 "equation" 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 "state". 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. So let's create a hypothetical "state" 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. Consolestate MyConsole = new consolestate; so to do console programming, but in a pure functional manner, you would need to nest a lot of function calls inside eachother. Consolestate FinalConsole = print(input(print(myconsole, " what's your name?")),"hello, %inputbuffer%!
"); Programming in this way keeps the "pure" 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: consolestate FinalConsole = myconsole: print(" what's your name? "): input(): print("hello, %inputbuffer%!"); this would indeed be a more convenient way to write it. How do we do that though?
What is a monad? Once you have a type (such as consolestate) 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 "monad" by defining an operator like : (bind) that automatically feeds return values on its left, into function parameters on its right, and a lift operator that turns normal functions, into functions that work with that specific kind of bind operator. How is a monad implemented?
See other answers, that seem quite free to jump into the details of that.
The easiest way to grok them (at least for me) is as "decorators", adding behavior while preserving the underlying semantics. Or, an even dirtier definition: it's functional programming's operator overloading.
4 No, this is a really bad couple of analogies. – Peaker Jul 22 '10 at 23:33 1 I would actually say it is the reverse. They allow you to compose "decorated types" (Task, IEnumerable, Nullable etc) AS IF they were just T.
– Tormod May 12 '11 at 17:32.
Two little tutorials from the wikibooks to explain the idea (one is F# but provides a nice short definition): Understanding monads Computation expressions (usage in F#).
Monads are to control flow what abstract data types are to data. 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).
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. So, a monad is simply a control flow construct. A better phrase to replace monad would be 'control type'.
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. For example, the "if" monad: if( clause ) then block at it's simplest has two slots - a clause, and a block. The if 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. 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. Of course, in the same way that data structures may be iterated over, or traversed, monads may be evaluated.
Compilers may or may not have support for user defined monads. Haskell certainly does. Ioke has some similar capabilities, athough the term monad is not used in the language.
If you can read ML syntax, a short, accessible explanation with practical, simple code is here.
Princess's explanation of F# Computation Expressions helped me, though I still can't say I've really understood. EDIT: this series - explaining monads with javascript - is the one that 'tipped the balance' for me. blog.jcoglan.com/2011/03/05/translation-... blog.jcoglan.com/2011/03/06/monad-syntax... blog.jcoglan.com/2011/03/11/promises-are... 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.
Some things that I had difficulty understanding: Rules-based explanations never worked for me, because most practical examples actually require more than just return/bind. Also, calling them rules didn't help.It is more a case of "there are these things that have something in common, let's call the things 'monads', and the bits in common 'rules'". Return (a -> M) and Bind (M -> (a -> M) -> M) are great, but what I could never understand is HOW Bind could extract the a from M in order to pass it into a -> M.
I don't think I've ever read anywhere (maybe it's obvious to everyone else), that the reverse of Return (M -> a) has to exist inside the monad, it just doesn't need to be exposed.
Explaining monads seems to be like explaining control-flow statements. Imagine that a non-programmer asks you to explain them? You can give them an explanation involving the theory - Boolean Logic, register values, pointers, stacks, and frames.
But that would be crazy. 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. Or you could also explain loops, if statements, routines, subroutines, and possibly co-routines. 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. They are also a way for functional programmers to use imperative code without actually admitting it, but that's not their only use.
mikehadlow.blogspot.com/2011/02/monads-i... This is the video you are looking for. Demonstrating in C# what the problem is with composition and aligning the types, and then implementing them properly in C#. Towards the end he displays how the same C# code looks in F# and finally in Haskell.
I wrote a good-sized explanation of monads (with Python examples) here.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.