4 ms·
Here's how I like to explain Monads to people. I've been told it's a decent explanation. (It ignores the monad laws and such, but it's a decent conceptual overv
by wyager 12y ago
Here's how I like to explain Monads to people. I've been told it's a decent explanation. (It ignores the monad laws and such, but it's a decent conceptual overview.)
OK, so you know Java interfaces? Haskell has something just like that. They're called "type classes", though. But it works pretty much the same way. When you write out a class definition, you write A) the name of the class B) all the functions the class has to support and C) the types of those functions. (Like a Java interface definition.)
Haskell has a type class called "Monad". To "implement the monad interface", in Java parlance, you have to implement two functions. The first is called "bind", but it's written ">>=". Here's its definition:
>>= :: m a -> (a -> m b) -> m b
Let's say our Monad was called `Foo`. In Java-land, this means the function takes a `Foo<a>`, a function that takes an `a` and returns a `Foo<b>`, and it uses those two things to return a `Foo<b>`.
The other function is "return", which is defined as
return :: a -> m a
Which, in Java terminology, means it takes an `a` and returns a `Foo<a>`.
If you implement those two functions, you now have a Monad.
If you've been told that Monads do anything in particular, you've been told wrong. Monads don't necessarily have anything to do with IO, or sequencing, or state, or anything like that.
It just so happens that those two functions (">>=" and "return") are super useful for representing a whole lot of common things, which happen to include things like IO and stateful algorithms. Monads don't have to do either of those things, but they certainly can.
- oconnor663 12y agoCan you add some examples of how bind and return get defined for commonly used monads, like IO? I'd love to have a more intuitive grasp of what they're for.
- JoshTriplett 12y agoIO is a bad example; its instance of Monad normally exists in native non-Haskell code (or in Haskell-runtime-specific code) rather than in Haskell. Another good reason that talking about the "IO monad" early on doesn't work out well. So, I'll start with a couple of non-IO examples and then provide a suggestion for how IO works. Let's start with Maybe. The Maybe type looks like this: data Maybe a = Just a | Nothing You often use Maybe to represent functions that only handle some inputs: safeHead :: [a] -> Maybe a safeHead (x:_) = Just x safeHead _ = Nothing > safeHead [1,2,3] Just 1 > safeHead [] Nothing The Maybe monad lets you assemble a series of operations of type Maybe into a single compound function of type Maybe. If any of the individual operations produce Nothing, the whole function produces Nothing. safeAddHeads :: Num a => [a] -> [a] -> Maybe a safeAddHeads l1 l2 = do v1 <- safeHead l1 v2 <- safeHead l2 return v1 + v2 > safeAddHeads [1,2,3] [2,4,6] Just 3 > safeAddHeads [1,2,3] [] Nothing That do notation get translated to the following uses of bind and return: safeAddHeads l1 l2 = safeHead l1 >>= \v1 -> safeHead l2 >>= \v2 -> return v1 + v2 Bind (>>=) implements this behavior, of obtaining a value and feeding it into the next combination, or returning Nothing: (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b Just a >>= f = f a Nothing >>= _ = Nothing Return takes a plain value and makes it a monadic value, so it's just the "Just" constructor: return :: a -> Maybe a return = Just (You could also write that as "return a = Just a", but you'll often see Haskell functions written in "point-free style", which means omitting explicit parameter names when not needed.) So, that's bind and return for Maybe. For a more unusual example, lists are a monad. The list monad acts like a cross-product: for every value in the list, do the remaining operations. For instance: pairs :: [a] -> [b] -> [(a,b)] pairs l1 l2 = do v1 <- l1 v2 <- l2 return (v1, v2) > pairs [1,2,3] [4,5] [(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)] If that looks a lot like a list comprehension, that's not a coincidence. Return, again, is easy: return :: a -> [a] return a = [a] Bind implements the behavior of running the right-hand side for each item on the left and combining the results into a list: (>>=) :: [a] -> (a -> [b]) -> [b] (x:xs) >>= f = f x ++ (xs >>= f) [] >>= _ = [] Note that the list bind operation calls itself recursively here: first call f on the first item, then call it on the rest. This could also be written with a fold or map; for instance: xs >>= f = concatMap f xs concatMap just runs concat on the result of map. The map applies f (of type a -> [b]) to each item in the list (type [a]); since f returns a list, that results in a list of lists ([[b]]), which concat combines into a single list ([b]). You might want to take a look at the Writer, Reader, and State monads for further examples. Note in particular that those three maintain some internal state information inside the monad, and in addition to the bind and return operations, they offer operations that work with that internal state. Having given those examples, here's a sketch of how IO could work. IO operations act as though they change some state (the outside world), and if you chain them together, the second operation acts on the state resulting from the first (for instance, if you call getLine twice, the first modifies the state of stdin by reading a line from it, and the second starts where the first left off by reading another line). That state isn't actually representable in Haskell, but let's imagine that it is. So, the IO type (to focus on the terminology suggested by this article) contains a value along with an operation changing the state of the world: data IO a = IOPrivate (StateOfTheWorld -> StateOfTheWorld) a Notice that a value of IO type contains an operation changing the state of the world, rather than an actual state of the world. It helps to think of an IO type as representing an operation to be run, and main is the top-level operation that actually gets run when you invoke the program. Continuing that analogy, something outside your program, provided by the Haskell runtime, does this: run :: IO () -> StateOfTheWorld run (IOPrivate f ()) = f initialStateOfTheWorld (Compare this to functions like runState, for instance.) Return takes a non-IO value and makes it into an IO value that doesn't actually change the state of the world: return :: a -> IO a return a = IOPrivate id a Bind sequences the changes to the state of the world: (>>=) :: IO a -> (a -> IO b) -> IO b (IOPrivate sf1 v1) >>= f = let IOPrivate sf2 v2 = f v1 in IOPrivate (sf2 . sf1) v2 ("sf" here stands for "state function".)
- eru 12y agoThat might be a decent explanation of monads, but the article's point is explicitly that we shouldn't worry beginners with monads at all.
- frowaway001 12y agoDid you even understand that the whole point of the article was about not bringing up Monads? Jesus.
- wyager 12y ago> Did you even understand that the whole point of the article was about not bringing up Monads? Jesus. Indeed, but there were people in this thread who were asking about them, and I will always prioritize people who are asking to learn something over people who are asking not to teach something.
- reilly3000 12y agoI see that you have invoked ire with your comment but I have to say: 1. I have never even attempted to grok Haskell 2. I read the article, noted that the author never actually defined 'monad' even those he raised the question, and asked myself 'yes, but what is a monad?' 3. I was going to Google it, but decided to check these comments for some concise answer so that I might avoid some kind of Haskell rabit hole when I should be coding. I found your comment to be just what I was looking for and written quite concisely. So, thanks, and haters gonna hate.
- tjradcliffe 12y agoEvery explanation of every Haskell feature I encounter reads the same way as this. You define "return" as "<code>return :: a -> m a</code>" and say this means it takes "an a" (by which I assume you mean an object of type a?) and returns a "<code>Foo<a></code>" (an object of type <code>Foo<a></code>?). The problem I have is: what on earth does this have to do with 'm'? Is 'm' equivalent to 'Foo'? If so, why don't you mention that? It isn't obvious to a newb who is lost in the welter of syntax. Does 'm a' mean the same thing as <code>Foo<a></code>? If so, why not use 'Foo' in your Haskell rather than 'm', which is simply introduced without any description, mention or explanation? Is there some significance to the naming? This is the kind of question that a newb specifically cannot answer, and Haskell tutorials are notoriously lax about. They have a strong tendency to assume you know the syntax of the language, which they use to explain the syntax of the language. You've given a nice, detailed explanation, but have failed to describe what 'm' is, and that means your average newb (me, or possibly even someone much, much smarter than me, as I'm told such people exist in profusion) is left making guesses. I'm pretty sure I know what the correct guesses are, but I really want to know: why did you use a completely different, unrelated, and opaque name for 'Foo' in your Haskell example, and then talk exclusively about 'Foo' in your explanation? This isn't really a knock at you personally: as I said, every Haskell tutorial I've encountered has similar issues. I'm just deeply curious as to why this is the case (and painfully aware that my own explanations regarding other languages are likely as opaque to newbs as these Haskell explanations are to me.)
- swift 12y agoThe 'm' is a type variable. This is a consequence of a difference in how Java interfaces and Haskell typeclasses are defined. (I'm continuing wyager's analogy between Java interfaces and Haskell typeclasses here.) Here's a sample Java interface: interface Pushable { void push(bool shouldShove); } Here's a similar Haskell typeclass: class Pushable p where push :: p -> Bool -> () In type signatures, an identifier starting with a lowercase letter is a type variable. So 'p' is a type variable here, like the 'm' type variable used in the Monad typeclass. It refers to the type which, in Java terms, implements Pushable. (In Haskell you'd say the type "is an instance of Pushable".) So why this difference? Java, being a C++-style OO language, privileges the implicit first argument. When class Button implements Pushable, you can think of its push method as having a real signature of "void push(Button this, bool shouldShove)". This particular pattern is special in Java, so you don't have to write the "Button this" parameter explicitly. But it's not a special pattern in Haskell, so you do need to explicitly write the 'p' in "push :: p -> Bool -> ()". To drive the point home, maybe one more comparison is useful. In Java, when an interface method needs to take a parameter that has the type of the implementing class, you need to do something that looks a bit more like Haskell. Here's an example: interface Comparable<T> { Ordering compare(T other); } If you're not familiar with this idiom (which is the same as the CRTP in C++), here's how you'd implement Comparable<T>: class Foo : Comparable<Foo> { Ordering compare(Foo other) { ... } } Now compare the type parameter 'T' in our Java Comparable<T> interface and the type parameter 't' in this Haskell Comparable typeclass: class Comparable t where compare :: t -> t -> Ordering They serve the same role - they refer to any type that may implement that interface (in Java) or be an instance of that typeclass (in Haskell). Hopefully this clarifies things a bit.