Monad (functional programming)

Monad (functional programming)

In functional programming, a monad is a programming structure that represents computations. Monads are a kind of abstract data type constructor that encapsulate program logic instead of data in the domain model. A defined monad allows the programmer to chain actions together and build different pipelines that process data in various steps, in which each action is decorated with additional processing rules provided by the monad; for example a sequence of arithmetic operations can be controlled to avoid division by zero in intermediate results. Programs written in functional style can make use of monads to structure procedures that include sequenced operations,[1][2] or to define some arbitrary control flows (like handling concurrency, continuations, side effects such as input/output, or exceptions).

Formally, a monad is constructed by defining two operations (bind and return) and a type constructor M that must fulfill several properties to allow the correct composition of monadic functions (i.e. functions that use values from the monad as their arguments). The return operation takes a value from a plain type and puts it into a monadic container of type M. The bind operation performs the reverse process, extracting the original value from the container and passing it to the associated next function in the pipeline.

A programmer uses an existing monad by composing monadic functions to define a new data-processing pipeline. The monad acts as a framework, as it's a reusable behavior that decides the order in which the specific monadic functions in the pipeline are called, and manages all the undercover work required by the computation.[3] The bind and return operators interleaved in the pipeline will be executed after each monadic function returns control, and will take care of the particular aspects handled by the monad.

The name is taken from the mathematical monad construct in category theory, though the two concepts are not identical.



Eugenio Moggi first described the general use of monads to structure programs.[4] Several people built on his work, including programming language researchers Philip Wadler and Simon Peyton Jones (both of whom were involved in the specification of Haskell). Early versions of Haskell used a problematic "lazy list" model for I/O, and Haskell 1.3 introduced monads as a more flexible way to combine I/O with lazy evaluation.

In addition to I/O, scientific articles and Haskell libraries have successfully applied monads to topics including parsers and programming language interpreters. The concept of monads along with the Haskell do-notation for them has also been generalized to form arrows.

Haskell and its derivatives have been for a long time the only major users of monads in programming. There also exist formulations in Scheme, Perl, Racket, Clojure and Scala, and monads have been an option in the design of a new ML standard. Recently F# has included a feature called computation expressions or workflows, which are an attempt to introduce monadic constructs within a syntax more palatable to programmers with an imperative background.[5]

Effect systems are an alternative way of describing side effects as types.


Some primary uses of monads in functional programming are to express input/output (I/O) operations and changes in state without using language features that introduce side effects.[6] Although a function cannot directly cause a side effect, it can construct a value describing a desired side effect, that the caller should apply at a convenient time. One value in such monadic function represents a state of the world. When passing in the state of the world to a function, the monad will create a new world back where the state has been changed according to the function's return value. The state created in this way can be passed to another function, thus defining a series of functions which will apply in order as steps of state changes. This process is similar to how a temporal logic represents the passage of time using only declarative propositions.

In the following example, putStrLn and getLine are monadic functions defined in terms of the I/O monad (see below). The monad controls the changes of state in the input and output streams, and threads each world state from one line to the next in the do-block.

  putStrLn "What is your name?"
  name <- getLine

However, I/O and state management are by no means the only uses of monads. They are useful in any situation where the programmer wants to carry out a purely functional computation while a related computation is carried out on the side. In imperative programming the side effects are embedded in the semantics of the programming language; with monads, they are made explicit in the monad definition, thus avoiding errors by action at a distance.

The name monad derives from category theory, a branch of mathematics that describes patterns applicable to many mathematical fields. (As a minor terminological mismatch, the term monad in functional programming contexts is usually used with a meaning corresponding to that of the term strong monad in category theory, a specific kind of category-theoretical monad.)[4]

The Haskell programming language is a functional language that makes heavy use of monads, and includes syntactic sugar to make monadic composition more convenient. All of the code samples in this page are written in Haskell unless noted otherwise.







In practical terms, a monad (seen as special result values carried throughout the pipeline) stores function results and side-effect representations. This allows side effects to be propagated through the return values of functions without breaking the pure functional model. For example, Haskell's Maybe monad can have either a normal return value, or Nothing. Similarly, error monads (such as Either e, for some type e representing error information) can have a normal return value or an error value. Consider how these apply to the example of "Maybe" type, as explained in the Examples section.


For a monad to behave correctly, the definitions must obey a few axioms.[7] (The ≡ symbol is not Haskell code, but indicates an equivalence between two Haskell expressions.)

  • "return" acts approximately as a neutral element of >>=.
