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
105
votes
3 answers

How to play with Control.Monad.Writer in haskell?

I'm new to functional programming and recently learning at Learn You a Haskell, but when I went through this chapter, I got stuck with the program below: import Control.Monad.Writer logNumber :: Int -> Writer [String] Int logNumber x = Writer…
Javran
  • 3,394
  • 2
  • 23
  • 40
103
votes
5 answers

What is indexed monad?

What is indexed monad and the motivation for this monad? I have read that it helps to keep track of the side effects. But the type signature and documentation doesn't lead me to anywhere. What would be an example of how it can help to keep track of…
Sibi
  • 47,472
  • 16
  • 95
  • 163
99
votes
3 answers

Difference between State, ST, IORef, and MVar

I am working through Write Yourself a Scheme in 48 Hours (I'm up to about 85hrs) and I've gotten to the part about Adding Variables and Assignments. There is a big conceptual jump in this chapter, and I wish it had been done in two steps with a good…
John F. Miller
  • 26,961
  • 10
  • 71
  • 121
97
votes
5 answers

Confused with the for-comprehension to flatMap/Map transformation

I really don't seem to be understanding Map and FlatMap. What I am failing to understand is how a for-comprehension is a sequence of nested calls to map and flatMap. The following example is from Functional Programming in Scala def…
sc_ray
  • 7,803
  • 11
  • 63
  • 100
96
votes
3 answers

mtl, transformers, monads-fd, monadLib, and the paradox of choice

Hackage has several packages for monad transformers: mtl: Monad transformer library transformers: Concrete functor and monad transformers monads-fd: Monad classes, using functional dependencies monads-tf: Monad classes, using type…
yairchu
  • 23,680
  • 7
  • 69
  • 109
88
votes
10 answers

Monads with Java 8

In the interests of helping to understand what a monad is, can someone provide an example using java ? Are they possible ? Lambda expressions are possible using java if you download the pre-release lambda compatible JDK8 from here…
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
87
votes
5 answers

Concrete example showing that monads are not closed under composition (with proof)?

It is well-known that applicative functors are closed under composition but monads are not. However, I have been having trouble finding a concrete counterexample showing that monads do not always compose. This answer gives [String -> a] as an…
Brent Yorgey
  • 2,043
  • 16
  • 17
85
votes
5 answers

Monads as adjunctions

I've been reading about monads in category theory. One definition of monads uses a pair of adjoint functors. A monad is defined by a round-trip using those functors. Apparently adjunctions are very important in category theory, but I haven't seen…
Bartosz Milewski
  • 11,012
  • 5
  • 36
  • 45
84
votes
1 answer

"Monad transformers more powerful than effects" - Examples?

The paper "Programming and reasoning with algebraic effects and dependent types" by Edwin C. Brady on effects in Idris contains the (unreferenced) claim that: Although [effects and monad transformers] are not equivalent in power — monads and monad…
geoff_h
  • 1,245
  • 8
  • 13
83
votes
18 answers

What is the point of the class Option[T]?

I am not able to understand the point of Option[T] class in Scala. I mean, I am not able to see any advanages of None over null. For example, consider the code: object Main{ class Person(name: String, var age: int){ def display =…
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
83
votes
3 answers

How does the ST monad work?

I understand that the ST monad is something like a little brother of IO, which in turn is the state monad with added RealWorld magic. I can picture states and I can picture that RealWorld is somehow put into IO, but every time I write a type…
David
  • 8,275
  • 5
  • 26
  • 36
82
votes
4 answers

How and why does the Haskell Cont monad work?

This is how the Cont monad is defined: newtype Cont r a = Cont { runCont :: (a -> r) -> r } instance Monad (Cont r) where return a = Cont ($ a) m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c Could you explain how and why this…
monb
  • 821
  • 1
  • 7
  • 3
79
votes
0 answers

Can anyone explain Monads?

Possible Duplicate: What is a monad? I think I understand what 'Maybe Monads' are, but I'm not sure about the other types.
Steve Willard
  • 16,647
  • 4
  • 28
  • 26
74
votes
5 answers

What are the benefits of applicative parsing over monadic parsing?

There seems to be a consensus that you should use Parsec as an applicative rather than a monad. What are the benefits of applicative parsing over monadic parsing? style performance abstraction Is monadic parsing out?
gawi
  • 13,940
  • 7
  • 42
  • 78
73
votes
2 answers

Monads vs. Arrows

I'm broadly familiar with the concepts of monads and arrows as used in functional programming. I also understand that they can be used to solve similar kinds of problems. However, I'm still a bit confused about how to select which one to use in any…
mikera
  • 105,238
  • 25
  • 256
  • 415