|
|
Line 1: |
Line 1: |
| In [[functional programming]], a '''monad''' is a structure that represents [[computation]]s defined as sequences of steps. A [[Type (computer science)|type]] with a monad structure defines what it means to [[Block (programming)|chain operations]], or nest [[Function (computer science)|functions]] of that type together. This allows the programmer to build [[Pipeline (software)|pipelines]] that process data in steps, in which each action is [[Decorator pattern|decorated]] with additional processing rules provided by the monad.<ref name="RealWorldHaskell">O'Sullivan, Bryan; Goerzen, John; Stewart, Don. ''[http://book.realworldhaskell.org/ Real World Haskell]''. O'Reilly, 2009. ch. 14.</ref> As such, monads have been described as "programmable semicolons"; a semicolon is the operator used to chain together individual [[statement (computer programming)|statement]]s in many [[imperative programming]] languages,<ref name="RealWorldHaskell"/> thus the expression implies that extra code will be executed between the statements in the pipeline. Monads have also been explained with a [[physical metaphor]] as [[assembly line]]s, where a conveyor belt transports data between functional units that transform it one step at a time.<ref>{{cite web|archiveurl=http://web.archive.org/web/20100910074354/http://www.haskell.org/all_about_monads/html/analogy.html|archivedate=10 sep 2010|url=http://www.haskell.org/all_about_monads/html/analogy.html|title=A physical analogy for monads}}</ref> They can also be seen as a functional [[design pattern]] to build [[Parameterized type|generic types]].<ref>{{cite web | url=http://ericlippert.com/2013/02/21/monads-part-one/ | title=Monads, part one | accessdate=6 September 2013 | author=Eric Lippert}}</ref>
| |
|
| |
|
| [[Purely functional]] programs can use monads to structure procedures that include sequenced operations like those found in [[structured programming]].<ref>[[Philip Wadler|Wadler, Philip]]. [http://citeseer.ist.psu.edu/wadler92comprehending.html Comprehending Monads]. Proceedings of the 1990 ACM Conference on LISP and Functional Programming, Nice. 1990.</ref><ref>Wadler, Philip. [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.38.9516 The Essence of Functional Programming]. Conference Record of the Nineteenth Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages. 1992.</ref> Many common programming concepts can be described in terms of a monad structure, including [[Side effect (computer science)|side effects]] such as [[input/output]], variable [[Assignment (computer science)|assignment]], [[exception handling]], [[parsing]], [[Nondeterministic programming|nondeterminism]], [[Concurrency (computer science)|concurrency]], and [[continuation]]s. This allows these concepts to be defined in a purely functional manner, without major extensions to the language's semantics. Languages like [[Haskell (programming language)|Haskell]] provide monads in the standard core, allowing programmers to reuse large parts of their formal definition and apply in many different libraries the same interfaces for combining functions.<ref>Hughes, J. (2005). [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.96.9534&rep=rep1&type=pdf Programming with arrows]. In Advanced Functional Programming (pp. 73-129). Springer Berlin Heidelberg. "</ref>
| |
|
| |
|
| Formally, a monad consists of a [[type constructor]] ''M'' and two operations, ''bind'' and ''return'' (where ''return'' is often also called ''unit''). The operations must fulfill several properties to allow the correct composition of ''monadic'' functions (i.e. functions that use values from the monad as their arguments or return value). The ''return'' operation takes a value from a plain type and puts it into a monadic container using the constructor, creating a ''monadic value''. 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, possibly with additional checks and transformations. Because a monad can insert additional operations around a program's domain logic, monads can be considered a sort of [[aspect-oriented programming]].<ref>De Meuter, Wolfgang. "[http://soft.vub.ac.be/Publications/1997/vub-prog-tr-97-10.pdf Monads as a theoretical foundation for AOP]". Workshop on Aspect Oriented Programming, ECOOP 1997.</ref> The [[domain logic]] can be defined by the application programmer in the pipeline, while required aside [[bookkeeping code|bookkeeping]] operations can be handled by a pre-defined monad built in advance.
| | Move on to the sidewalk, the concentrate belongs to the UGG snow boots endlessly! Sporting your UGG boots, and out of your ever-shifting posture! Now, boots 4 sale will give you the method to dry your beloved UGG boots in the air. Probably an individual wants to talk to: dry the boots is as simple as pie, what pay out interest to? If you think so, it would be mistaken. The improper drying process could induce UGG snow boots this sort of as UGG traditional short gray flora, Ugg Women's Kensington Boots Olive, UGG basic tall 5815 chocolate, UGG Broome 5518 black, UGG Bailey Button Triplet Chocolate, UGG Common Tall black Bomber Jacket very easily shade fading. Definitely it won't necessarily mean that you want to make your UGG boots develop into the painted deal with. If you love your UGG boots, look the proper strategy pursuing to dry your UGG. <br><br>Upend your UGG boots, keep the sole upward, and allow the h2o out. Of program, the frequent higher of the boots is tender and could not be upended. Consequently, you ought to set a crabstick into the boots to play the guidance function. The crabstick should bigger than the leg of the boot, in order to prevent the boots speak to to earth. Then place them against the wall, let them organic air drying. Keep away from by all indicates set them in the sunshine, if not, they are very easily discoloration. In particular the UGG traditional quick flora black, this kind of brunet boots will turn into malformed just after shade fading. <br><br><br>The technique is summarized by the employees of boots 4 sale, If you imagine that makes sense, you can air your New UGG in accordance with the strategy earlier mentioned. And your beloved UGG boots will maintain the identical with the first, no deformation and no coloration fading. Permit yourself grow to be the concentrate of the road now!<br><br>If you loved this write-up and you would like to receive additional information pertaining to [http://tinyurl.com/k7shbtq http://tinyurl.com/k7shbtq] kindly browse through our own internet site. |
| | |
| The name and concept comes from the eponymous construct ([[Monad (category theory)|monad]]) in [[category theory]], where monads are one particular kind of [[functor]], a mapping between categories; although the term ''monad'' in functional programming contexts is usually used with a meaning corresponding to that of the term ''[[strong monad]]'' in category theory.<ref name="moggi91" />
| |
| | |
| ==History==
| |
| The concept of monad programming appeared in the 1980s in the programming language [[Opal programming language|Opal]] even though it was called "commands" and never formally specified.{{citation needed|date=June 2013}} [[Eugenio Moggi]] first described the general use of monads to structure programs in 1991.<ref name="moggi91">{{cite journal | authorlink = Eugenio Moggi| first=Eugenio | last=Moggi | year = 1991 | title = Notions of computation and monads | journal = Information and Computation | volume = 93 | issue = 1 | pages = | url = http://www.disi.unige.it/person/MoggiE/ftp/ic91.pdf}}</ref> 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 (programming language)|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, programming language researchers and Haskell libraries designers 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 [[applicative functor]]s and [[Arrow (computer science)|arrow]]s.
| |
| | |
| For a long time, Haskell and its derivatives have been the only major users of monads in programming. There also exist formulations in [[Scheme (programming language)|Scheme]], [[Perl]], [[Python (programming language)|Python]], [[Racket (programming language)|Racket]], [[Clojure]] and [[Scala (programming language)|Scala]], and monads have been an option in the design of a new [[ML (programming language)|ML]] standard. Recently [[F Sharp (programming language)|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.<ref name="seq">{{cite web | url = http://blogs.msdn.com/dsyme/archive/2007/09/22/some-details-on-f-computation-expressions-aka-monadic-or-workflow-syntax.aspx | title = Some Details on F# Computation Expressions | accessdate = 2007-12-14}}</ref>
| |
| | |
| ==Motivating examples==
| |
| The [[Haskell (programming language)|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 article are written in [[Haskell (programming language)|Haskell]] unless noted otherwise.
| |
| | |
| We demonstrate two common examples given when introducing monads: the ''Maybe'' monad and the ''I/O'' monad. Monads are of course not restricted to the Haskell language, though: the second example shows the ''Writer'' monad in [[JavaScript]].
| |
| | |
| ===The Maybe monad===
| |
| Now consider the [[option type]] ''Maybe a'', representing a value that is either a single value of type ''a'', or no value at all. To distinguish these, we have two [[algebraic data type]] constructors: <code>Just x</code>, containing the value <code>x</code>, or <code>Nothing</code>, containing no value.
| |
| <source lang="haskell">
| |
| data Maybe t = Just t | Nothing
| |
| </source>
| |
| We would like to be able to use this type as a simple sort of [[checked exception]]: at any point in a computation, the computation may fail, which causes the rest of the computation to be skipped and the final result to be <code>Nothing</code>. If all steps of the calculation succeed, the final result is <code>Just x</code> for some value <code>x</code>.
| |
| | |
| In the following example, <code>add</code> is a function that takes two arguments of type ''Maybe Int'', and returns a result of the same type. If both <code>mx</code> and <code>my</code> have <code>Just</code> values, we want to return <code>Just</code> their sum; but if either <code>mx</code> or <code>my</code> is <code>Nothing</code>, we want to return <code>Nothing</code>. If we naïvely attempt to write functions with this kind of behavior, we'll end up with a nested series of "if <code>Nothing</code> then <code>Nothing</code> else do something with the <code>x</code> in <code>Just x</code>" cases that will quickly become unwieldy:<ref name="RealWorldHaskell" />
| |
| <source lang="haskell">
| |
| add :: Maybe Int -> Maybe Int -> Maybe Int
| |
| add mx my =
| |
| case mx of
| |
| Nothing -> Nothing
| |
| Just x -> case my of
| |
| Nothing -> Nothing
| |
| Just y -> Just (x + y)
| |
| </source>
| |
| To alleviate this, we can define operations for chaining these computations together. The ''bind'' binary operator (<code>>>=</code>) chains the results of one computation that could fail into a function that chooses another computation that could fail. If the first argument is <code>Nothing</code>, the second argument (the function) is ignored and the entire operation simply fails. If the first argument is <code>Just x</code>, we pass <code>x</code> to the function to get a new ''Maybe'' value, which may or may not result in a <code>Just</code> value.
| |
| <source lang="haskell">
| |
| (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
| |
| Nothing >>= _ = Nothing
| |
| (Just x) >>= f = f x
| |
| </source>
| |
| We already have a value constructor that returns a value without affecting the computation's additional state: <code>Just</code>.
| |
| <source lang="haskell">
| |
| return :: a -> Maybe a
| |
| return x = Just x
| |
| </source>
| |
| We can then write the example as:
| |
| <source lang="haskell">
| |
| add :: Maybe Int -> Maybe Int -> Maybe Int
| |
| add mx my =
| |
| mx >>= (\x ->
| |
| my >>= (\y ->
| |
| return (x + y)))
| |
| </source>
| |
| | |
| Using some additional [[syntactic sugar]] known as [[do-notation]], the example can be written as:
| |
| <source lang="haskell">
| |
| add :: Maybe Int -> Maybe Int -> Maybe Int
| |
| add mx my = do
| |
| x <- mx
| |
| y <- my
| |
| return (x + y)
| |
| </source>
| |
| | |
| Since this type of operation is quite common, there is a standard function in Haskell (<code>liftM2</code>) to take two monadic values (here: two Maybes) and combine their contents (two numbers) using another function (addition), making it possible to write the previous example as
| |
| <source lang="haskell">
| |
| add :: Maybe Int -> Maybe Int -> Maybe Int
| |
| add = liftM2 (+)
| |
| </source>
| |
| (Writing out the definition of liftM2 yields the code presented above in do-notation.)
| |
| | |
| === The Writer monad ===
| |
| The Writer monad allows a process to carry additional information "on the side", along with the computed value. This can be useful to log error or debugging information which is not the primary result.<ref>{{cite web|url=http://monads.haskell.cz/html/writermonad.html|title=The Writer monad|publisher=haskell.cz}}</ref>
| |
| | |
| The following example implements a Writer monad in Javascript:
| |
| | |
| First, a Writer monad is declared. Function ''unit'' creates a new value type from a basic type, with an empty log string attached to it; and ''bind'' applies a function to an old value, and returns the new result value with an expanded log. The [[Bracket#Uses_of_.22.5B.22_and_.22.5D.22|array brackets]] work here as the monad's type constructor, creating a value of the monadic type for the Writer monad from simpler components (the value in position 0 of the array, and the log string in position 1).
| |
| <source lang="Javascript">
| |
| var unit = function(value) { return [value, ''] };
| |
| </source>
| |
| | |
| <source lang="Javascript">
| |
| var bind = function(monadicValue, transformWithLog) {
| |
| var value = monadicValue[0],
| |
| log = monadicValue[1],
| |
| result = transformWithLog(value);
| |
| return [ result[0], log + result[1] ];
| |
| };
| |
| </source>
| |
| | |
| ''pipeline'' is an auxiliary function that concatenates a sequence of ''bind''s applied to an array of functions.
| |
| | |
| <source lang="Javascript">
| |
| var pipeline = function(monadicValue, functions) {
| |
| for (var key in functions) {
| |
| monadicValue = bind(monadicValue, functions[key]);
| |
| }
| |
| return monadicValue;
| |
| };
| |
| </source>
| |
| | |
| Examples of functions that return values of the type expected by the above Writer monad:
| |
| <source lang="Javascript">
| |
| var squared = function(x) {
| |
| return [x * x, 'was squared.'];
| |
| };
| |
| | |
| var halved = function(x) {
| |
| return [x / 2, 'was halved.'];
| |
| };
| |
| </source>
| |
| | |
| Finally, an example of using the monad to build a pipeline of mathematical functions with debug information on the side:{{clarify|date=July 2013}}
| |
| <source lang="Javascript">
| |
| pipeline(unit(4), [squared, halved]); // [8, "was squared.was halved."]
| |
| </source>
| |
| | |
| ===The I/O monad===
| |
| In a [[purely functional]] language, such as Haskell, functions cannot have any externally visible side effects as part of the function semantics. 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.<ref>[[Simon Peyton Jones|Peyton Jones, Simon L.]]; Wadler, Philip. [http://citeseer.ist.psu.edu/peytonjones93imperative.html Imperative Functional Programming]. Conference record of the Twentieth Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, Charleston, South Carolina. 1993</ref> In the Haskell notation, a value of type ''IO a'' represents an action that, when performed, produces a value of type ''a''.
| |
| | |
| We can think of a value of type ''IO'' as a function that takes as its argument the current state of the world, and will return a new world 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 be applied in order as steps of state changes. This process is similar to how a [[temporal logic]] represents the passage of time using only [[Declarative programming|declarative]] propositions.
| |
| | |
| We would like to be able to describe all of the basic types of I/O operations, e.g. write text to [[standard output]], read text from standard input, read and write files, send data over networks, etc. In addition, we need to be able to compose these primitives to form larger programs. For example, we would like to be able to write:
| |
| <source lang="haskell">
| |
| main :: IO ()
| |
| main = do
| |
| putStrLn "What is your name?"
| |
| name <- getLine
| |
| putStrLn ("Nice to meet you, " ++ name ++ "!")
| |
| </source>
| |
| How can we formalize this intuitive notation? To do this, we need to be able to perform some basic operations with I/O actions:
| |
| * We should be able to sequence two I/O operations together. In Haskell, this is written as an infix operator <code>>></code>, so that <code>putStrLn "abc" >> putStrLn "def"</code> is an I/O action that prints two lines of text to the console. The type of <code>>></code> is ''IO a → IO b → IO b'', meaning that the operator takes two I/O operations and returns a third that sequences the two together and returns the value of the second.
| |
| * We should have an I/O action which does ''nothing''. That is, it returns a value but has no side effects. In Haskell, this action constructor is called <code>return</code>; it has type ''a → IO a''.
| |
| * More subtly, we should be able to determine our next action based on the results of previous actions. To do this, Haskell has an operator <code>>>=</code> (pronounced ''bind'') with type ''IO a → (a → IO b) → IO b''. That is, the operand on the left is an I/O action that returns a value of type <code>a</code>; the operand on the right is a function that can pick an I/O action based on the value produced by the action on the left. The resulting combined action, when performed, performs the first action, then evaluates the function with the first action's return value, then performs the second action, and finally returns the second action's value.
| |
| | |
| :An example of the use of this operator in Haskell would be <code>getLine >>= putStrLn</code>, which reads a single line of text from standard input and echos it to standard output. Note that the first operator, <code>>></code>, is just a special case of this operator in which the return value of the first action is ignored and the selected second action is always the same.
| |
| | |
| It is not necessarily obvious that the three preceding operations, along with a suitable primitive set of I/O operations, allow us to define ''any program action whatsoever'', including data transformations (using [[lambda expressions]]), if/then control flow, and looping control flows (using recursion). We can write the above example as one long expression:
| |
| <source lang="haskell">
| |
| main =
| |
| putStrLn "What is your name?" >>
| |
| getLine >>= \name ->
| |
| putStrLn ("Nice to meet you, " ++ name ++ "!")
| |
| </source>
| |
| The pipeline structure of the ''bind'' operator ensures that the ''getLine'' and ''putStrLn'' operations get evaluated only once and in the given order, so that the side-effects of extracting text from the input stream and writing to the output stream are correctly handled in the functional pipeline. This remains true even if the language performs [[Out-of-order execution|out-of-order]] or [[lazy evaluation]] of functions.
| |
| | |
| Clearly, there is some common structure between the I/O definitions and the Maybe definitions, even though they are different in many ways. Monads are an abstraction upon the structures described above, and many similar structures, that finds and exploits the commonalities. The general monad concept includes any situation where the programmer wants to carry out a purely functional computation while a related computation is carried out on the side.
| |
| | |
| ==Formal definition==
| |
| A monad is a construction that, given an underlying [[type system]], embeds a corresponding type system (called the ''monadic type system'') into it (that is, each monadic type acts as the underlying type). This monadic type system preserves all significant aspects of the underlying type system, while adding features particular to the monad.<ref group="note">Technically, the monad is not required to preserve the underlying type. For example, the trivial monad in which there is only one polymorphic value which is produced by all operations satisfies all of the axioms for a monad. Conversely, the monad is not required to add any additional structure; the identity monad, which simply preserves the original type unchanged, also satisfies the monad axioms and is useful as a recursive base for monad transformers.</ref>
| |
| | |
| The usual formulation of a monad for programming is known as a [[Kleisli triple]], and has the following components:
| |
| #A ''type constructor'' that defines, for every underlying type, how to obtain a corresponding monadic type. In Haskell's notation, the name of the monad represents the type constructor. If ''M'' is the name of the monad and ''t'' is a data type, then ''M t'' is the corresponding type in the monad.
| |
| #A ''unit function'' that maps a value in an underlying type to a value in the corresponding monadic type. The unit function has the polymorphic type ''t→M t''. The result is normally the "simplest" value in the corresponding type that completely preserves the original value (simplicity being understood appropriately to the monad). In Haskell, this function is called <code>return</code> due to the way it is used in the do-notation described later.
| |
| #A ''binding operation'' of polymorphic type ''(M t)→(t→M u)→(M u)'', which Haskell represents by the [[infix notation|infix]] operator <code>>>=</code>. Its first argument is a value in a monadic type, its second argument is a function that maps from the underlying type of the first argument to another monadic type, and its result is in that other monadic type. Typically, the binding operation can be understood as having four stages:
| |
| ##The monad-related structure on the first argument is "pierced" to expose any number of values in the underlying type t.
| |
| ##The given function is applied to all of those values to obtain values of type (M u).
| |
| ##The monad-related structure on those values is also pierced, exposing values of type u.
| |
| ##Finally, the monad-related structure is reassembled over all of the results, giving a single value of type (M u).
| |
| | |
| Given a type constructor ''M'', in most contexts, a value of type ''M a'' can be thought of as an action that returns a value of type ''a''. The ''return'' operation takes a value from a plain type ''a'' and puts it into a monadic container of type ''M a''; the ''bind'' operation chains a monadic value of type ''M a'' with a function of type ''a → M b'' to create a monadic value of type ''M b''.
| |
| | |
| ===Monad laws===
| |
| For a monad to behave correctly, the definitions must obey a few axioms, together called the monad laws.<ref>{{cite web|url=http://www.haskell.org/haskellwiki/Monad_laws|title=Monad laws|work=HaskellWiki|publisher=haskell.org|accessdate=2011-12-11}}</ref> The ≡ symbol indicates equivalence between two Haskell expressions in the following text.
| |
| | |
| * ''return'' acts approximately as a [[neutral element]] of <tt>>>=</tt>, in that:
| |
| ** <source lang="haskell" enclose="none">(return x) >>= f ≡ f x</source>
| |
| ** <source lang="haskell" enclose="none">m >>= return ≡ m</source>
| |
| * Binding two functions in succession is the same as binding one function that can be determined from them:
| |
| ** <source lang="haskell" enclose="none">(m >>= f) >>= g ≡ m >>= ( \x -> (f x >>= g) )</source>
| |
| | |
| The axioms can also be expressed using expressions in [[#do-notation|do-block style]]:
| |
| * <source lang="haskell" enclose="none">do { f x } ≡ do { v <- return x; f v }</source>
| |
| * <source lang="haskell" enclose="none">do { m } ≡ do { v <- m; return v }</source>
| |
| * <source lang="haskell" enclose="none">do { x <- m; y <- f x; g y } ≡ do { y <- do { x <- m; f x }; g y }</source>
| |
| or using the monadic composition operator, <source lang="haskell" enclose="none">(f >=> g) x = (f x) >>= g</source>:
| |
| *<source lang="haskell" enclose="none">return >=> g ≡ g</source>
| |
| *<source lang="haskell" enclose="none">f >=> return ≡ f</source>
| |
| *<source lang="haskell" enclose="none">(f >=> g) >=> h ≡ f >=> (g >=> h)</source>
| |
| | |
| ===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 (''t''→''u'') → M ''t''→M ''u'',<ref>{{cite web|title=Functors, Applicative Functors and Monoids|publisher=learnyouahaskell.com|url=http://learnyouahaskell.com/functors-applicative-functors-and-monoids}}</ref> 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:
| |
| <source lang="haskell">
| |
| fmap f m = m >>= (return . f)
| |
| join n = n >>= id
| |
| | |
| m >>= g ≡ join ((fmap g) m)
| |
| </source>
| |
| | |
| Here, m has the type M ''t'', n has the type M (M ''r''), f has the type ''t'' → ''u'', and g has the type t → M ''v'', where ''t'', ''r'', ''u'' and ''v'' are underlying types.
| |
| | |
| The fmap function is defined for any [[functor]] in the category of types and functions, not just for monads. It is expected to satisfy the functor laws:
| |
| <source lang="haskell">
| |
| fmap id ≡ id
| |
| fmap (f . g) ≡ (fmap f) . (fmap g)
| |
| </source>
| |
| | |
| The ''return'' function characterizes [[pointed functor]]s in the same category, by accounting for the ability to "lift" values into the functor. It should satisfy the following law:
| |
| <source lang="haskell">
| |
| return . f ≡ fmap f . return
| |
| </source>
| |
| | |
| In addition, the ''join'' function characterizes monads:
| |
| <source lang="haskell">
| |
| join . fmap join = join . join
| |
| join . fmap return = join . return = id
| |
| join . fmap (fmap f) = fmap f . join
| |
| </source>
| |
| | |
| ===Additive monads {{anchor|Additive monad}}===
| |
| An '''additive monad''' is a monad endowed with a monadic zero ''mzero'' and a binary operator ''mplus'' satisfying the [[monoid]] laws, with the monadic zero as unit. The operator ''mplus'' has type ''M t'' → ''M t'' → ''M 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.)
| |
| | |
| Binding ''mzero'' with any function produces the zero for the result type, just as 0 multiplied by any number is 0.
| |
| <source lang="haskell">
| |
| mzero >>= f ≡ mzero
| |
| </source>
| |
| | |
| Similarly, binding any ''m'' with a function that always returns a zero results in a zero
| |
| <source lang="haskell">
| |
| m >>= (\x -> mzero) ≡ mzero
| |
| </source>
| |
| | |
| Intuitively, the zero represents a value in the monad that has only monad-related structure and no values from the underlying type. In the Maybe monad, "Nothing" is a zero. In the List monad, "[]" (the empty list) is a zero.
| |
| | |
| ==Syntactic sugar: <code>do</code>-notation {{anchor|do-notation}} ==
| |
| Although there are times when it makes sense to use the ''bind'' operator <code>>>=</code> directly in a program, it is more typical to use a format called ''do-notation'' (''perform-notation'' in [[OCaml]], ''computation expressions'' in [[F Sharp (programming language)|F#]]), that mimics the appearance of imperative languages. The compiler translates do-notation to expressions involving <code>>>=</code>. For example, the following code:
| |
| | |
| <source lang="haskell">
| |
| a = do x <- [3..4]
| |
| [1..2]
| |
| return (x, 42)
| |
| </source>
| |
| is transformed during compilation into:
| |
| | |
| <source lang="haskell">
| |
| a = [3..4] >>= (\x -> [1..2] >>= (\_ -> return (x, 42)))
| |
| </source>
| |
| It is helpful to see the implementation of the list monad, and to know that concatMap maps a function over a list and concatenates (flattens) the resulting lists:
| |
| | |
| <source lang="haskell">
| |
| instance Monad [] where
| |
| m >>= f = concatMap f m
| |
| return x = [x]
| |
| fail s = []
| |
| </source>
| |
| Therefore, the following transformations hold and all the following expressions are equivalent:
| |
| | |
| <source lang="haskell">
| |
| a = [3..4] >>= (\x -> [1..2] >>= (\_ -> return (x, 42)))
| |
| a = [3..4] >>= (\x -> concatMap (\_ -> return (x, 42)) [1..2] )
| |
| a = [3..4] >>= (\x -> [(x,42),(x,42)] )
| |
| a = concatMap (\x -> [(x,42),(x,42)] ) [3..4]
| |
| a = [(3,42),(3,42),(4,42),(4,42)]
| |
| </source>
| |
| Notice that the list <tt>[1..2]</tt> is not used. The lack of a left-pointing arrow, translated into a binding to a function that ignores its argument, indicates that only the monadic structure is of interest, not the values inside it, e.g. for a state monad this might be used for changing the state without producing any more result values. The do-block notation can be used with any monad as it is simply syntactic sugar for <code>>>=</code>.
| |
| | |
| The following definitions for safe division for values in the Maybe monad are also equivalent:
| |
| | |
| <source lang="haskell">
| |
| x // y = do
| |
| a <- x -- Extract the values "inside" x and y, if there are any.
| |
| b <- y
| |
| if b == 0 then Nothing else Just (a / b)
| |
| | |
| x // y = x >>= (\a -> y >>= (\b -> if b == 0 then Nothing else Just (a / b)))
| |
| </source>
| |
| A similar example in F# using a computation expression:
| |
| <source lang="ocaml">
| |
| 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)
| |
| }
| |
| </source>
| |
| | |
| The syntactic sugar of the maybe block would get translated internally to the following expression:
| |
| | |
| <source lang="ocaml">
| |
| maybe.Delay(fun () ->
| |
| maybe.Bind(readNum(), fun x ->
| |
| maybe.Bind(readNum(), fun y ->
| |
| if (y=0) then None else maybe.Return( x/y ))))
| |
| </source>
| |
| | |
| == Generic monadic functions ==
| |
| Given values produced by safe division, we might want to carry on doing calculations without having to check manually if they are <tt>Nothing</tt> (i.e. resulted from an attempted division by zero). We can do this using a "[[Lift (mathematics)|lifting]]" function, which we can define not only for <tt>Maybe</tt> but for arbitrary monads. In Haskell this is called <tt>liftM2</tt>:
| |
| <source lang="haskell">
| |
| liftM2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c
| |
| liftM2 op mx my = do
| |
| x <- mx
| |
| y <- my
| |
| return (op x y)
| |
| </source>
| |
| Recall that arrows in a type [[Currying#Definition|associate to the right]], so <tt>liftM2</tt> is a function that takes a binary function as an argument and returns another binary function. The type signature says: If <tt>m</tt> is a monad, we can "lift" any binary function into it. For example:
| |
| <source lang="haskell">
| |
| (.*.) :: (Monad m, Num a) => m a -> m a -> m a
| |
| x .*. y = liftM2 (*) x y
| |
| </source>
| |
| defines an operator <tt>(.*.)</tt> which multiplies two numbers, unless one of them is <tt>Nothing</tt> (in which case it again returns <tt>Nothing</tt>). The advantage here is that we need not dive into the details of the implementation of the monad; if we need to do the same kind of thing with another function, or in another monad, using <tt>liftM2</tt> makes it immediately clear what is meant (see [[Code reuse]]).
| |
| | |
| Mathematically, the liftM2 operator is defined by:
| |
| | |
| :<math>\text{liftM2} \colon \forall M \colon \text{monad}, \; (A_1 \to A_2 \to R) \to M \, A_1 \to M \, A_2 \to M \, R = </math><math> op \mapsto m_1 \mapsto m_2 \mapsto \text{bind} \; m_1 \; (a_1 \mapsto \text{bind} \; m_2 \; (a_2 \mapsto \text{return} \; (op \, a_1 \, a_2)))</math>
| |
| | |
| ==Other examples==
| |
| | |
| ===Identity monad===
| |
| The simplest monad is the identity monad, which attaches no information to values. | |
| <source lang="haskell">
| |
| Id t = t
| |
| return x = x
| |
| x >>= f = f x
| |
| </source>
| |
| | |
| A do-block in this monad performs [[Variable (programming)|variable]] substitution; <tt>do {x <- 2; return 3*x}</tt> results in 6.
| |
| | |
| From the category theory point of view, the identity monad is derived from the adjunction between [[identity functor]]s.
| |
| | |
| ===Collections===
| |
| Some familiar [[Collection (computing)|collection]] types, including [[Linked list|lists]], [[Set (computer science)|sets]], and [[multiset]]s, are monads. The definition for lists is given here.
| |
| | |
| <source lang="haskell">
| |
| -- "return" constructs a one-item list.
| |
| return x = [x]
| |
| -- "bind" concatenates the lists obtained by applying f to each item in list xs.
| |
| xs >>= f = concat (map f xs)
| |
| -- The zero object is an empty list.
| |
| mzero = []
| |
| </source>
| |
| | |
| [[List comprehension]]s are a special application of the list monad. For example, the list comprehension <tt>[ 2*x | x <- [1..n], isOkay x]</tt> corresponds to the computation in the list monad <tt>do {x <- [1..n]; if isOkay x then return (2*x) else mzero;}</tt>.
| |
| | |
| The notation of list comprehensions is similar to the [[set-builder notation]], but sets can't be made into a monad, since there's a restriction on the type of computation to be comparable for equality, whereas a monad does not put any constraints on the types of computations. Actually, the Set is a '''restricted monad'''.<ref>[http://www.randomhacks.net/articles/2007/03/15/data-set-monad-haskell-macros How to make Data.Set a monad] shows an implementation of the Set restricted monad in [[Haskell (programming language)|Haskell]]</ref>
| |
| The monads for collections naturally represent [[Nondeterministic algorithm|nondeterministic computation]]. The list (or other collection) represents all the possible results from different nondeterministic paths of computation at that given time. For example, when one executes <tt>x <- [1,2,3,4,5]</tt>, one is saying that the variable <tt>x</tt> can non-deterministically take on any of the values of that list. If one were to return <tt>x</tt>, it would evaluate to a list of the results from each path of computation. Notice that the bind operator above follows this theme by performing <tt>f</tt> on each of the current possible results, and then it concatenates the result lists together.
| |
| | |
| Statements like <tt>if condition x y then return () else mzero</tt> are also often seen; if the condition is true, the non-deterministic choice is being performed from one dummy path of computation, which returns a value we are not assigning to anything; however, if the condition is false, then the <tt>mzero = []</tt> monad value non-deterministically chooses from 0 values, effectively terminating that path of computation. Other paths of computations might still succeed. This effectively serves as a "guard" to enforce that only paths of computation that satisfy certain conditions can continue. So collection monads are very useful for solving logic puzzles, Sudoku, and similar problems.
| |
| | |
| In a language with [[lazy evaluation]], like [[Haskell (programming language)|Haskell]], a list is evaluated only to the degree that its elements are requested: for example, if one asks for the first element of a list, only the first element will be computed. With respect to usage of the list monad for non-deterministic computation that means that we can non-deterministically generate a lazy list of all results of the computation and ask for the first of them, and only as much work will be performed as is needed to get that first result. The process roughly corresponds to backtracking: a path of computation is chosen, and then if it fails at some point (if it evaluates <tt>mzero</tt>), then it [[Backtracking|backtracks]] to the last branching point, and follows the next path, and so on. If the second element is then requested, it again does just enough work to get the second solution, and so on. So the list monad is a simple way to implement a backtracking algorithm in a lazy language. | |
| | |
| From the category theory point of view, collection monads are derived from adjunctions between a [[free functor]] and an underlying functor between the [[category of sets]] and a [[category of monoids]]. Taking different types of monoids, we obtain different types of collections.
| |
| {| class="wikitable"
| |
| |-
| |
| ! 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===
| |
| A state monad allows a programmer to attach state information of any type to a calculation. Given any value type, the corresponding type in the state monad is a function which accepts a state, then outputs a new state (of type <tt>s</tt>) along with a return value (of type <tt>t</tt>).
| |
| | |
| <source lang="haskell">
| |
| type State s t = s -> (t, s)
| |
| </source>
| |
| | |
| Note that this monad, unlike those already seen, takes a type parameter, the type of the state information. The monad operations are defined as follows:
| |
| | |
| <source lang="haskell">
| |
| -- "return" produces the given value without changing the state.
| |
| return x = \s -> (x, s)
| |
| -- "bind" modifies m so that it applies f to its result.
| |
| m >>= f = \r -> let (x, s) = m r in (f x) s
| |
| </source>
| |
| | |
| Useful state operations include:
| |
| <source lang="haskell">
| |
| get = \s -> (s, s) -- Examine the state at this point in the computation.
| |
| put s = \_ -> ((), s) -- Replace the state.
| |
| modify f = \s -> ((), f s) -- Update the state
| |
| </source>
| |
| | |
| Another operation applies a state monad to a given initial state:
| |
| <source lang="haskell">
| |
| runState :: State s a -> s -> (a, s)
| |
| runState t s = t s
| |
| </source>
| |
| | |
| do-blocks in a state monad are sequences of operations that can examine and update the state data.
| |
| | |
| Informally, a state monad of state type ''S'' maps the type of return values ''T'' into functions of type <math>S \rarr T \times S</math>, where ''S'' is the underlying state. The ''return'' function is simply:
| |
| :<math>\text{return} \colon T \rarr S \rarr T \times S = t \mapsto s \mapsto (t, s)</math>
| |
| The ''bind'' function is: | |
| :<math>\text{bind} \colon (S \rarr T \times S) \rarr (T \rarr S \rarr T' \times S) \rarr S \rarr T' \times S</math><math> \ = m \mapsto k \mapsto s \mapsto (k \ t \ s') \quad \text{where} \; (t, s') = m \, s</math>.
| |
| | |
| From the category theory point of view, a state monad is derived from the adjunction between the product functor and the exponential functor, which exists in any [[cartesian closed category]] by definition.
| |
| | |
| ===Environment monad===
| |
| The environment monad (also called the ''reader monad'' and the ''function monad'') allows a computation to depend on values from a shared environment. The monad type constructor maps a type ''T'' to functions of type ''E'' → ''T'', where E is the type of the shared environment. The monad functions are:
| |
| :<math>\text{return} \colon T \rarr E \rarr T = t \mapsto e \mapsto t</math>
| |
| :<math>\text{bind} \colon (E \rarr T) \rarr (T \rarr E \rarr T') \rarr E \rarr T' = r \mapsto f \mapsto e \mapsto f \, (r \, e) \, e</math>
| |
| | |
| The following monadic operations are useful:
| |
| | |
| :<math>\text{ask} \colon E \rarr E = \text{id}_E</math>
| |
| :<math>\text{local} \colon (E \rarr E) \rarr (E \rarr T) \rarr E \rarr T = f \mapsto c \mapsto e \mapsto c \, (f \, e)</math>
| |
| | |
| The ''ask'' operation is used to retrieve the current context, while ''local'' executes a computation in a modified subcontext. As in the state monad, computations in the environment monad may be invoked by simply providing an environment value and applying it to an instance of the monad.
| |
| | |
| ===Writer monad===
| |
| The writer monad allows a program to compute various kinds of auxiliary output which can be "composed" or "accumulated" step-by-step, in addition to the main result of a computation. It is often used for logging or profiling. Given the underlying type ''T'', a value in the writer monad has type ''W'' × ''T'', where ''W'' is a type endowed with an operation satisfying the [[monoid]] laws. The monad functions are simply:
| |
| :<math>\text{return} \colon T \rarr W \times T = t \mapsto (\epsilon, t)</math>
| |
| :<math>\text{bind} \colon (W \times T) \rarr (T \rarr W \times T') \rarr W \times T' = (w, t) \mapsto f \mapsto (w * w',\, t') \quad \text{where} \; (w', t') = f \, t</math>
| |
| where ε and * are the identity element of the monoid W and its associative operation, respectively.
| |
| | |
| The ''tell'' monadic operation is defined by:
| |
| :<math>\text{tell} \colon W \rarr (W \times 1) = w \mapsto (w, ())</math>
| |
| 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===
| |
| A [[continuation]] monad with return type <math>R</math> maps type <math>T</math> into functions of type <math>\left( T \rarr R \right) \rarr R</math>. It is used to model [[continuation-passing style]]. The return and bind functions are as follows:
| |
| | |
| :<math>\text{return} \colon T \rarr \left( T \rarr R \right) \rarr R = t \mapsto f \mapsto f \, t</math>
| |
| :<math>\text{bind} \colon \left( \left( T \rarr R \right) \rarr R \right) \rarr \left( T \rarr \left( T' \rarr R \right) \rarr R \right) \rarr \left( T' \rarr R \right) \rarr R</math><math>= c \mapsto f \mapsto k \mapsto c \, \left( t \mapsto f \, t \, k \right)</math>
| |
| | |
| The [[call-with-current-continuation]] function is defined as follows:
| |
| | |
| :<math>\text{call/cc} \colon \left( \left( T \rarr \left( T' \rarr R \right) \rarr R \right) \rarr \left( T \rarr R \right) \rarr R \right) \rarr \left( T \rarr R \right) \rarr R</math><math> = f \mapsto k \mapsto \left( f \left( t \mapsto x \mapsto k \, t \right) \, k \right)</math>
| |
| | |
| ===Others===
| |
| Other concepts that researchers have expressed as monads include:
| |
| | |
| *[[Iteratee]]
| |
| *[[Exception handling]]
| |
| *[[Graphical user interface]]s
| |
| *[[Interprocess communication]]
| |
| *[[Parser]]s
| |
| *[[Interpreter (computing)|Interpreter]]s
| |
| *[[Strict evaluation]]
| |
| *Interfaces to code written in other languages
| |
| | |
| == Free monads ==
| |
| {{expand section|date=June 2013}}
| |
| | |
| == Comonads ==
| |
| Comonads are the categorical dual of monads. They are defined by a type constructor W ''T'' and two operations: ''extract'' with type W ''T'' → ''T'' 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:
| |
| :<math>\text{extend} \,\, \text{extract} = \text{id}</math>
| |
| :<math>\text{extract} \circ (\text{extend} \, f) = f</math>
| |
| :<math>(\text{extend} \, f) \circ (\text{extend} \, g) = \text{extend} \, (f \circ (\text{extend} \, g))</math>
| |
| | |
| Alternatively, comonads may be defined in terms of operations ''fmap'', ''extract'' and ''duplicate''. The ''fmap'' and ''extract'' operations define W as a copointed functor. The ''duplicate'' operation characterizes comonads: it has type W ''T'' → W (W ''T'') and satisfies the following laws:
| |
| :<math>\text{extract} \circ \text{duplicate} = \text{id}</math>
| |
| :<math>\text{fmap} \, \text{extract} \circ \text{duplicate} = \text{id}</math>
| |
| :<math>\text{duplicate} \circ \text{duplicate} = \text{fmap} \, \text{duplicate} \circ \text{duplicate}</math>
| |
| | |
| The two formulations are related as follows:
| |
| :<math>\text{fmap}: (A \rarr B) \rarr \mathrm{W} \, A \rarr \mathrm{W} \, B = f \mapsto \text{extend} \, (f \circ \text{extract})</math>
| |
| :<math>\text{duplicate}: \mathrm{W} \, A \rarr \mathrm{W} \, \mathrm{W} \, A = \text{extend} \, \text{id}</math>
| |
| | |
| :<math>\text{extend}: (\mathrm{W} \, A \rarr B) \rarr \mathrm{W} \, A \rarr \mathrm{W} \, B = f \mapsto (\text{fmap} \, f) \circ \text{duplicate}</math>
| |
| | |
| 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 ''A'' → ''B''.
| |
| | |
| ===Identity comonad===
| |
| The identity comonad is the simplest comonad: it maps type ''T'' to itself. The ''extract'' operator is the identity and the ''extend'' operator is function application.
| |
| | |
| ===Product comonad===
| |
| The product comonad maps type <math>T</math> into tuples of type <math>C \times T</math>, where <math>C</math> is the context type of the comonad. The comonad operations are:
| |
| :<math>\text{extract}: (C \times T) \rarr T = (c, t) \mapsto t</math>
| |
| :<math>\text{extend}: ((C \times A) \rarr B) \rarr C \times A \rarr C \times B = f \mapsto (c, a) \mapsto (c, f \, (c, a))</math>
| |
| :<math>\text{fmap}: (A \rarr B) \rarr (C \times A) \rarr (C \times B) = (c, a) \mapsto (c, f \, a)</math>
| |
| :<math>\text{duplicate}: (C \times A) \rarr (C \times (C \times A)) = (c, a) \mapsto (c, (c, a))</math>
| |
| | |
| ===Function comonad===
| |
| The function comonad maps type <math>T</math> into functions of type <math>M \rarr T</math>, where <math>M</math> is a type endowed with a [[monoid]] structure. The comonad operations are:
| |
| :<math>\text{extract}: (M \rarr T) \rarr T = f \mapsto f \, \varepsilon</math>
| |
| :<math>\text{extend}: ((M \rarr A) \rarr B) \rarr (M \rarr A) \rarr M \rarr B = f \mapsto g \mapsto m \mapsto f \, (m' \mapsto g \, (m * m'))</math>
| |
| :<math>\text{fmap}: (A \rarr B) \rarr (M \rarr A) \rarr M \rarr B = f \mapsto g \mapsto (f \circ g)</math>
| |
| :<math>\text{duplicate}: (M \rarr A) \rarr M \rarr (M \rarr A) = f \mapsto m \mapsto m' \mapsto f \, (m * m')</math>
| |
| where ε is the identity element of <math>M</math> and * is its associative operation.
| |
| | |
| ===Costate comonad===
| |
| The costate comonad maps a type <math>T</math> into type <math>(S \rarr T) \times S</math>, where S is the base type of the store. The comonad operations are:
| |
| :<math>\text{extract}: ((S \rarr T) \times S) \rarr T = (f, s) \mapsto f \, s</math>
| |
| :<math>\text{extend}: (((S \rarr A) \times S) \rarr B) \rarr ((S \rarr A) \times S) \rarr (S \rarr B) \times S \,</math><math>= f \mapsto (g, s) \mapsto ((s' \mapsto f \, (g, s')), s)</math>
| |
| :<math>\text{fmap}: (A \rarr B) \rarr ((S \rarr A) \times S) \rarr (S \rarr B) \times S = f \mapsto (f', s) \mapsto (f \circ f', s)</math>
| |
| :<math>\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)</math>
| |
| | |
| == See also ==
| |
| * [[Arrows in functional programming]] — whereas monads generalize the results of a computation to effects, arrows further generalize the inputs similarly.
| |
| * [[Aspect-oriented programming]], a paradigm to increase modularity by isolating secondary or supporting functionality.
| |
| * [[Effect system]], an alternative way of describing side effects as types.
| |
| * [[Inversion of control]] — the abstract principle of calling specific functions from a reusable software entity.
| |
| * [[Monad transformer]]s — which allow monads to be composed in a modular and convenient way.
| |
| * [[Uniqueness type]]s - an alternative way of dealing with side-effects in functional languages
| |
| | |
| ==Notes==
| |
| {{Reflist|group=note}}
| |
| | |
| ==References==
| |
| <references />
| |
| | |
| == External links ==
| |
| {{Wikibooks|Haskell|Understanding monads}}
| |
| | |
| ===Haskell monad tutorials ===
| |
| * [http://haskell.org/haskellwiki/Monad_tutorials_timeline Monad Tutorials Timeline] Probably the most comprehensive collection of links to monad tutorials, ordered by date.
| |
| *{{cite web|url=http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html|title=You Could Have Invented Monads! (And Maybe You Already Have.)|last=Piponi|first=Dan|date=August 7, 2006|work=A Neighborhood of Infinity}} — The most famous "blog post" tutorial.
| |
| *{{cite journal|last=Yorgey|first=Brent|date=12 March 2009|title=The Typeclassopedia|journal=The Monad.Reader|issue=13|pages=17–68|url=http://www.haskell.org/wikiupload/8/85/TMR-Issue13.pdf}} — An attempt to explain all of the leading typeclasses in Haskell in an elementary way, with monadic functors considered as only one form, best understood by comparison with others: e.g., the more general idea of a "Functor" as something you can map over; "Applicative" functors, and so forth; contains an extensive bibliography.
| |
| *{{cite web|url=http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/|title=Abstraction, intuition, and the "monad tutorial fallacy"|last=Yorgey|first=Brent|date=January 12, 2009|work=blog :: Brent -> [String]|publisher=[[WordPress.com]]}} — Opposes the idea of making a tutorial about monads in particular.
| |
| * [http://haskell.org/haskellwiki/What_a_Monad_is_not What a Monad is not] deals with common misconceptions and oversimplifications in a humorous way.
| |
| *{{cite web|url=http://noordering.wordpress.com/2009/03/31/how-you-shouldnt-use-monad/|title=How you should(n’t) use Monad|date=March 31, 2009|work=No Ordering|author= beelsebob |publisher=[[WordPress.com]]}} — Takes a similar point of view, locating monads in a much wider array of Haskell functor classes, of use only in special circumstances.
| |
| *{{cite web|url=http://mvanier.livejournal.com/3917.html|title=Yet Another Monad Tutorial (part 1: basics)|last=Vanier|first=Mike|date=July 25, 2010|work=Mike's World-O-Programming|publisher=[[LiveJournal]]}} — An extremely detailed set of tutorials, deriving monads from first principles.
| |
| *{{cite web|url=http://learnyouahaskell.com/a-fistful-of-monads|title=A Fistful of Monads}} An explanation of Monads, building on the concepts of Functors, Applicative Functors and Monoids discussed in the [http://learnyouahaskell.com/functors-applicative-functors-and-monoids previous chapter].
| |
| * [http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html Functors, Applicatives and Monads in Pictures]. A humorous beginner's guide to monads.
| |
| | |
| ==== Older tutorials ====
| |
| * [http://www.haskell.org/haskellwiki/All_About_Monads All About Monads]
| |
| * [http://haskell.org/haskellwiki/Monads_as_computation Haskell Wiki: Monads as Computation]
| |
| * [http://haskell.org/haskellwiki/Monads_as_containers Haskell Wiki: Monads as Containers]
| |
| *{{cite web|url=http://www.engr.mun.ca/~theo/Misc/haskell_and_monads.htm|title=Monads for the Working Haskell Programmer|last=Norvell|first=Theodore|publisher=Memorial University of Newfoundland}}
| |
| *{{cite journal|last=Klinger|first=Stefan|date=15 December 2005|title=The Haskell Programmer’s Guide to the IO Monad — Don’t Panic|publisher=Centre for Telematics and Information Technology, University of Twente|issue=5–54|issn=1381-3625|url=http://stefan-klinger.de/files/monadGuide.pdf}}
| |
| *{{cite web|url=http://onlamp.com/pub/a/onlamp/2007/08/02/introduction-to-haskell-pure-functions.html|title=Introduction to Haskell, Part 3: Monads|last=Turoff|first=Adam|date=August 2, 2007|work=ONLamp|publisher=O'Reilly Media}}
| |
| * [http://spbhug.folding-maps.org/wiki/MonadsEn Monads] A monad tutorial providing examples of non-trivial monads apart from the conventional IO/Maybe/List/State monads.
| |
| *{{cite web|url=http://ertes.de/articles/monads.html|title=Understanding Haskell Monads|last=Söylemez|first=Ertugrul|date=2010-07-11}}
| |
| | |
| ==== Other documentation ====
| |
| *{{cite web|url=http://members.chello.nl/hjgtuyl/tourdemonad.html|title=A tour of the Haskell monad functions|last=van Tuyl|first=Henk-Jan|date=2010-02-27}}
| |
| *{{cite journal|last=Moggi|first=Eugenio|title=Notions of computation and monads|url=http://www.disi.unige.it/person/MoggiE/ftp/ic91.pdf}} — The original paper suggesting use of monads for programming
| |
| *{{cite journal|last=Wadler|first=Philip|authorlink=Philip Wadler|date=August 2001|title=Monads for functional programming|publisher=University of Glasgow|url=http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf}} — Describes monads in Haskell (before they were implemented)
| |
| | |
| ===Scala monad tutorials ===
| |
| *{{cite video |people=League, Chris |date=July 12, 2010 |title=Monadologie: Professional Help for Type Anxiety |url=http://vimeo.com/13304075 |format=flv |medium=Tech talk |publisher=New York Scala Enthusiasts |location=[[New York City]]}}
| |
| *{{cite web|url=http://blog.tmorris.net/posts/understanding-monads-using-scala-part-1/index.html|title=Understanding Monads using Scala (Part 1)|last=Morris|first=Tony|date=June 22, 2010|work=λ Tony’s blog λ}}
| |
| * {{Cite web
| |
| | first1 = James
| |
| | last1 = Iry
| |
| | date = September 18, 2007
| |
| | title = Monads are Elephants
| |
| | url = http://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html
| |
| }}
| |
| * {{Cite web
| |
| | first1 = Gregory
| |
| | last1 = Meredith
| |
| | date = April 25, 2010
| |
| | title = Pro Scala: Monadic Design Patterns for the Web
| |
| | publisher =
| |
| | edition = 1st
| |
| | pages = 300
| |
| | isbn =
| |
| | url = http://github.com/leithaus/XTrace/blob/monadic/src/main/book/content/monadic.pdf
| |
| | postscript = <!--none-->
| |
| }}
| |
| | |
| === Monads in other languages ===
| |
| * [http://web.archive.org/web/20080515195640/http://sleepingsquirrel.org/monads/monads.html Monads in Perl]
| |
| * [http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html Monads in Ruby]
| |
| * [http://www.valuedlessons.com/2008/01/monads-in-python-with-nice-syntax.html Monads in Python]
| |
| * [http://lamp.epfl.ch/~emir/bqbase/2005/01/20/monad.html Monads in Scala]
| |
| * [http://onclojure.com/2009/03/05/a-monad-tutorial-for-clojure-programmers-part-1/ Monads in Clojure]
| |
| * [http://labs.mudynamics.com/2009/05/13/monadic-parser-in-javascript/ Monads in JavaScript]
| |
| * [http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx Monads in C# and LINQ]
| |
| * [http://enfranchisedmind.com/blog/posts/a-monad-tutorial-for-ocaml/ Monads in Ocaml]
| |
| * [http://blog.ircmaxell.com/2013/07/taking-monads-to-oop-php.html Monads in PHP]
| |
| | |
| {{DEFAULTSORT:Monad (Functional Programming)}}
| |
| [[Category:1991 in computer science]]
| |
| [[Category:Functional programming]]
| |
| [[Category:Adjoint functors]]
| |
| [[Category:Articles with example Haskell code]]
| |
| [[Category:Software design patterns]]
| |