(return x) >>= f ≡ f x
m >>= return ≡ m

In the last rule, the notation \x -> defines an anonymous function that maps any value x to the expression that follows.

In mathematical notation, the axioms are:

(\text{return} \; x) \gg\!= f \equiv f \; x
m \gg\!= \text{return} \equiv m
(m \gg\!= f) \gg\!= g \equiv m \gg\!= \lambda x \; . \; (f \, x \gg\!\!= g)

The axioms can also be expressed in do-block style (see below):

do { x <- m; 
     y <- f x;
     g y }

Monadic zero

A monad can optionally define a "zero" value for every type. Binding a zero with any function produces the zero for the result type, just as 0 multiplied by any number is 0.

mzero >>= f ≡ mzero


m >>= (\x -> mzero) ≡ mzero


An additive monad is a monad endowed with a monadic zero and an operation (called mplus) satisfying the monoid laws, with the monadic zero as unit. The operation has type M tM tM t (where M is the monad constructor and t is the underlying data type), satisfies the associative law and has the zero as both left and right identity. (Thus, an additive monad is also a monoid.)

An introductory example as a control structure

The following example shows usage of a monad as a control structure in the well-known context of real division. It uses the Maybe monad, which is designed to handle exceptional cases in operations, to check for divisions by 0.

This requires the definition of a special division operator // to perform a sequence of divisions, either of which could result in an operating error. The // operator checks whether the divisor is 0, in which case it returns a special value Nothing that is chained through the other operations in the procedure. The // operator is defined in terms of the Maybe constructor and its corresponding bind and return operators.

The following pseudocode defines a safeDivisions function performing a sequence of divisions and assignments to variables. This function is called with the input value 2, which returns the value 1, and input value 0, which performs an invalid division by zero operation and returns the special value Nothing.

safeDivisions x = do
      val1 <- 6' // x'
      val2 <- val1' // 3'
      return val2
safeDivisions 2
-> 1'
safeDivisions 0
-> Nothing

The values 6', 3' and the variables x', val1', val2' are modified versions of the equivalent numbers transformed to match the correct type required by the // operator. Operations on these transformed values are augmented with the error-control aspect provided by the Maybe monad. In this particular case, the monad is used to define the behavior of a not-a-number special value, which is often found in programming languages as part of the language definition but in this case is provided as a library function.


Checking for the presence of a previous error is performed in the Maybe monad definition, so it doesn't need to be replicated in every new operator that uses it. The operator only needs to test for errors it produces, not previous errors in the pipeline; the monad itself abstracts in a reusable way the error-checking in composite functions.

The whole process in the example above is written in a functional programming style, thus retaining referential transparency. This implies that all computation steps, even jumps in the control flow, are expressed as a part of the program. Contrast this with exceptions in imperative programming in which the effects of changes in execution state are defined outside the programming language, encapsulated as opaque language primitives.

The division function used in the previous example is undefined for some known values, such as zero. Division might occur repeatedly in a calculation. A programmer might want to express a sequence of divisions without caring for error control, like the following one which returns the resistance of two electrical resistors in parallel:

-- par is a function that takes two real numbers and returns another
-- It is an example taken from electrical engineering (see above) to
--   illustrate why implementing [[NaN]]-semantics on top of the current
--   division system is useful; it is not related to Monads.
par :: Float -> Float -> Float -- resistance(R1), resistance(R2) -> resistance(R1 in parallel with R2)
par R1 R2 = 1 / ((1 / R1) + (1 / R2)) -- formula given from electrical engineering

Instead of avoiding any errors by checking whether each divisor is zero, it might be convenient to have a modified division operator that does the check implicitly, as in the following pseudocode:

