monadic-programming


What is a monad?

In fewer then 10 words:

Here are a few definitions from mmmdonuts that he gave in #scheme-on-freenode.

Pattern for using functions to transmit state without mutation.

Or, If you prefer some more verbosity:

The basic principle is just that you can build up state by passing closures around, adding to the state contained in each closure by creating a new closure containing the extra state and invoking the original closure as necessary.

Monads just formalize that into a pattern with a specific set of operations. Part of the monad pattern is setting things up so you don't have to explicitly pass the state from function to function, it's handled behind the scenes.

Keeping that part in mid check out foldoc's Haskell heavy Definition of Monad. Part of the problem with the above definitions is that they are a bit simplistic, monads do not deal exclusively with emulating state.

Riastradh

These definitions aren't really right at all. Monads have nothing inherent to do with state. A more accurate definition would be: Monads provide a generalized interface to sequential computation.


Monads in Scheme

Check out http://okmij.org/ftp/Scheme/monad-in-Scheme.html

There's an extensive post to comp.lang.functional on monads in Scheme,

http://groups.google.com/group/comp.lang.functional/msg/2fde5545c6657c81




New Page

NOTE: This is a work in progress, I am attempting to clean up this page as I learn more about monads. This should be considered the first draft.

What is a monad?

In less then 10 words: "Monads provide a generalized interface to sequential computation". Frequently they are used to deal with state-oriented computation in a referentially-transparent way. Sometimes you will hear a definition like "Monads allow you to emulate state", however that is not a complete definition of a monad.

Originally, monads come from category theory. (more info on its category theory history here).

Monadic Operations

There are 2 operations on monads. unit and bind. The unit operation will take a value x and transform it to the value M x. Unit is also called return

bind, also called >>= ....

Monadic Law

(need to flesh out and explain the laws a little better, as well as get into the associative law, and left-right identity)

For a "thing" to be called a monad, it must satisfy 3 laws:

  1. (return x) >>= f == f x
  2. m >>= return == m
  3. (m >>= f) >>= g == m >>= (\x -> f x >>= g) (this is the essence of the 3 laws, but isn't exactly clear to someone without a formal mathematical background)