Hacker News new | past | comments | ask | show | jobs | submit login

Do you understand the three-level distinction between type constructors (i.e. templates like C++, or generics in other languages), classes and instances? Do you understand first-class functions (lambdas)? If you've got those concepts down, you can understand monads.

Monads are the name for a particular member of a forth level on that three-level stack of abstractions (call them type classes, as that's what Haskell calls them (though I'm fudging a little here)); a type class is a particular shape for a generic type, in the same way that any given generic type is a particular shape for a class, and a class is a particular shape for an instance.

So when people talk about Option/Maybe being a monad, they mean Option/Maybe is a generic type (i.e. a type constructor) which has a certain shape - i.e. has a particular set of methods / functions defined on it.

That's the abstraction level of monads out of the way. The next thing to understand is the particular operations required. Monads are like containers for values, but rather than operating on the values directly (e.g. y = f(x)), you instead pass the monad the function you'd like it to apply to the value (e.g. y = x.bind(f)), and it returns you a monad which is logically the wrapper that function applied to its contents.

Because the application of the function to the value inside the monad is delegated to the monad itself, it gets to decide what to do with it. In the case of Option/Maybe, it'll only apply the function if the contents aren't empty. In the case of IO, it'll logically buffer up a list of imperative I/O operations which will be logically returned as a result of the main function; and that list of imperative instructions will then be imperatively executed, after the nice and pure Haskell program has finished its unpolluted existence. (That's how it happens logically (assuming there are no cheats available in the language), but not necessarily actually.)




I really like the shapes explanation. It's a much more explicit version of what I was trying to say.




Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: