Live data from Hacker News

Ask HN: What is a monad?

news.ycombinator.com

31–40 of 55 posts

Re: Ask HN: What is a monad?

#31

It's a design pattern for encapsulation, with similar goals to OO but different methods. Rather than telling you what a monad is, I'll just tell you the goal. OO is designed to hide the dangerous parts of the world from you. The dangerous parts of the world (or at least some dangerous parts of the world) are encapsulated inside little black boxes with well defined interaction points. If you interact only through thos…

A monad puts you into a box and only gives you a few interaction points with the outside world. You can do whatever you want in a monad, but you are never allowed to leave the box.

This is not true for many commonly used monads, except for the IO monad. You can extract values from the list monad, Maybe monad, state monad, etc.

Put simply, a monad specifies how values can be wrapped in a 'box', and how such boxes are combined. For instance, Maybe is a box that can contains either a variable or nothing. In Haskell:

data Maybe a = Nothing | Just a

The Maybe monad specifies how expressions resulting in a Maybe are combined. Expressions are evaluated until/unless one of the expressions returns 'Nothing', and the value of the monad becomes Nothing.

Comparably, the IO monad specifies how IO actions are combined, the State monad combines expressions in such a manner to create 'state', etc.

We have tried to illustrate Monads with a Haskell-ish example here:

http://www.nlpwp.org/book/chap-words.xhtml#id3390030

Re: Ask HN: What is a monad?

#32

Monads are red herrings , if what you're interested in is getting started with functional programming (or even Haskell specifically). It's an unfortunate flaw in the Haskell literature that makes it seem like you have to grok monads to learn Haskell; you don't. Monads enable syntactic sugar . If you're getting started with Haskell, you'll notice that when you write code that does I/O, you use a weird imperative-looki…

Each of your statements seems plausible, even profound in itself.

Then I try to combine them and my head explodes.

You don't need to understand Monads to understand Haskell but they're how you print "Hello world"?? Yeah. Your other example also seem pithy and worthy, and again leave me feeling like the result is utterly opaque. You've shown goodness and power and all but it feels like you're holding the real definition behind your back to make the magic look even more magical-er.

How's-about-ya-spit-it-out. What the heck's a monad?

I feel like I've gotten as far as thinking that a monad's like a little interpreter/pre-interpreter. You pass it something like raw code and it binds more meaning to the variables as well as change the context of execution etc, all before that code gets eventually interpreted. Kind of like how you pass fragments of code to Ruby functions and kind of like how c++ templates are parameterized by type.

Wikipedia says "A monad is a construction that, given an underlying type system, embeds a corresponding type system (called the monadic type system) into it (that is, each monadic type acts as the underlying type). This monadic type system preserves all significant aspects of the underlying type system, while adding features particular to the monad." http://en.wikipedia.org/wiki/Monad_(functional_programming) At least that definition doesn't leave me feeling like someone's said "I can't tell you but they're really great"...

Re: Ask HN: What is a monad?

#33
post #28

It's a design pattern for encapsulation, with similar goals to OO but different methods. Rather than telling you what a monad is, I'll just tell you the goal. OO is designed to hide the dangerous parts of the world from you. The dangerous parts of the world (or at least some dangerous parts of the world) are encapsulated inside little black boxes with well defined interaction points. If you interact only through thos…

Monads have nothing to do with OO. Ignore this guy's comment and read samstokes' instead.

[deleted]

Re: Ask HN: What is a monad?

#34
Moggi used monads in category theory to define computations with side effects in functional programming. The basic insight is that in addition to the values of various types in functional programming, there are "computations" of various types. Examples of "computations" would be exceptions or continuations. Each monad defines for each value type a computation "containing" that type, and the whole type system of values you started with can be embedded in a new type system with new computation types.

Monads in category theory are an algebraic device for embedding a category--usually a cartesian closed category--of types of values into a new category with types of computations. However, the correspondence between Haskell monads and category monads are related by a series of adjunctions.

