https://wiki.haskell.org/api.php?action=feedcontributions&user=Remko&feedformat=atomHaskellWiki - User contributions [en]2021-10-23T12:21:18ZUser contributionsMediaWiki 1.27.4https://wiki.haskell.org/index.php?title=Monad&diff=59903Monad2015-07-06T06:28:25Z<p>Remko: /* Monads in other languages */</p>
<hr />
<div>{{Standard class|Monad|module=Control.Monad|module-doc=Control-Monad|package=base}}<br />
<br />
'''''Monads''''' in Haskell can be thought of as ''composable'' computation descriptions. The essence of monad is thus ''separation'' of ''composition timeline'' from the composed computation's ''execution timeline'', as well as the ability of ''computation'' to implicitly carry extra data, as pertaining to the computation itself, in addition to its ''one'' (hence the name) output, that it '''''will produce''''' when run (or queried, or called upon). This lends monads to supplementing ''pure'' calculations with features like I/O, common environment or state, etc. <br />
<br />
Each monad, or computation type, provides means, subject to '''''Monad Laws''''', to '''''(a)''''' ''create'' a description of computation action that will produce (a.k.a. "return") a given Haskell value, '''''(b)''''' somehow ''run'' a computation action description (possibly getting its output back into Haskell should the monad choose to allow it, if computations described by the monad are pure, or causing the prescribed side effects if it's not), and '''''(c)''''' ''combine'' (a.k.a. "bind") a computation action description with a ''reaction'' to it &ndash; a regular Haskell function of one argument (that will receive computation-produced value) returning another action description (using or dependent on that value, if need be) &ndash; thus creating a combined computation action description that will feed the original action's output through the reaction while automatically taking care of the particulars of the computational process itself. A monad might also define additional primitives to provide access to and/or enable manipulation of data it implicitly carries, specific to its nature.<br />
<br />
[[Image:Monads inter-dependencies 2.png|center]]<br />
<br />
Thus in Haskell, though it is a purely-functional language, side effects that '''''will be performed''''' by a computation can be dealt with and combined ''purely'' at the monad's composition time. Monads thus resemble programs in a particular [[DSL]]. While programs may describe impure effects and actions ''outside'' Haskell, they can still be combined and processed (''"assembled"'') purely, ''inside'' Haskell, creating a pure Haskell value - a computation action description that describes an impure calculation. That is how Monads in Haskell '''''separate''''' between the ''pure'' and the ''impure''. <br />
<br />
The computation doesn't have to be impure and can be pure itself as well. Then monads serve to provide the benefits of separation of concerns, and automatic creation of a computational "pipeline". Because they are very useful in practice but rather mind-twisting for the beginners, numerous tutorials that deal exclusively with monads were created (see [[Monad#Monad tutorials|monad tutorials]]).<br />
<br />
== Common monads ==<br />
Most common applications of monads include:<br />
* Representing failure using <hask>Maybe</hask> monad<br />
* Nondeterminism using <hask>List</hask> monad to represent carrying multiple values<br />
* State using <hask>State</hask> monad<br />
* Read-only environment using <hask>Reader</hask> monad<br />
* I/O using <hask>IO</hask> monad<br />
<br />
== Monad class ==<br />
<br />
Monads can be viewed as a standard programming interface to various data or control structures, which is captured by the <hask>Monad</hask> class. All common monads are members of it:<br />
<br />
<haskell><br />
class Monad m where<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
(>>) :: m a -> m b -> m b<br />
return :: a -> m a<br />
fail :: String -> m a<br />
</haskell><br />
<br />
In addition to implementing the class functions, all instances of Monad should obey the following equations, or '''''Monad Laws''''':<br />
<br />
<haskell><br />
return a >>= k = k a<br />
m >>= return = m<br />
m >>= (\x -> k x >>= h) = (m >>= k) >>= h<br />
</haskell><br />
<br />
See [[Monad laws|this intuitive explanation]] of why they should obey the Monad laws. It basically says that monad's reactions should be associative under Kleisli composition, defined as <code>(f >=> g) x = f x >>= g</code>, with <code>return</code> its left and right identity element.<br />
<br />
Any Monad can be made a [[Functor]] by defining <br />
<br />
<haskell><br />
fmap ab ma = ma >>= (return . ab)<br />
</haskell><br />
<br />
However, the Functor class is not a superclass of the Monad class. See [[Functor hierarchy proposal]].<br />
<br />
== Special notation ==<br />
<br />
In order to improve the look of code that uses monads Haskell provides a special [[syntactic sugar]] called <hask>do</hask>-notation. For example, the following expression:<br />
<br />
<haskell><br />
thing1 >>= (\x -> func1 x >>= (\y -> thing2 <br />
>>= (\_ -> func2 y >>= (\z -> return z))))<br />
</haskell><br />
<br />
which can be written more clearly by breaking it into several lines and omitting parentheses:<br />
<br />
<haskell><br />
thing1 >>= \x -><br />
func1 x >>= \y -><br />
thing2 >>= \_ -><br />
func2 y >>= \z -><br />
return z<br />
</haskell><br />
<br />
This can also be written using the <hask>do</hask>-notation as follows:<br />
<br />
<haskell><br />
do<br />
x <- thing1<br />
y <- func1 x<br />
thing2<br />
z <- func2 y<br />
return z<br />
</haskell><br />
<br />
Code written using <hask>do</hask>-notation is transformed by the compiler to ordinary expressions that use the functions from the <hask>Monad</hask> class.<br />
<br />
When using <hask>do</hask>-notation and a monad like <hask>State</hask> or <hask>IO</hask> programs look very much like programs written in an imperative language as each line contains a statement that can change the simulated global state of the program and optionally binds a (local) variable that can be used by the statements later in the code block.<br />
<br />
It is possible to intermix the <hask>do</hask>-notation with regular notation.<br />
<br />
More on <hask>do</hask>-notation can be found in a section of [[Monads as computation#Do notation|Monads as computation]] and in other [[Monad#Monad tutorials|tutorials]].<br />
<br />
== Commutative monads ==<br />
'''Commutative monads''' are monads for which the order of actions makes no difference (they '''commute'''), that is when following code:<br />
<haskell><br />
do<br />
a <- actA<br />
b <- actB<br />
m a b<br />
</haskell><br />
is the same as:<br />
<haskell><br />
do<br />
b <- actB<br />
a <- actA<br />
m a b<br />
</haskell><br />
<br />
Examples of commutative include:<br />
* <hask>Reader</hask> monad<br />
* <hask>Maybe</hask> monad<br />
<br />
== Monad tutorials ==<br />
<br />
Monads are known for being deeply confusing to lots of people, so there are plenty of tutorials specifically related to monads. Each takes a different approach to Monads, and hopefully everyone will find something useful.<br />
<br />
See the [[Monad tutorials timeline]] for a comprehensive list of monad tutorials.<br />
<br />
== Monad reference guides ==<br />
<br />
An explanation of the basic Monad functions, with examples, can be found in the reference guide [http://members.chello.nl/hjgtuyl/tourdemonad.html A tour of the Haskell Monad functions], by Henk-Jan van Tuyl.<br />
<br />
== Monad research ==<br />
<br />
A collection of [[Research_papers/Monads_and_arrows|research papers]] about monads.<br />
<br />
== Monads in other languages ==<br />
<br />
Implementations of monads in other languages.<br />
<br />
* [http://www.reddit.com/r/programming/comments/1761q/monads_in_c_pt_ii/ C]<br />
* [https://github.com/clojure/algo.monads Clojure]<br />
* [http://cml.cs.uchicago.edu/pages/cml.html CML.event] ?<br />
* [http://www.st.cs.ru.nl/papers/2010/CleanStdEnvAPI.pdf Clean] State monad<br />
* [http://cratylus.freewebspace.com/monads-in-javascript.htm JavaScript]<br />
* [http://www.ccs.neu.edu/home/dherman/browse/code/monads/JavaMonads/ Java]<br />
* [http://permalink.gmane.org/gmane.comp.lang.concatenative/1506 Joy]<br />
* [http://research.microsoft.com/en-us/um/people/emeijer/Papers/XLinq%20XML%20Programming%20Refactored%20(The%20Return%20Of%20The%20Monoids).htm LINQ]<br />
* [http://common-lisp.net/project/cl-monad-macros/monad-macros.htm Lisp]<br />
* [http://lambda-the-ultimate.org/node/1136#comment-12448 Miranda]<br />
* OCaml:<br />
** [http://www.cas.mcmaster.ca/~carette/pa_monad/ OCaml]<br />
** [https://mailman.rice.edu/pipermail/metaocaml-users-l/2005-March/000057.html more]<br />
** [http://www.cas.mcmaster.ca/~carette/metamonads/ MetaOcaml]<br />
** [http://blog.enfranchisedmind.com/2007/08/a-monad-tutorial-for-ocaml/ A Monad Tutorial for Ocaml]<br />
* [http://www.reddit.com/r/programming/comments/p66e/are_monads_actually_used_in_anything_except Perl6 ?]<br />
* [http://logic.csci.unt.edu/tarau/research/PapersHTML/monadic.html Prolog] <br />
* Python<br />
** [http://code.activestate.com/recipes/439361/ Python]<br />
** Twisted's [http://www.reddit.com/r/programming/comments/p66e/are_monads_actually_used_in_anything_except/cp8eh Deferred monad]<br />
* Ruby:<br />
** [http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html Ruby]<br />
** [http://meta-meta.blogspot.com/2006/12/monads-in-ruby-part-1-identity.html and other implementation]<br />
* Scheme:<br />
** [http://okmij.org/ftp/Scheme/monad-in-Scheme.html Scheme]<br />
** [http://www.ccs.neu.edu/home/dherman/research/tutorials/monads-for-schemers.txt also]<br />
** Monads & Do notation: [https://el-tramo.be/blog/async-monad/ Part 1] [https://el-tramo.be/blog/scheme-monads/ Part 2]<br />
* [http://wiki.tcl.tk/13844 Tcl]<br />
* [http://okmij.org/ftp/Computation/monadic-shell.html The Unix Shell]<br />
* [http://okmij.org/ftp/Computation/monads.html More monads by Oleg]<br />
* [http://lambda-the-ultimate.org/node/2322 CLL]: a concurrent language based on a first-order intuitionistic linear logic where all right synchronous connectives are restricted to a monad. <br />
<br />
Unfinished:<br />
<br />
* [http://wiki.tcl.tk/14295 Parsing], [http://wiki.tcl.tk/13844 Maybe and Error] in Tcl<br />
<br />
And possibly there exist:<br />
<br />
* Standard ML (via modules?)<br />
<br />
Please add them if you know of other implementations.<br />
<br />
[http://lambda-the-ultimate.org/node/1136 Collection of links to monad implementations in various languages.] on [http://lambda-the-ultimate.org/ Lambda The Ultimate].<br />
<br />
==Interesting monads==<br />
<br />
A list of monads for various evaluation strategies and games:<br />
<br />
* [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Identity.html Identity monad] - the trivial monad.<br />
* [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html Optional results from computations] - error checking without null.<br />
* [http://hackage.haskell.org/packages/archive/monad-mersenne-random/latest/doc/html/Control-Monad-Mersenne-Random.html Random values] - run code in an environment with access to a stream of random numbers.<br />
* [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Reader.html Read only variables] - guarantee read-only access to values.<br />
* [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Writer-Lazy.html Writable state] - i.e. log to a state buffer<br />
* [http://www.haskell.org/haskellwiki/New_monads/MonadSupply A supply of unique values] - useful for e.g. guids or unique variable names<br />
* [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad-ST.html ST - memory-only, locally-encapsulated mutable variables]. Safely embed mutable state inside pure functions.<br />
* [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State-Lazy.html Global state] - a scoped, mutable state.<br />
* [http://hackage.haskell.org/packages/archive/Hedi/latest/doc/html/Undo.html Undoable state effects] - roll back state changes<br />
* [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad-Instances.html#t:Monad Function application] - chains of function application.<br />
* [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Error.html Functions which may error] - track location and causes of errors.<br />
* [http://hackage.haskell.org/packages/archive/stm/latest/doc/html/Control-Monad-STM.html Atomic memory transactions] - software transactional memory<br />
* [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Cont.html Continuations] - computations which can be interrupted and resumed.<br />
* [http://www.haskell.org/ghc/docs/latest/html/libraries/base/System-IO.html#t%3AIO IO] - unrestricted side effects on the world<br />
* [http://hackage.haskell.org/packages/archive/level-monad/0.4.1/doc/html/Control-Monad-Levels.html Search monad] - bfs and dfs search environments.<br />
* [http://hackage.haskell.org/packages/archive/stream-monad/latest/doc/html/Control-Monad-Stream.html non-determinism] - interleave computations with suspension.<br />
* [http://hackage.haskell.org/packages/archive/stepwise/latest/doc/html/Control-Monad-Stepwise.html stepwise computation] - encode non-deterministic choices as stepwise deterministic ones<br />
* [http://logic.csci.unt.edu/tarau/research/PapersHTML/monadic.html Backtracking computations]<br />
* [http://www.cs.cornell.edu/people/fluet/research/rgn-monad/index.html Region allocation effects]<br />
* [http://hackage.haskell.org/packages/archive/logict/0.5.0.2/doc/html/Control-Monad-Logic.html LogicT] - backtracking monad transformer with fair operations and pruning<br />
* [http://hackage.haskell.org/packages/archive/monad-task/latest/doc/html/Control-Monad-Task.html concurrent events and threads] - refactor event and callback heavy programs into straight-line code via co-routines<br />
* [http://hackage.haskell.org/package/QIO QIO] - The Quantum computing monad<br />
* [http://hackage.haskell.org/packages/archive/full-sessions/latest/doc/html/Control-Concurrent-FullSession.html Pi calculus] - a monad for Pi-calculus style concurrent programming<br />
* [http://www-fp.dcs.st-and.ac.uk/~kh/papers/pasco94/subsubsectionstar3_3_2_3.html Commutable monads for parallel programming]<br />
* [http://hackage.haskell.org/package/stream-monad Simple, Fair and Terminating Backtracking Monad]<br />
* [http://hackage.haskell.org/package/control-monad-exception Typed exceptions with call traces as a monad]<br />
* [http://hackage.haskell.org/package/control-monad-omega Breadth first list monad]<br />
* [http://hackage.haskell.org/package/control-monad-queue Continuation-based queues as monads]<br />
* [http://hackage.haskell.org/package/full-sessions Typed network protocol monad]<br />
* [http://hackage.haskell.org/package/level-monad Non-Determinism Monad for Level-Wise Search]<br />
* [http://hackage.haskell.org/package/monad-tx Transactional state monad]<br />
* [http://hackage.haskell.org/package/monadiccp A constraint programming monad]<br />
* [http://hackage.haskell.org/package/ProbabilityMonads A probability distribution monad]<br />
* [http://hackage.haskell.org/package/set-monad Sets] - Set computations<br />
* [http://hackage.haskell.org/package/http-monad/ HTTP] - http connections as a monadic environment<br />
* [http://hackage.haskell.org/package/monad-memo Memoization] - add memoization to code<br />
<br />
There are many more interesting instance of the monad abstraction out there. Please add them as you come across each species.<br />
<br />
==Fun==<br />
<br />
* If you are tired of monads, you can easily [http://www.haskell.org.monadtransformer.parallelnetz.de/haskellwiki/Category:Monad get rid of them].<br />
<br />
==See also==<br />
<br />
* [[What a Monad is not]]<br />
* [[Monads as containers]]<br />
* [[Monads as computation]]<br />
* [[Monad/ST]]<br />
* [http://www.haskellforall.com/2012/06/you-could-have-invented-free-monads.html Why free monads matter] (blog article)<br />
<br />
[[Category:Monad|*]]</div>Remko