Questions tagged [monads]

A monad in programming is a composable computation description. Monads are an important construct in functional programming languages like Haskell.

A monad in programming is a composable computation description. Monads are an important construct in functional languages like Haskell.

In Haskell, a Monad is simply any type constructor m with two functions,

return :: a → m a                       -- construct `m a` value from an `a` value,
                                        --   and
(>>=) :: m a → (a → m b) → m b          -- "bind": combine `m a` value and
                                        --    `a → m b` value into an `m b` value

following several algebraic laws. (:: means "has type".)

A value of type m a represents (describes) an m-type computation, producing an a-type result.

Having defined

(>=>) :: Monad m => (a → m b) → (b → m c) → a → m c
--                     f           g        x
(f >=> g) x        =   f x >>= g         -- a.k.a. "Kleisli composition"

the Monad laws are:

return >=> g       =   g                 -- left identity
f      >=> return  =   f                 -- right identity
f >=> (g >=> h)    =  (f >=> g) >=> h    -- associativity

These types of values can be used to represent a wide variety of different tasks including: I/O, continuations, coroutines, non-determinism, error-handling, mutable state, parsing and more (each with its specific choice for m). In addition, they are particularly useful for embedding simple DSLs within a functional language like Haskell. In fact, it can be said that Monads are EDSLs, in a certain sense.

More precisely,

  • mappable computation descriptions are Functors, having
    fmap :: (a → b) → m a → m b operation, as if allowing us to write

    fmap f c = do { x <- c; return (f x) }

  • composable mappable computation descriptions are Applicative Functors, having
    (<*>) :: m (a → b) → m a → m b operation, conceptually allowing for

    c1 <*> c2 = do { x <- c1; y <- c2; return (x y) }

  • whereas whenever we have composable mappable computation description constructors, i.e. things of type a → m b composable with the Kleisli composition operator >=>, so we can write

    c >>= g = do { x <- c; y <- g x; return y },

    then we have a Monad.


To quote the user:leftaroundabout from here:

... [an] often-quoted analogy is that an action [i.e. a monadic value of type IO a] is like a recipe for a cake, the result [of type a] is the cake itself.

Applying [a function] directly to the IO action would be like taking a knife to cut the recipe in pieces, and expecting that you can then use that recipe to bake a ready-cut cake.

Clearly that's not how it works. You first need to execute (bind) an IO action before you can manipulate the result.

Alternatively, you can use the fmap operator. What this does is basically, it takes a recipe and some instruction what to do with the result, and then adds that instruction to the end of the recipe. If you then execute that recipe, the result of it will indeed be a cake cut into pieces.

3481 questions
1677
votes
47 answers

What is a monad?

Having briefly looked at Haskell recently, what would be a brief, succinct, practical explanation as to what a monad essentially is? I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail.
ljs
  • 37,275
  • 36
  • 106
  • 124
909
votes
5 answers

A monad is just a monoid in the category of endofunctors, what's the problem?

Who first said the following? A monad is just a monoid in the category of endofunctors, what's the problem? And on a less important note, is this true and if so could you give an explanation (hopefully one that can be understood by someone who…
Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141
882
votes
21 answers

Monad in plain English? (For the OOP programmer with no FP background)

In terms that an OOP programmer would understand (without any functional programming background), what is a monad? What problem does it solve and what are the most common places it's used? Update To clarify the kind of understanding I was looking…
user65663
562
votes
8 answers

Large-scale design in Haskell?

What is a good way to design/structure large functional programs, especially in Haskell? I've been through a bunch of the tutorials (Write Yourself a Scheme being my favorite, with Real World Haskell a close second) - but most of the programs are…
Dan
  • 5,763
  • 3
  • 17
  • 13
450
votes
1 answer

Scalaz iteratees: "Lifting" `EnumeratorT` to match `IterateeT` for a "bigger" monad

If I have an EnumeratorT and a corresponding IterateeT I can run them together: val en: EnumeratorT[String, Task] = EnumeratorT.enumList(List("a", "b", "c")) val it: IterateeT[String, Task, Int] = IterateeT.length (it &= en).run : Task[Int] If the…
lmm
  • 17,386
  • 3
  • 26
  • 37
420
votes
7 answers

What are free monads?

I've seen the term Free Monad pop up every now and then for some time, but everyone just seems to use/discuss them without giving an explanation of what they are. So: what are free monads? (I'd say I'm familiar with monads and the Haskell basics,…
David
  • 8,275
  • 5
  • 26
  • 36
407
votes
8 answers

Why do we need monads?

In my humble opinion the answers to the famous question "What is a monad?", especially the most voted ones, try to explain what is a monad without clearly explaining why monads are really necessary. Can they be explained as the solution to a…
cibercitizen1
  • 20,944
  • 16
  • 72
  • 95
231
votes
5 answers

Good examples of Not a Functor/Functor/Applicative/Monad?

While explaining to someone what a type class X is I struggle to find good examples of data structures which are exactly X. So, I request examples for: A type constructor which is not a Functor. A type constructor which is a Functor, but not…
Rotsor
  • 13,655
  • 6
  • 43
  • 57
206
votes
5 answers

In C#, What is a monad?

There is a lot of talk about monads these days. I have read a few articles / blog posts, but I can't go far enough with their examples to fully grasp the concept. The reason is that monads are a functional language concept, and thus the examples are…
Charlie Flowers
  • 17,338
  • 10
  • 71
  • 88
187
votes
8 answers

Why are side-effects modeled as monads in Haskell?

Could anyone give some pointers on why the impure computations in Haskell are modelled as monads? I mean monad is just an interface with 4 operations, so what was the reasoning to modelling side-effects in it?
bodacydo
  • 75,521
  • 93
  • 229
  • 319
148
votes
4 answers

What is the purpose of the reader monad?

The reader monad is so complex and seems to be useless. In an imperative language like Java or C++, there is no equivalent concept for the reader monad, if I am not mistaken. Can you give me a simple example and clear this up a little bit?
chipbk10
  • 5,783
  • 12
  • 49
  • 85
126
votes
7 answers

Applicatives compose, monads don't

Applicatives compose, monads don't. What does the above statement mean? And when is one preferable to other?
116
votes
16 answers

Pattern to avoid nested try catch blocks?

Consider a situation where I have three (or more) ways of performing a calculation, each of which can fail with an exception. In order to attempt each calculation until we find one that succeeds, I have been doing the following: double val; try {…
jjoelson
  • 5,771
  • 5
  • 31
  • 51
109
votes
5 answers

Functional design patterns

There are a lot of functional idioms: monads, applicatives, arrows, etc. They are documented in different articles but unfortunately I don't know any book or article where they're summarized in one place (there is Typeclassopedia but it has a lot of…
Konstantin Solomatov
  • 10,252
  • 8
  • 58
  • 88
107
votes
1 answer

Why do we have map, fmap and liftM?

map :: (a -> b) -> [a] -> [b] fmap :: Functor f => (a -> b) -> f a -> f b liftM :: Monad m => (a -> b) -> m a -> m b Why do we have three different functions that do essentially the same thing?
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
1
2 3
99 100