Suppose that C is a cartesian closed category and M:C->C is a monad with natural transformations e:1->M (the unit) and u:MM->M (the multiplication).

We assume a fixed choice of products and compatible exponentials: for each type A of C,

  A x ( ) -| [A -> ( )]
Here's the adjunction

  MA -> [[A->MB] -> MB]
  ---------------------
  MA x [A -> MB] -> MB
  ---------------------
  [MA -> MB] x MA -> MB
  -----------------------
  [A -> MB] -> [MA -> MB]
The final map is given by currying, but it can also be motivated as follows if you think of the exponentials as internal hom sets. If g:A -> MB is in C, so that g:A->B is in the Kleisli category C^M, then u_{MB}oM(g):MA->MB. We can write this as the lambda term \lambda x\in A A -> MB.u_{MB} oM x

This lambda term corresponds to composition in the Kleisli category C^M of C, and belongs to the internal language LL(C), the simply typed lambda calculus determined by C. Under the Curry-Howard-Lambek correspondence, the lambda term corresponds to the required map of C.

Re: Ask HN: What is a monad?

#35
It's the operator that allows to chain two statements together. It's written ";" in Pascal, and is often implicit in other languages.

When a language explicitly talks about monads, it's because it lets you overload that operator, i.e. it let's you give alternative definitions of what it means to chain statements together.

Re: Ask HN: What is a monad?

#36
post #29

Earlier quoted context omitted.

Hmm, I see. Does it also execute code, like a sort of exception handler, or is it just for limiting/allowing access to scope?

A monad is a type that has certain associated functions — to wrap values in the monad and do calculations on what's inside. The type itself obviously cannot execute code, but the associated functions obviously do. Monads can be used to implement exceptions. As an example, lists are monads. The operator for doing calculations with the value in a monad is >>= (pronounced "bind"). To double every item in an array, you c…

Hmm, I see. The problem with my understanding it is that people are describing its properties and I have to build the mental model from them.

Are Python list comprehensions monads?

Re: Ask HN: What is a monad?

#37
There are already a number of excellent answers, but I'll try my hand. You don't know something until you can explain it 3 different ways.

Haskell excels as a functional language because it has excellent piping, Monads are just another form of piping with particularly great syntactic and psychological properties. They act as wrappers around a direct type and setting the return type of a function as a monadic type (such as IO () or [Int] or Maybe Bool) means that the primary type is () or Int or Bool, but there's something special being passed along as well.

In practice this saves typing since you don't explicitly pass the special monadically-hidden information. It also psychologically lets you think of simple types being wrapped in contexts which have certain properties. Some contexts can be unwrapped, some cannot. Some contexts can transform into other contexts directly, some cannot. Learning the behavior of each monad independently teaches you about these behaviors and then becomes important in advanced Haskell programming.

When learning, avoid them. Learn how to use IO by rote and ask in IRC about the confusing type errors that will arise. They usually translate as "you tried to combine two pipes which don't fit, so that monadic special sauce was lost". Part of learning Haskell is learning all of the joints and adaptors which help you to combine types effectively (including monads).

When you have a firm grasp of using compositions and maps and filters, start with the Maybe monad. Implement it and use all the general monad adaptors on them. Then learn the basic State monad because it makes the special sauce very explicit. Learn IO last because it's really a special case and should never be introduced as a monad.

Re: Ask HN: What is a monad?

#38

Monads are red herrings , if what you're interested in is getting started with functional programming (or even Haskell specifically). It's an unfortunate flaw in the Haskell literature that makes it seem like you have to grok monads to learn Haskell; you don't. Monads enable syntactic sugar . If you're getting started with Haskell, you'll notice that when you write code that does I/O, you use a weird imperative-looki…