-- // is an operator that takes two "Maybe Float"s and returns another.
-- "Maybe Float" extends the Float type to represent calculations that may fail.
(//) :: Maybe Float -> Maybe Float -> Maybe Float
_ // Just 0 = Nothing
Just x // Just y = Just (x / y)
_ // _ = Nothing
parM :: Float -> Float -> Maybe Float
parM R1 R2 = 1' // ((1' // R1') +' (1' // R2'))
-- where 1', R1', R2' are the "Maybe" versions of 1, R1, R2 and +' "adds" Maybe Floats.
-- See [[#Maybe monad|below]] for details.

With the // operator, dividing by zero anywhere in the computation will result in the entire computation returning a special value of the Maybe monad called "Nothing", which indicates a failure to compute a value; when one // operator returns Nothing, the definition of the Maybe monad ensures that the rest of the expression will not be executed. Otherwise, the computation will produce a numerical result, contained in the other Maybe value, which is called "Just". The result of this division operator can then be passed to other functions. This concept of "maybe values" is one situation where monads are useful.



a = do x <- [3..4]
       return (x, 42)

is transformed during compilation into:



instance Monad [] where
  m >>= f  = concatMap f m
  return x = [x]
  fail s   = []





x // y = do
  b <- y

A similar example in F# using a computation expression:

let readNum () =
  let s = Console.ReadLine()
  let succ,v = Int32.TryParse(s)
  if (succ) then Some(v) else None
let secure_div = 
  maybe { 
    let! x = readNum()
    let! y = readNum()
    if (y = 0) 
    then None
    else return (x / y)


maybe.Delay(fun () ->
  maybe.Bind(readNum(), fun x ->
    maybe.Bind(readNum(), fun y ->

Generic monadic functions


liftM2 op mx my = do
    x <- mx
    y <- my
    return (op x y)


x .*. y = liftM2 (*) x y


Mathematically, the liftM2 operator is defined by:




A monad for I/O operations is usually implemented in the language implementation rather than being defined publicly. The following example demonstrates the use of an I/O monad to interact with the user.

  putStrLn "What is your name?"
  name <- getLine

The do notation of this procedure resembles an imperative program. But the expansion of the do-block shows how the procedure is defined in pure functional terms thanks to the I/O monad, and makes explicit the information flow from one action to the next:

putStrLn "What is your name?" >>= 
   (\_ ->
      getLine >>=
         (\name ->
            putStrLn ("Nice to meet you, " ++ name ++ "!")))


Maybe monad

The Maybe monad is an option type: it handles exceptional cases in operations as special values in an underlying type.

A Maybe type is defined as the combination of "just the underlying type" (represented by wrapping the type with the Just constructor), with a value representing "nothing", i.e. undefined.

data Maybe t = Just t | Nothing

The Maybe value corresponding to an underlying value, is just that value (represented by wrapping with Just).

return x = Just x

Binding a function to something that is just a value means applying it directly to that value (the function must return a monadic type). Binding a function to nothing produces nothing.

(Just x) >>= f = f x
Nothing >>= f = Nothing

For the safe division example, (/) is the underlying function, (//) is the safe monadic version. There are two Maybe inputs. If either input is Nothing, then Nothing is returned. Otherwise the inputs are Just x and Just y, from which the operator extracts the x and y values in the underlying type. If y is zero, (/) cannot be applied, so Nothing is returned, otherwise Just (x / y) is returned:

(//) :: Maybe a -> Maybe a -> Maybe a
_ // Nothing = Nothing
Nothing // _  = Nothing
_ // Just 0 = Nothing

A more general version that applies to all types m such that m is an instance of the Monad class:

(//) :: (Fractional a, Monad m) => a -> a -> m a
_ // 0 = fail "//: divide by zero"
x // y = return (x / y)

This is the definition of the same Maybe monad in the F# language:[8]

type MaybeBuilder() =
    member this.Bind(x, f) =
        match x with
        | Some(x) -> f(x)
        | _ -> None
    member this.Delay(f) = f()
    member this.Return(x) = Some x
let maybe = MaybeBuilder()

The following definitions complete the original motivating example of the "par" function.

add x y = do
  x' <- x
  y' <- y
  return (x' + y')
par x y = let
  one = return 1
  jx = return x
  jy = return y
  in one // (add (one // jx) (one // jy))

If the result of any division is Nothing, it will propagate through the rest of the expression.

The // operator actually requires parameters of type Maybe a, so the pseudocode example in the introduction paragraph is invalid. Here is the correct version which lifts values of the basic type into monadic ones:

safeDivisions x = do
  val1 <- return 6 // return x
  val2 <- return 3 // return 1
  val3 <- val1 // val2
  return val3

From the category theory point of view, the Maybe monad is derived from the adjunction between the free functor and the underlying functor between the category of sets and the category of pointed sets.

Identity monad


Id t = t
return x = x
x >>= f = f x

A do-block in this monad performs variable substitution; do {x <- 2; return 3*x} results in 6.




-- "return" constructs a one-item list.
return x = [x]
xs >>= f = concat (map f xs)
-- The zero object is an empty list.
mzero = []






type of collections type of monoids
list monoid
finite multiset commutative monoid
finite set idempotent commutative monoid
finite permutation idempotent non-commutative monoid

State monads




return x = \s -> (x, s)

Useful state operations include:

put s' = \s -> ((), s') -- Replace the state.

Another operation applies a state monad to a given initial state:

runState t s = t s




The bind function is:



Environment monad



The following monadic operations are useful:



Writer monad




The tell monadic operation is defined by:

\text{tell} \colon W \rarr (W \times 1) = w \mapsto (w, ())

where 1 and () denote the unit type and its trivial element. It is used in combination with bind to update the auxiliary value without affecting the main computation.

Continuation monad






Other concepts that researchers have expressed as monads include:

fmap and join

Although Haskell defines monads in terms of the return and bind functions, it is also possible to define a monad in terms of return and two other operations, join and fmap. This formulation fits more closely with the definition of monads in category theory. The fmap operation, with type (tu) → (M t→M u), takes a function between two types and produces a function that does the "same thing" to values in the monad. The join operation, with type M (M t)→M t, "flattens" two layers of monadic information into one.

The two formulations are related as follows. As before, the ≡ symbol indicates equivalence between two Haskell expressions.

(fmap f) m ≡ m >>= (\x -> return (f x))
join n ≡ n >>= id
m >>= g ≡ join ((fmap g) m)



fmap id = id


return . f = fmap f . return

In addition, the join function characterizes monads:

join . fmap join = join . join
join . fmap return = join . return = id
join . fmap (fmap f) = fmap f . join


Comonads are the categorical dual of monads. They are defined by a type constructor W T and two operations: extract with type W TT for any T, and extend with type (W T → T') → W T → W T' . The operations extend and extract are expected to satisfy these laws:




The two formulations are related as follows:


Whereas monads could be said to represent side-effects, a comonads W represents a kind of context. The extract functions extracts a value from its context, while the extend function may be used to compose a pipeline of "context-dependent functions" of type W AB.

Identity comonad


Product comonad


\text{fmap}: (A \rarr B) \rarr (C \times A) \rarr (C \times B) = (c, a) \mapsto (c, f \, a)

Function comonad




Costate comonad


\text{duplicate}: ((S \rarr A) \times S) \rarr (S \rarr ((S \rarr A) \times S)) \times S = (f, s) \mapsto (s' \mapsto (f, s'), s)

See also


  1. ^ Wadler, Philip. Comprehending Monads. Proceedings of the 1990 ACM Conference on LISP and Functional Programming, Nice. 1990.
  2. ^ Wadler, Philip. The Essence of Functional Programming. Conference Record of the Nineteenth Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages. 1992.
  3. ^ A physical analogy for monads, explains monads as assembly lines.
  4. ^ a b Moggi, Eugenio (1991). "Notions of computation and monads". Information and Computation 93 (1). 
  7. ^ The three fundamental laws of Monad. See this page
  8. ^ F# Overview (IV.) - Language Oriented Programming

External links

Haskell monad tutorials

Older tutorials

Other documentation

Scala monad tutorials

Monads in other languages

Wikimedia Foundation. 2010.

Look at other dictionaries:

  • Functional programming — In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast with the… …   Wikipedia

  • Monad — may refer to: Contents 1 Philosophy 2 Mathematics and computer science 3 Music 4 Biology 5 …   Wikipedia

  • Monad transformer — In functional programming, a monad transformer is a type constructor which takes a monad as an argument and returns a monad as a result. Monad transformers can be used to compose features encapsulated by monads such as state, exception handling,… …   Wikipedia


  • Haskell (programming language) — Haskell Paradigm(s) functional, lazy/non strict, modular Appeared in 1990 Designed by Simon Peyton Jones, Lennart Aug …   Wikipedia

  • J (programming language) — Not to be confused with the J++ or J# programming languages. Infobox programming language name = J paradigm = array, functional, function level, tacit year = 1990 designer = Ken Iverson Roger Hui developer = JSoftware latest release version =… …   Wikipedia

  • Main function (programming) — In some programming languages, the main function is where a program starts execution. It is generally the first user written function run when a program starts (some system specific software generally runs before the main function), though some… …   Wikipedia

  • Comparison of programming languages (mapping) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Flow-based programming — In computer science, flow based programming (FBP) is a programming paradigm that defines applications as networks of black box processes, which exchange data across predefined connections by message passing. These black box processes can be… …   Wikipedia

  • Applicative programming language — In the classification of programming languages, an applicative programming language is designed to support the development of programs as giving the result of a function of the combined variables. Successive functional transformations are applied …   Wikipedia