Live data from Hacker News

Ask HN: What is a monad?

news.ycombinator.com

11–20 of 55 posts

Re: Ask HN: What is a monad?

#11
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-looking syntax ("do notation") that looks different to the normal functional style:

    main :: IO ()
    main = do
      putStrLn "Please enter your name"
      name 
'putStrLn "Hello"' doesn't actually print anything; it returns an IO value that, when interpreted by the Haskell runtime, prints something: that interpretation takes place when 'main' is run. The do notation is syntactic sugar for creating a sort of compound IO value that interprets as a bunch of actions rather than just one. The reason you can use do notation for IO but not for (all) other Haskell code is that IO values are monadic (which is another and possibly more useful way of saying "IO is a monad"): that just means that they behave in a certain way when combined (to produce that compound value) and obey certain laws to make the do notation well behaved.

Monads are a design pattern to abstract away repetitive functional code. For example, if you write a lot of pure-functional code you sometimes end up having to pass around a 'state' parameter. If a function reads or writes from the state, then any function that calls it has to pass in the state, and so on. This leads to a lot of functions with an extra state parameter, many of which don't even care about the state except to pass it down the call tree. An improvement would be to write a higher-order function which took a function which didn't care about state and wrapped it to produce one that just passed the state through. The State monad encapsulates this wrapping and lets you clean up the rest of your code.

Monads are what's between the lines of an imperative program. Bourne shell scripts have the default error-handling rule that they ignore failing commands unless it's the last one executed, or put another way, they run in a monad that ignores errors:

    cat nonexistent.txt   # prints an error message
    echo Done.            # still executes, prints "Done."
    # script returns success
But you can tell it to run instead in a monad which stops after the first error:

    set -e                # change the monad, i.e. the error-handling rule
    cat nonexistent.txt   # prints an error message
    echo Done.            # never runs
    # script returns failure
Old-school Visual Basic has the opposite default, but you can make it behave like a shell script with "ON ERROR RESUME NEXT". Yes, VB had monads.

Monads are a specific example of higher-kinded polymorphism, which is a very powerful and useful concept that's starting to enter the programming mainstream (examples are template concepts in C++ and LINQ in C# and .NET). Parametric polymorphism (List in Java and C#, etc) means you don't have to write a 'reverse' function that works on lists of strings, and another 'reverse' function for lists of ints, etc; you can just write a generic reverse function that works on lists of any kind, because it doesn't need to know the details of the contained type, just how to iterate over a list. However, if you want to reverse an array, you still have to write a new 'reverse'. If your language supports higher-kinded polymorphism, you can write a generic reverse function that works on any kind of container, because all it needs to know is that the container has some well-behaved method of iteration.

(The LINQ example is a bit more subtle, because C# doesn't support higher-kinded polymorphism, but LINQ is a hard-coded exception to that rule. The cool LINQ syntax works for any type which provides certain operations and behaves in a certain way - which just happen to coincide with the requirements for the type to be monadic.)

Re: Ask HN: What is a monad?

#12
post #2

Leibniz on Monads: http://www.rbjones.com/rbjpub/philos/classics/leibniz/monad....

Unfortunately "monad" gets used in a few contexts unrelated to the sense the OP is asking about. Similarly, the (cancelled) TV series Caprica recently started using "monad" to mean "monotheist".

Re: Ask HN: What is a monad?

#13

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…

So, a sort of sandbox function?

Re: Ask HN: What is a monad?

#15

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…

So, a sort of sandbox function?

Yes.

But, more like sandbox type.

Re: Ask HN: What is a monad?

#16
post #6

A cheap and unexciting trick for passing a value through a couple of functions. (Monads are cool, but it's important to understand that there's nothing, nuttin', whatsoever fancy about them, so I like to call them a "cheap trick".) This is a good intro: http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/ba... Be sure to mentally replace "monad" with "warm fuzzy thing" when reading it and it should make sense.

Actually, the effects of that trick are nothing less than exciting.

For example, that trick allows you to pass information from future (one of Wadler examples).

Re: Ask HN: What is a monad?

#17
DON'T start functional programming with monads. Familiarize with currying, pattern matching, how to create data types in Haskell, using recursion instead of loops, higher order functions, list comprehensions, type classes, polymorphism in Haskell (different than subtyping in OOP). Ignore monads for a while. To understand monads you must have a good grip of those concepts. You can start with http://learnyouahaskell.com/chapters.

You'll see Haskell tutorials delay telling about the concept. There's a reason.

For a bird's eye of monads you can check this: http://www.reddit.com/r/programming/comments/64th1/monads_in...

If you are ready, read and do exercises in http://blog.sigfpe.com/2007/04/trivial-monad.html and then http://blog.sigfpe.com/2006/08/you-could-have-invented-monad....

Re: Ask HN: What is a monad?

#18
post #2

Leibniz on Monads: http://www.rbjones.com/rbjpub/philos/classics/leibniz/monad....

Unfortunately "monad" gets used in a few contexts unrelated to the sense the OP is asking about. Similarly, the (cancelled) TV series Caprica recently started using "monad" to mean "monotheist".

On the other hand, it seems that if one is willing to propose a similarity between one of the cornerstones of rationalism and the misuse of "monad" by a fictional character on a canceled television series, one might be more open to seeing more direct lines of intellectual descent from an inventor of the calculus to functional programming.

The embedded type system of a programmatic monad remains unchanged despite the monad's combination into higher level structures - a somewhat Leibnizian characteristic.

Re: Ask HN: What is a monad?

#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 defined. (You can only compose an arrow if the range of one is the domain of the next.)

A functor is just a (natural) function on categories mapping both objects and arrows in a compatible way. Endofunctors map to the same category.

As each object in this category of endofunctors is a function we want to compose, we have to be given a way to do that. This is what that the monoid here does -- it's a way to describe the allowed ways of combining natural transformations, including any systematic tweaks to be done during the combination.

(The classical definition of a monoid is just a set with an associative binary operation with an identity.)

Post reply on HN