Each of your statements seems plausible, even profound in itself. Then I try to combine them and my head explodes. You don't need to understand Monads to understand Haskell but they're how you print "Hello world"?? Yeah. Your other example also seem pithy and worthy, and again leave me feeling like the result is utterly opaque. You've shown goodness and power and all but it feels like you're holding the real definiti…

For a more thorough, probably better written although longer explanation, I say going to http://blog.sigfpe.com/2006/08/you-could-have-invented-monad... and reading through that, but I'll give it my own, shorter go and see if you can follow.

Monads are basically a design pattern dealing with special data types. Let's say you're in some situation where there's nondeterminism—each function doesn't return just a value, but several possible values. To use a pseudo-C++-like type system, all of your functions have a signature like

    List doSomething(A);
where it returns a list of B's to represent every possible value. You want to chain these together, and the naïve way is

    foo = doSomething(x)
    bar = []
    for someFoo in foo:
        bar += doSomethingElse(someFoo);
    baz = []
    for someBar in bar:
        baz += doSomeOtherThing(someBar)
So for every function, you have to repeatedly accumulate the possible values for every possible value so far. If you have higher-order functions, you can encapsulate this in a function like this

    def bind(f, list):
        results = []
        for value in list:
            results += f(value)
        return results
which means the above example could be rewritten as

    bind(doSomeOtherThing,
         bind(doSomethingElse,
              bind(doSomething, [x])))
Now, the type of bind looks something like

    List bind(List f(A), List)
which is to say it takes a function from a normal type to a "special" type—in this case a list—and applies it to a "special" type—in this case, every element of a list. In this case, we'd say that List, together with the bind function, is monadic. The Haskell types look more like

    bind :: (a -> m b) -> m a -> m b
    -- or for our particular example
    bind :: (a -> [b]) -> [a] -> [b]
The key here—and it's a simple example, so it's probably hard to see how it extends to the hype given—is that you've got a "special" kind of data and you're taking functions which operate on normal (non-special, in this case, non-list) data and writing functions to use them on special data with little work. The cool thing is that it's a really common pattern, which is why Haskell programmers mention it a lot.

(Note: in Haskell, 'bind' is actually an operator written >>=, and the order of its arguments are reversed, so its type is

    >>= :: (Monad m) => m a -> (a -> m b) -> m b
but there are reasons for writing it the way I did.)

Re: Ask HN: What is a monad?

#39
post #20

What, no one is giving the standard answer of "a monad is a monoid in the category of endofunctors?" A category is something like a set, but combining the objects with allowed operations. (How very OOP!) The available functions are first-class citizens (called arrows). The objects are the domains and ranges of the arrows, and their internal structures are not exposed. Arrow composition is associative when it is defin…

The paragraph starting "As each object in this category..." made no sense to me. I can explain the what a monoid in the category of endofunctors is, how it relates to a Haskell monad and maybe you can explain what you meant.

OK, a monoid in the category of endofunctors is an endofunctor F together with a natural transformation (the multiplication of the monoid) from F composed with F to F, and another natural transformation from id to F (called the unit). In Haskell F is the type constructor of the monad, the unit is called return and the multiplication is usually called join (and in the case of the list monad is also known as concat).

(Note that the definition of monoid needed here is not that of a set with associative binary operation, but the more general "monoid object in a monoidal category". Instead of a set S and a multiplication S x S->S, where x denotes cartesian product, we want a functor F and a multiplication F o F->F where o denotes composition. This is an instance of the general sort of monoid since the category of endofunctors is monoidal with respect to composition.)

Re: Ask HN: What is a monad?

#40

Monads are red herrings , if what you're interested in is getting started with functional programming (or even Haskell specifically). It's an unfortunate flaw in the Haskell literature that makes it seem like you have to grok monads to learn Haskell; you don't. Monads enable syntactic sugar . If you're getting started with Haskell, you'll notice that when you write code that does I/O, you use a weird imperative-looki…

Lovely, thank you.
Post reply on HN