Category:Monads

From Rosetta Code
Revision as of 11:07, 2 February 2016 by Hout (talk | contribs) (Slight reorganisation of the overview text)
Monads is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

In functional programming, the Monad pattern is a general solution to the problem of nesting (or 'composing') a class of functions which enclose their output values in some kind of useful wrapping. The output envelope might, for example, contain, in addition to the returned value, a log string, or a boolean indicator of whether or not the input was a legal value. Sometimes the output might simply be enclosed in a list representing a range of possible values rather than a single value.

Functions of this type can not be directly nested with each other, because their output type (wrapped) does not match their input type (raw and unwrapped).

The monad pattern consists of writing two higher-order functions which allow the programmer to easily nest the application of such functions, by abstracting out the mechanics, and making sure that a function does not choke on an unexpected input type (a wrapped type, when it was expected a raw type).

More specifically, the two higher-order functions of the monad pattern handle the details of: 1. wrapping data in a particular kind of envelope, and 2. Providing other functions with direct access to the contents of an enclosing envelope.

These two functions are sometimes named as follows:

  1. Return or Unit, which wraps a piece of raw data, returning the wrapped 'monadic' form.
  2. Bind, which applies some other function directly to the contents of a monadic wrapper, obtains a result, and returns a wrapped form of that result.


(The term monad derives from a concept in category theory. In ancient Greek the word μοναδικος means 'consisting of units').

Commonly used monads:

the Writer monad
Nests functions which return their output in an envelope that includes a log string.
the Maybe monad
Nest partial functions which return their output in a wrapper that includes a boolean flag – indicating whether or not the input value was legal.
the List monad
Nests functions whose outputs consist of ranges of possible values, rather than single values. This provides a convenient encoding of cartesian products and set comprehensions.


(Other frequently used monads are the the IO monad, and the State monad)

Pages in category "Monads"

The following 3 pages are in this category, out of 3 total.