Monad (sans metaphors)
(Main article in category monad)
|Line 1:||Line 1:|
=== Introduction ===
=== Introduction ===
Latest revision as of 21:04, 1 November 2009
 1 Introduction
Many discussions of Haskell Monads seek to explain them through the use of a variety of metaphors. This page attempts to simply provide a more technical yet straightforward description of Monads in Haskell.
 2 So what is a monad?
A Monad is a type constructor with two operations, implementing a standard interface and following a few simple rules.
The Monad type class tells you the interface (what operations you've got, and their types), the Monad laws tell you what all types implementing that interface should have in common.The Monadic interface gives you two operations: one to throw things into a Monad thing (
The Monad laws tell you two useful facts about Monad things thrown together in that way: whatever it is the Monad does, anything just thrown into it will take no part in that action, and whichever way you use that chaining operation, the structure of chaining is irrelevant - only the ordering of chained Monad things matters.
There are usually other ways to create 'primitive' Monadic things, which can be combined into complex Monadic structures using the operations from the Monad interface.
There is usually a way to interpret Monadic structures built in this way - a 'run' operation of some kind. Examples include:
- I/O: The 'primitive Monadic things' are basic I/O operations. The 'run' operation is outside the language, applied to 'Main.main', and interprets (abstract) IO Monad structures sequentially, starting with the leftmost innermost I/O operation in the structure and applying the second argument of to the result of executing the first.(>>=)
- : The 'primitive Monadic things' are lists. The 'run' operation is the identity, i.e the lists are directly exposed as data structures. creates a singleton list.returnapplies its second argument to each element of its first argument and concatenates the results ((>>=)).concatMap
- State: The 'primitive Monadic things' are operations on a state type, returning a result and a state. 'run' is and applies a (possibly) complex Monadic thing to an input state, returning a result and a (modified) state.runStatereturns its parameter, passing its input state unchanged.returnapplies its first parameter to the input state, applies its second parameter to the result value and result state of the first.(>>=)
 3 Source
- Claus Reinke on Haskell-Cafe: Monad Description For Imperative Programmer