All About Monads
From HaskellWiki
(Difference between revisions)
(It has begun.) 
m (Typo) 

(13 intermediate revisions by 6 users not shown)  
Line 1:  Line 1:  
−  ''All About Monads'' is a tutorial on monads and monad transformers and a walkthrough of common monad instances. You can download a PDF version [http://mauke.dyndns.org/stuff/haskell/All_About_Monads.pdf here]. 
+  ''All About Monads'' is a tutorial on monads and monad transformers and a walkthrough of common monad instances. You can download a PDF version [http://ompldr.org/vY29zdw/All_About_Monads.pdf here] or [http://www.mediafire.com/?no3dq024hgacye4 here]. And [http://web.archive.org/web/20061211101052/http://www.nomaware.com/monads/html/index.html here] is a version of the article which includes [http://web.archive.org/web/20061210172052/http://www.nomaware.com/monads/html/examples.html source code]. 
Attempts are being made at porting the tutorial to this wiki; what you're seeing below is a preview of the result of that effort. If you wish to help out you should fork [https://github.com/dag/allaboutmonads this GitHub repo] rather than edit this page, for now. 
Attempts are being made at porting the tutorial to this wiki; what you're seeing below is a preview of the result of that effort. If you wish to help out you should fork [https://github.com/dag/allaboutmonads this GitHub repo] rather than edit this page, for now. 

−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[index.htmlTable of Contents]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[meet.htmlMeet the Monads]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Introduction = 
= Introduction = 

−  
−  * [[#whatWhat is a monad?]] 

−  * [[#whyWhy should I make the effort to understand monads?]] 

−  
−  
−   

== What is a monad? == 
== What is a monad? == 

Line 27:  Line 9:  
A monad is a way to structure computations in terms of values and sequences of computations using those values. Monads allow the programmer to build up computations using sequential building blocks, which can themselves be sequences of computations. The monad determines how combined computations form a new computation and frees the programmer from having to code the combination manually each time it is required. 
A monad is a way to structure computations in terms of values and sequences of computations using those values. Monads allow the programmer to build up computations using sequential building blocks, which can themselves be sequences of computations. The monad determines how combined computations form a new computation and frees the programmer from having to code the combination manually each time it is required. 

−  ''It is useful to think of a monad as a strategy for combining computations into more complex computations.'' For example, you should be familiar with the <tt>Maybe</tt> type in Haskell: 
+  ''It is useful to think of a monad as a strategy for combining computations into more complex computations.'' For example, you should be familiar with the <code>Maybe</code> type in Haskell: 
−  <pre>data Maybe a = Nothing  Just a</pre> 
+  <haskell> 
−  which represents the type of computations which may fail to return a result. The <tt>Maybe</tt> type suggests a strategy for combining computations which return <tt>Maybe</tt> values: if a combined computation consists of one computation <tt>B</tt> that depends on the result of another computation <tt>A</tt>, then the combined computation should yield <tt>Nothing</tt> whenever either <tt>A</tt> or <tt>B</tt> yield <tt>Nothing</tt> and the combined computation should yield the result of <tt>B</tt> applied to the result of <tt>A</tt> when both computations succeed. 
+  data Maybe a = Nothing  Just a 
+  </haskell> 

+  which represents the type of computations which may fail to return a result. The <code>Maybe</code> type suggests a strategy for combining computations which return <code>Maybe</code> values: if a combined computation consists of one computation <code>B</code> that depends on the result of another computation <code>A</code>, then the combined computation should yield <code>Nothing</code> whenever either <code>A</code> or <code>B</code> yield <code>Nothing</code> and the combined computation should yield the result of <code>B</code> applied to the result of <code>A</code> when both computations succeed. 

Other monads exist for building computations that perform I/O, have state, may return multiple results, etc. There are as many different type of monads as there are strategies for combining computations, but there are certain monads that are especially useful and are common enough that they are part of the standard [http://www.haskell.org/onlinelibrary/ Haskell 98 libraries]. These monads are each described in [[introII.htmlPart II]]. 
Other monads exist for building computations that perform I/O, have state, may return multiple results, etc. There are as many different type of monads as there are strategies for combining computations, but there are certain monads that are especially useful and are common enough that they are part of the standard [http://www.haskell.org/onlinelibrary/ Haskell 98 libraries]. These monads are each described in [[introII.htmlPart II]]. 

Line 47:  Line 29:  
Each of these features will be revisited later in the tutorial in the context of specific monads. 
Each of these features will be revisited later in the tutorial in the context of specific monads. 

−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[index.htmlTable of Contents]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[meet.htmlMeet the Monads]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Meet the Monads 
Meet the Monads 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[introduction.htmlIntroduction]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[class.htmlDoing it with class]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Meet the Monads = 
= Meet the Monads = 

−  * [[#typeconstructorsType constructors]] 
+  We will use the <code>Maybe</code> type constructor throughout this chapter, so you should familiarize yourself with the definition and usage of [http://www.haskell.org/onlinelibrary/maybe.html <code>Maybe</code>] before continuing. 
−  * [[#maybeMaybe a monad]] 

−  * [[#listA list is also a monad]] 

−  * [[#example1An example]] 

−  * [[#summarySummary]] 

−  
−  
−   

−  
−  We will use the <tt>Maybe</tt> type constructor throughout this chapter, so you should familiarize yourself with the definition and usage of [http://www.haskell.org/onlinelibrary/maybe.html <tt>Maybe</tt>] before continuing. 

== Type constructors == 
== Type constructors == 

−  To understand monads in Haskell, you need to be comfortable dealing with type constructors. A ''type constructor'' is a parameterized type definition used with polymorphic types. By supplying a type constructor with one or more concrete types, you can construct a new concrete type in Haskell. In the definition of <tt>Maybe</tt>: 
+  To understand monads in Haskell, you need to be comfortable dealing with type constructors. A ''type constructor'' is a parameterized type definition used with polymorphic types. By supplying a type constructor with one or more concrete types, you can construct a new concrete type in Haskell. In the definition of <code>Maybe</code>: 
−  <pre> data Maybe a = Nothing  Just a</pre> 
+  <haskell> 
−  <tt>Maybe</tt> is a type constructor and <tt>Nothing</tt> and <tt>Just</tt> are data constructors. You can construct a data value by applying the <tt>Just</tt> data constructor to a value: 
+  data Maybe a = Nothing  Just a 
+  </haskell> 

+  <code>Maybe</code> is a type constructor and <code>Nothing</code> and <code>Just</code> are data constructors. You can construct a data value by applying the <code>Just</code> data constructor to a value: 

−  <pre> country = Just "China"</pre> 
+  <haskell> 
−  In the same way, you can construct a type by applying the <tt>Maybe</tt> type constructor to a type: 
+  country = Just "China" 
+  </haskell> 

+  In the same way, you can construct a type by applying the <code>Maybe</code> type constructor to a type: 

−  <pre> lookupAge :: DB > String > Maybe Int</pre> 
+  <haskell> 
−  Polymorphic types are like containers that are capable of holding values of many different types. So <tt>Maybe Int</tt> can be thought of as a <tt>Maybe</tt> container holding an <tt>Int</tt> value (or <tt>Nothing</tt>) and <tt>Maybe String</tt> would be a <tt>Maybe</tt> container holding a <tt>String</tt> value (or <tt>Nothing</tt>). In Haskell, we can also make the type of the container polymorphic, so we could write "<tt>m a</tt>" to represent a container of some type holding a value of some type! 
+  lookupAge :: DB > String > Maybe Int 
+  </haskell> 

+  Polymorphic types are like containers that are capable of holding values of many different types. So <code>Maybe Int</code> can be thought of as a <code>Maybe</code> container holding an <code>Int</code> value (or <code>Nothing</code>) and <code>Maybe String</code> would be a <code>Maybe</code> container holding a <code>String</code> value (or <code>Nothing</code>). In Haskell, we can also make the type of the container polymorphic, so we could write "<code>m a</code>" to represent a container of some type holding a value of some type! 

−  We often use type variables with type constructors to describe abstract features of a computation. For example, the polymorphic type <tt>Maybe a</tt> is the type of all computations that may return a value or <tt>Nothing</tt>. In this way, we can talk about the properties of the container apart from any details of what the container might hold. 
+  We often use type variables with type constructors to describe abstract features of a computation. For example, the polymorphic type <code>Maybe a</code> is the type of all computations that may return a value or <code>Nothing</code>. In this way, we can talk about the properties of the container apart from any details of what the container might hold. 
[[Image:info.png]] If you get messages about "kind errors" from the compiler when working with monads, it means that you are not using the type constructors correctly. <br /> 
[[Image:info.png]] If you get messages about "kind errors" from the compiler when working with monads, it means that you are not using the type constructors correctly. <br /> 

Line 97:  Line 56:  
== Maybe a monad == 
== Maybe a monad == 

−  In Haskell a monad is represented as a type constructor (call it <tt>m</tt>), a function that builds values of that type (<tt>a > m a</tt>), and a function that combines values of that type with computations that produce values of that type to produce a new computation for values of that type (<tt>m a > (a > m b) > m b</tt>). Note that the container is the same, but the type of the contents of the container can change. It is customary to call the monad type constructor "<tt>m</tt>" when discussing monads in general. The function that builds values of that type is traditionally called "<tt>return</tt>" and the third function is known as "bind" but is written "<tt>>>=</tt>". The signatures of the functions are: 
+  In Haskell a monad is represented as a type constructor (call it <code>m</code>), a function that builds values of that type (<code>a > m a</code>), and a function that combines values of that type with computations that produce values of that type to produce a new computation for values of that type (<code>m a > (a > m b) > m b</code>). Note that the container is the same, but the type of the contents of the container can change. It is customary to call the monad type constructor "<code>m</code>" when discussing monads in general. The function that builds values of that type is traditionally called "<code>return</code>" and the third function is known as "bind" but is written "<code>>>=</code>". The signatures of the functions are: 
−  <pre> the type of monad m 
+  <haskell> 
+   the type of monad m 

data m a = ... 
data m a = ... 

 return is a type constructor that creates monad instances 
 return is a type constructor that creates monad instances 

−  return :: a > m a 
+  return :: a > m a 
 bind is a function that combines a monad instance m a with a computation 
 bind is a function that combines a monad instance m a with a computation 

 that produces another monad instance m b from a's to produce a new 
 that produces another monad instance m b from a's to produce a new 

 monad instance m b 
 monad instance m b 

−  (>>=) :: m a > (a > m b) > m b</pre> 
+  (>>=) :: m a > (a > m b) > m b 
−  Roughly speaking, the monad type constructor defines a type of computation, the <tt>return</tt> function creates primitive values of that computation type and <tt>>>=</tt> combines computations of that type together to make more complex computations of that type. Using the container analogy, the type constructor <tt>m</tt> is a container that can hold different values. <tt>m a</tt> is a container holding a value of type <tt>a</tt>. The <tt>return</tt> function puts a value into a monad container. The <tt>>>=</tt> function takes the value from a monad container and passes it to a function to produce a monad container containing a new value, possibly of a different type. The <tt>>>=</tt> function is known as "bind" because it binds the value in a monad container to the first argument of a function. By adding logic to the binding function, a monad can implement a specific strategy for combining computations in the monad. 
+  </haskell> 
+  Roughly speaking, the monad type constructor defines a type of computation, the <code>return</code> function creates primitive values of that computation type and <code>>>=</code> combines computations of that type together to make more complex computations of that type. Using the container analogy, the type constructor <code>m</code> is a container that can hold different values. <code>m a</code> is a container holding a value of type <code>a</code>. The <code>return</code> function puts a value into a monad container. The <code>>>=</code> function takes the value from a monad container and passes it to a function to produce a monad container containing a new value, possibly of a different type. The <code>>>=</code> function is known as "bind" because it binds the value in a monad container to the first argument of a function. By adding logic to the binding function, a monad can implement a specific strategy for combining computations in the monad. 

This will all become clearer after the example below, but if you feel particularly confused at this point you might try looking at this [[analogy.htmlphysical analogy of a monad]] before continuing. 
This will all become clearer after the example below, but if you feel particularly confused at this point you might try looking at this [[analogy.htmlphysical analogy of a monad]] before continuing. 

Line 115:  Line 74:  
== An example == 
== An example == 

−  Suppose that we are writing a program to keep track of sheep cloning experiments. We would certainly want to know the genetic history of all of our sheep, so we would need <tt>mother</tt> and <tt>father</tt> functions. But since these are cloned sheep, they may not always have both a mother and a father! 
+  Suppose that we are writing a program to keep track of sheep cloning experiments. We would certainly want to know the genetic history of all of our sheep, so we would need <code>mother</code> and <code>father</code> functions. But since these are cloned sheep, they may not always have both a mother and a father! 
−  We would represent the possibility of not having a mother or father using the <tt>Maybe</tt> type constructor in our Haskell code: 
+  We would represent the possibility of not having a mother or father using the <code>Maybe</code> type constructor in our Haskell code: 
−  <pre>type Sheep = ... 
+  <haskell> 
+  type Sheep = ... 

−  father :: Sheep > Maybe Sheep 
+  father :: Sheep > Maybe Sheep 
father = ... 
father = ... 

−  mother :: Sheep > Maybe Sheep 
+  mother :: Sheep > Maybe Sheep 
−  mother = ...</pre> 
+  mother = ... 
+  </haskell> 

Then, defining functions to find grandparents is a little more complicated, because we have to handle the possibility of not having a parent: 
Then, defining functions to find grandparents is a little more complicated, because we have to handle the possibility of not having a parent: 

−  <pre>maternalGrandfather :: Sheep > Maybe Sheep 
+  <haskell> 
+  maternalGrandfather :: Sheep > Maybe Sheep 

maternalGrandfather s = case (mother s) of 
maternalGrandfather s = case (mother s) of 

−  Nothing > Nothing 
+  Nothing > Nothing 
−  Just m > father m</pre> 
+  Just m > father m 
+  </haskell> 

and so on for the other grandparent combinations. 
and so on for the other grandparent combinations. 

It gets even worse if we want to find great grandparents: 
It gets even worse if we want to find great grandparents: 

−  <pre>mothersPaternalGrandfather :: Sheep > Maybe Sheep 
+  <haskell> 
+  mothersPaternalGrandfather :: Sheep > Maybe Sheep 

mothersPaternalGrandfather s = case (mother s) of 
mothersPaternalGrandfather s = case (mother s) of 

−  Nothing > Nothing 
+  Nothing > Nothing 
−  Just m > case (father m) of 
+  Just m > case (father m) of 
−  Nothing > Nothing 
+  Nothing > Nothing 
−  Just gf > father gf</pre> 
+  Just gf > father gf 
−  Aside from being ugly, unclear, and difficult to maintain, this is just too much work. It is clear that a <tt>Nothing</tt> value at any point in the computation will cause <tt>Nothing</tt> to be the final result, and it would be much nicer to implement this notion once in a single place and remove all of the explicit <tt>case</tt> testing scattered all over the code. This will make the code easier to write, easier to read and easier to change. So good programming style would have us create a combinator that captures the behavior we want: 
+  </haskell> 
+  Aside from being ugly, unclear, and difficult to maintain, this is just too much work. It is clear that a <code>Nothing</code> value at any point in the computation will cause <code>Nothing</code> to be the final result, and it would be much nicer to implement this notion once in a single place and remove all of the explicit <code>case</code> testing scattered all over the code. This will make the code easier to write, easier to read and easier to change. So good programming style would have us create a combinator that captures the behavior we want: 

Code available in [[../examples/example1.hsexample1.hs]] 
Code available in [[../examples/example1.hsexample1.hs]] 

−  <pre> comb is a combinator for sequencing operations that return Maybe 
+  <haskell> 
−  comb :: Maybe a > (a > Maybe b) > Maybe b 
+   comb is a combinator for sequencing operations that return Maybe 
+  comb :: Maybe a > (a > Maybe b) > Maybe b 

comb Nothing _ = Nothing 
comb Nothing _ = Nothing 

comb (Just x) f = f x 
comb (Just x) f = f x 

 now we can use `comb` to build complicated sequences 
 now we can use `comb` to build complicated sequences 

−  mothersPaternalGrandfather :: Sheep > Maybe Sheep 
+  mothersPaternalGrandfather :: Sheep > Maybe Sheep 
−  mothersPaternalGrandfather s = (Just s) `comb` mother `comb` father `comb` father </pre> 
+  mothersPaternalGrandfather s = (Just s) `comb` mother `comb` father `comb` father 
−  The combinator is a huge success! The code is much cleaner and easier to write, understand and modify. Notice also that the <tt>comb</tt> function is entirely polymorphic — it is not specialized for <tt>Sheep</tt> in any way. In fact, ''the combinator captures a general strategy for combining computations that may fail to return a value.'' Thus, we can apply the same combinator to other computations that may fail to return a value, such as database queries or dictionary lookups. 
+  </haskell> 
+  The combinator is a huge success! The code is much cleaner and easier to write, understand and modify. Notice also that the <code>comb</code> function is entirely polymorphic — it is not specialized for <code>Sheep</code> in any way. In fact, ''the combinator captures a general strategy for combining computations that may fail to return a value.'' Thus, we can apply the same combinator to other computations that may fail to return a value, such as database queries or dictionary lookups. 

−  The happy outcome is that common sense programming practice has led us to create a monad without even realizing it. The <tt>Maybe</tt> type constructor along with the <tt>Just</tt> function (acts like <tt>return</tt>) and our combinator (acts like <tt>>>=</tt>) together form a simple monad for building computations which may not return a value. All that remains to make this monad truly useful is to make it conform to the monad framework built into the Haskell language. That is the subject of the next chapter. 
+  The happy outcome is that common sense programming practice has led us to create a monad without even realizing it. The <code>Maybe</code> type constructor along with the <code>Just</code> function (acts like <code>return</code>) and our combinator (acts like <code>>>=</code>) together form a simple monad for building computations which may not return a value. All that remains to make this monad truly useful is to make it conform to the monad framework built into the Haskell language. That is the subject of the next chapter. 
== A list is also a monad == 
== A list is also a monad == 

−  We have seen that the <tt>Maybe</tt> type constructor is a monad for building computations which may fail to return a value. You may be surprised to know that another common Haskell type constructor, <tt>[]</tt> (for building lists), is also a monad. The List monad allows us to build computations which can return 0, 1, or more values. 
+  We have seen that the <code>Maybe</code> type constructor is a monad for building computations which may fail to return a value. You may be surprised to know that another common Haskell type constructor, <code>[]</code> (for building lists), is also a monad. The List monad allows us to build computations which can return 0, 1, or more values. 
−  The <tt>return</tt> function for lists simply creates a singleton list (<tt>return x = [x]</tt>). The binding operation for lists creates a new list containing the results of applying the function to all of the values in the original list (<tt>l >>= f = concatMap f l</tt>). 
+  The <code>return</code> function for lists simply creates a singleton list (<code>return x = [x]</code>). The binding operation for lists creates a new list containing the results of applying the function to all of the values in the original list (<code>l >>= f = concatMap f l</code>). 
One use of functions which return lists is to represent ''ambiguous'' computations — that is computations which may have 0, 1, or more allowed outcomes. In a computation composed from ambigous subcomputations, the ambiguity may compound, or it may eventually resolve into a single allowed outcome or no allowed outcome at all. During this process, the set of possible computational states is represented as a list. The List monad thus embodies a strategy for performing simultaneous computations along all allowed paths of an ambiguous computation. 
One use of functions which return lists is to represent ''ambiguous'' computations — that is computations which may have 0, 1, or more allowed outcomes. In a computation composed from ambigous subcomputations, the ambiguity may compound, or it may eventually resolve into a single allowed outcome or no allowed outcome at all. During this process, the set of possible computational states is represented as a list. The List monad thus embodies a strategy for performing simultaneous computations along all allowed paths of an ambiguous computation. 

Line 170:  Line 129:  
== Summary == 
== Summary == 

−  We have seen that a monad is a type constructor, a function called <tt>return</tt>, and a combinator function called <tt>bind</tt> or <tt>>>=</tt>. These three elements work together to encapsulate a strategy for combining computations to produce more complex computations. 
+  We have seen that a monad is a type constructor, a function called <code>return</code>, and a combinator function called <code>bind</code> or <code>>>=</code>. These three elements work together to encapsulate a strategy for combining computations to produce more complex computations. 
−  Using the <tt>Maybe</tt> type constructor, we saw how good programming practice led us to define a simple monad that could be used to build complex computations out of sequences of computations that could each fail to return a value. The resulting <tt>Maybe</tt> monad encapsulates a strategy for combining computations that may not return values. By codifying the strategy in a monad, we have achieved a degree of modularity and flexibility that is not present when the computations are combined in an ad hoc manner. 
+  Using the <code>Maybe</code> type constructor, we saw how good programming practice led us to define a simple monad that could be used to build complex computations out of sequences of computations that could each fail to return a value. The resulting <code>Maybe</code> monad encapsulates a strategy for combining computations that may not return values. By codifying the strategy in a monad, we have achieved a degree of modularity and flexibility that is not present when the computations are combined in an ad hoc manner. 
−  We have also seen that another common Haskell type constructor, <tt>[]</tt>, is a monad. The List monad encapsulates a strategy for combining computations that can return 0, 1, or multiple values. 
+  We have also seen that another common Haskell type constructor, <code>[]</code>, is a monad. The List monad encapsulates a strategy for combining computations that can return 0, 1, or multiple values. 
−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[introduction.htmlIntroduction]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[class.htmlDoing it with class]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Doing it with class 
Doing it with class 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[meet.htmlMeet the Monads]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[laws.htmlThe monad laws]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Doing it with class = 
= Doing it with class = 

−  
−  * [[#classesHaskell type classes]] 

−  * [[#monadThe Monad class]] 

−  * [[#example2Example continued]] 

−  * [[#donotationDo notation]] 

−  * [[#summarySummary]] 

−  
−  
−   

== Haskell type classes == 
== Haskell type classes == 

Line 205:  Line 145:  
== The Monad class == 
== The Monad class == 

−  In Haskell, there is a standard <tt>Monad</tt> class that defines the names and signatures of the two monad functions <tt>return</tt> and <tt>>>=</tt>. It is not strictly necessary to make your monads instances of the <tt>Monad</tt> class, but it is a good idea. Haskell has special support for <tt>Monad</tt> instances built into the language and making your monads instances of the <tt>Monad</tt> class will allow you to use these features to write cleaner and more elegant code. Also, making your monads instances of the <tt>Monad</tt> class communicates important information to others who read the code and failing to do so can cause you to use confusing and nonstandard function names. It's easy to do and it has many benefits, so just do it! 
+  In Haskell, there is a standard <code>Monad</code> class that defines the names and signatures of the two monad functions <code>return</code> and <code>>>=</code>. It is not strictly necessary to make your monads instances of the <code>Monad</code> class, but it is a good idea. Haskell has special support for <code>Monad</code> instances built into the language and making your monads instances of the <code>Monad</code> class will allow you to use these features to write cleaner and more elegant code. Also, making your monads instances of the <code>Monad</code> class communicates important information to others who read the code and failing to do so can cause you to use confusing and nonstandard function names. It's easy to do and it has many benefits, so just do it! 
−  The standard <tt>Monad</tt> class definition in Haskell looks something like this: 
+  The standard <code>Monad</code> class definition in Haskell looks something like this: 
−  <pre>class Monad m where 
+  <haskell> 
−  (>>=) :: m a > (a > m b) > m b 
+  class Monad m where 
−  return :: a > m a</pre> 
+  (>>=) :: m a > (a > m b) > m b 
+  return :: a > m a 

+  </haskell> 

== Example continued == 
== Example continued == 

−  Continuing the [[meet.html#example1previous example]], we will now see how the <tt>Maybe</tt> type constructor fits into the Haskell monad framework as an instance of the <tt>Monad</tt> class. 
+  Continuing the [[meet.html#example1previous example]], we will now see how the <code>Maybe</code> type constructor fits into the Haskell monad framework as an instance of the <code>Monad</code> class. 
−  Recall that our <tt>Maybe</tt> monad used the <tt>Just</tt> data constructor to fill the role of the monad <tt>return</tt> function and we built a simple combinator to fill the role of the monad <tt>>>=</tt> binding function. We can make its role as a monad explicit by declaring <tt>Maybe</tt> as an instance of the <tt>Monad</tt> class: 
+  Recall that our <code>Maybe</code> monad used the <code>Just</code> data constructor to fill the role of the monad <code>return</code> function and we built a simple combinator to fill the role of the monad <code>>>=</code> binding function. We can make its role as a monad explicit by declaring <code>Maybe</code> as an instance of the <code>Monad</code> class: 
−  <pre>instance Monad Maybe where 
+  <haskell> 
−  Nothing >>= f = Nothing 
+  instance Monad Maybe where 
−  (Just x) >>= f = f x 
+  Nothing >>= f = Nothing 
−  return = Just</pre> 
+  (Just x) >>= f = f x 
−  Once we have defined <tt>Maybe</tt> as an instance of the Monad class, we can use the standard monad operators to build the complex computations: 
+  return = Just 
+  </haskell> 

+  Once we have defined <code>Maybe</code> as an instance of the Monad class, we can use the standard monad operators to build the complex computations: 

−  <pre> we can use monadic operations to build complicated sequences 
+  <haskell> 
−  maternalGrandfather :: Sheep > Maybe Sheep 
+   we can use monadic operations to build complicated sequences 
−  maternalGrandfather s = (return s) >>= mother >>= father 
+  maternalGrandfather :: Sheep > Maybe Sheep 
+  maternalGrandfather s = (return s) >>= mother >>= father 

−  fathersMaternalGrandmother :: Sheep > Maybe Sheep 
+  fathersMaternalGrandmother :: Sheep > Maybe Sheep 
−  fathersMaternalGrandmother s = (return s) >>= father >>= mother >>= mother </pre> 
+  fathersMaternalGrandmother s = (return s) >>= father >>= mother >>= mother 
−  In Haskell, <tt>Maybe</tt> is defined as an instance of the <tt>Monad</tt> class in the standard prelude, so you don't need to do it yourself. The other monad we have seen so far, the list constructor, is also defined as an instance of the <tt>Monad</tt> class in the standard prelude. 
+  </haskell> 
+  In Haskell, <code>Maybe</code> is defined as an instance of the <code>Monad</code> class in the standard prelude, so you don't need to do it yourself. The other monad we have seen so far, the list constructor, is also defined as an instance of the <code>Monad</code> class in the standard prelude. 

−  [[Image:info.png]] When writing functions that work with monads, try to make use of the <tt>Monad</tt> class instead of using a specific monad instance. A function of the type 
+  [[Image:info.png]] When writing functions that work with monads, try to make use of the <code>Monad</code> class instead of using a specific monad instance. A function of the type 
−  <pre>doSomething :: (Monad m) => a > m b</pre> 
+  <haskell> 
+  doSomething :: (Monad m) => a > m b 

+  </haskell> 

is much more flexible than one of the type 
is much more flexible than one of the type 

−  <pre>doSomething :: a > Maybe b</pre> 
+  <haskell> 
−  The former function can be used with many types of monads to get different behavior depending on the strategy embodied in the monad, whereas the latter function is restricted to the strategy of the <tt>Maybe</tt> monad. 
+  doSomething :: a > Maybe b 
+  </haskell> 

+  The former function can be used with many types of monads to get different behavior depending on the strategy embodied in the monad, whereas the latter function is restricted to the strategy of the <code>Maybe</code> monad. 

== Do notation == 
== Do notation == 

−  Using the standard monadic function names is good, but another advantage of membership in the <tt>Monad</tt> class is the Haskell support for "do" notation. Do notation is an expressive shorthand for building up monadic computations, similar to the way that list comprehensions are an expressive shorthand for building computations on lists. Any instance of the <tt>Monad</tt> class can be used in a doblock in Haskell. 
+  Using the standard monadic function names is good, but another advantage of membership in the <code>Monad</code> class is the Haskell support for "do" notation. Do notation is an expressive shorthand for building up monadic computations, similar to the way that list comprehensions are an expressive shorthand for building computations on lists. Any instance of the <code>Monad</code> class can be used in a doblock in Haskell. 
−  In short, the do notation allows you to write monadic computations using a pseudoimperative style with named variables. The result of a monadic computation can be "assigned" to a variable using a left arrow <tt><</tt> operator. Then using that variable in a subsequent monadic computation automatically performs the binding. The type of the expression to the right of the arrow is a monadic type <tt>m a</tt>. The expression to the left of the arrow is a pattern to be matched against the value ''inside'' the monad. <tt>(x:xs)</tt> would match against <tt>Maybe [1,2,3]</tt>, for example. 
+  In short, the do notation allows you to write monadic computations using a pseudoimperative style with named variables. The result of a monadic computation can be "assigned" to a variable using a left arrow <code><</code> operator. Then using that variable in a subsequent monadic computation automatically performs the binding. The type of the expression to the right of the arrow is a monadic type <code>m a</code>. The expression to the left of the arrow is a pattern to be matched against the value ''inside'' the monad. <code>(x:xs)</code> would match against <code>Maybe [1,2,3]</code>, for example. 
−  Here is a sample of do notation using the <tt>Maybe</tt> monad: 
+  Here is a sample of do notation using the <code>Maybe</code> monad: 
Code available in [[../examples/example2.hsexample2.hs]] 
Code available in [[../examples/example2.hsexample2.hs]] 

−  <pre> we can also use donotation to build complicated sequences 
+  <haskell> 
−  mothersPaternalGrandfather :: Sheep > Maybe Sheep 
+   we can also use donotation to build complicated sequences 
−  mothersPaternalGrandfather s = do m < mother s 
+  mothersPaternalGrandfather :: Sheep > Maybe Sheep 
−  gf < father m 
+  mothersPaternalGrandfather s = do m < mother s 
−  father gf</pre> 
+  gf < father m 
−  Compare this to <tt>fathersMaternalGrandmother</tt> written above without using do notation. 
+  father gf 
+  </haskell> 

+  Compare this to <code>fathersMaternalGrandmother</code> written above without using do notation. 

The do block shown above is written using the layout rule to define the extent of the block. Haskell also allows you to use braces and semicolons when defining a do block: 
The do block shown above is written using the layout rule to define the extent of the block. Haskell also allows you to use braces and semicolons when defining a do block: 

−  <pre>mothersPaternalGrandfather s = do { m < mother s; gf < father m; father gf }</pre> 
+  <haskell> 
+  mothersPaternalGrandfather s = do { m < mother s; gf < father m; father gf } 

+  </haskell> 

Notice that do notation resembles an imperative programming language, in which a computation is built up from an explicit sequence of simpler computations. In this respect, monads offer the possibility to create imperativestyle computations within a larger functional program. This theme will be expanded upon when we deal with sideeffects and the I/O monad later. 
Notice that do notation resembles an imperative programming language, in which a computation is built up from an explicit sequence of simpler computations. In this respect, monads offer the possibility to create imperativestyle computations within a larger functional program. This theme will be expanded upon when we deal with sideeffects and the I/O monad later. 

Do notation is simply syntactic sugar. There is nothing that can be done using do notation that cannot be done using only the standard monadic operators. But do notation is cleaner and more convenient in some cases, especially when the sequence of monadic computations is long. You should understand both the standard monadic binding notation and do notation and be able to apply each where they are appropriate. 
Do notation is simply syntactic sugar. There is nothing that can be done using do notation that cannot be done using only the standard monadic operators. But do notation is cleaner and more convenient in some cases, especially when the sequence of monadic computations is long. You should understand both the standard monadic binding notation and do notation and be able to apply each where they are appropriate. 

−  The actual translation from do notation to standard monadic operators is roughly that every expression matched to a pattern, <tt>x < expr1</tt>, becomes 
+  The actual translation from do notation to standard monadic operators is roughly that every expression matched to a pattern, <code>x < expr1</code>, becomes 
−  <pre>expr1 >>= \x ></pre> 
+  <haskell> 
−  and every expression without a variable assignment, <tt>expr2</tt> becomes 
+  expr1 >>= \x > 
+  </haskell> 

+  and every expression without a variable assignment, <code>expr2</code> becomes 

−  <pre>expr2 >>= \_ ></pre> 
+  <haskell> 
−  All do blocks must end with a monadic expression, and a let clause is allowed at the beginning of a do block (but let clauses in do blocks do not use the "in" keyword). The definition of <tt>mothersPaternalGrandfather</tt> above would be translated to: 
+  expr2 >>= \_ > 
+  </haskell> 

+  All do blocks must end with a monadic expression, and a let clause is allowed at the beginning of a do block (but let clauses in do blocks do not use the "in" keyword). The definition of <code>mothersPaternalGrandfather</code> above would be translated to: 

−  <pre>mothersPaternalGrandfather s = mother s >>= \m > 
+  <haskell> 
−  father m >>= \gf > 
+  mothersPaternalGrandfather s = mother s >>= \m > 
−  father gf</pre> 
+  father m >>= \gf > 
+  father gf 

+  </haskell> 

It now becomes clear why the binding operator is so named. It is literally used to bind the value in the monad to the argument in the following lambda expression. 
It now becomes clear why the binding operator is so named. It is literally used to bind the value in the monad to the argument in the following lambda expression. 

== Summary == 
== Summary == 

−  Haskell provides builtin support for monads. To take advantage of Haskell's monad support, you must declare the monad type constructor to be an instance of the <tt>Monad</tt> class and supply definitions of the <tt>return</tt> and <tt>>>=</tt> (pronounced "bind") functions for the monad. 
+  Haskell provides builtin support for monads. To take advantage of Haskell's monad support, you must declare the monad type constructor to be an instance of the <code>Monad</code> class and supply definitions of the <code>return</code> and <code>>>=</code> (pronounced "bind") functions for the monad. 
−  A monad that is an instance of the <tt>Monad</tt> class can be used with donotation, which is syntactic sugar that provides a simple, imperativestyle notation for describing computations with monads. 
+  A monad that is an instance of the <code>Monad</code> class can be used with donotation, which is syntactic sugar that provides a simple, imperativestyle notation for describing computations with monads. 
−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[meet.htmlMeet the Monads]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[laws.htmlThe monad laws]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

The monad laws 
The monad laws 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[class.htmlDoing it with class]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[exercises.htmlExercises]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The monad laws = 
= The monad laws = 

−  * [[#lawsThe three fundamental laws]] 
+  The tutorial up to now has avoided technical discussions, but there are a few technical points that must be made concerning monads. Monadic operations must obey a set of laws, known as "the monad axioms". These laws aren't enforced by the Haskell compiler, so it is up to the programmer to ensure that any <code>Monad</code> instances they declare obey the laws. Haskell's <code>Monad</code> class also includes some functions beyond the minimal complete definition that we have not seen yet. Finally, many monads obey additional laws beyond the standard monad laws, and there is an additional Haskell class to support these extended monads. 
−  * [[#failFailure IS an option]] 

−  * [[#nowayoutNo way out]] 

−  * [[#zeroZero and Plus]] 

−  * [[#summarySummary]] 

−  
−  
−   

−  
−  The tutorial up to now has avoided technical discussions, but there are a few technical points that must be made concerning monads. Monadic operations must obey a set of laws, known as "the monad axioms". These laws aren't enforced by the Haskell compiler, so it is up to the programmer to ensure that any <tt>Monad</tt> instances he declares obey they laws. Haskell's <tt>Monad</tt> class also includes some functions beyond the minimal complete definition that we have not seen yet. Finally, many monads obey additional laws beyond the standard monad laws, and there is an additional Haskell class to support these extended monads. 

== The three fundamental laws == 
== The three fundamental laws == 

−  The concept of a monad comes from a branch of mathematics called category theory. While it is not necessary to know category theory to create and use monads, we do need to obey a small bit of mathematical formalism. To create a monad, it is not enough just to declare a Haskell instance of the <tt>Monad</tt> class with the correct type signatures. To be a proper monad, the <tt>return</tt> and <tt>>>=</tt> functions must work together according to three laws: 
+  The concept of a monad comes from a branch of mathematics called category theory. While it is not necessary to know category theory to create and use monads, we do need to obey a small bit of mathematical formalism. To create a monad, it is not enough just to declare a Haskell instance of the <code>Monad</code> class with the correct type signatures. To be a proper monad, the <code>return</code> and <code>>>=</code> functions must work together according to three laws: 
−  # <tt>(return x) >>= f == f x</tt> 
+  # <code>(return x) >>= f == f x</code> 
−  # <tt>m >>= return == m</tt> 
+  # <code>m >>= return == m</code> 
−  # <tt>(m >>= f) >>= g == m >>= (\x > f x >>= g)</tt> 
+  # <code>(m >>= f) >>= g == m >>= (\x > f x >>= g)</code> 
−  The first law requires that <tt>return</tt> is a leftidentity with respect to <tt>>>=</tt>. The second law requires that <tt>return</tt> is a rightidentity with respect to <tt>>>=</tt>. The third law is a kind of associativity law for <tt>>>=</tt>. Obeying the three laws ensures that the semantics of the donotation using the monad will be consistent. 
+  The first law requires that <code>return</code> is a leftidentity with respect to <code>>>=</code>. The second law requires that <code>return</code> is a rightidentity with respect to <code>>>=</code>. The third law is a kind of associativity law for <code>>>=</code>. Obeying the three laws ensures that the semantics of the donotation using the monad will be consistent. 
−  Any type constructor with return and bind operators that satisfy the three monad laws is a monad. In Haskell, the compiler does not check that the laws hold for every instance of the <tt>Monad</tt> class. It is up to the programmer to ensure that any <tt>Monad</tt> instance he creates satisfies the monad laws. 
+  Any type constructor with return and bind operators that satisfy the three monad laws is a monad. In Haskell, the compiler does not check that the laws hold for every instance of the <code>Monad</code> class. It is up to the programmer to ensure that any <code>Monad</code> instance they create satisfies the monad laws. 
== Failure IS an option == 
== Failure IS an option == 

−  The definition of the <tt>Monad</tt> class given [[class.html#monadearlier]] showed only the minimal complete definition. The full definition of the <tt>Monad</tt> class actually includes two additional functions: <tt>fail</tt> and <tt>>></tt>. 
+  The definition of the <code>Monad</code> class given [[class.html#monadearlier]] showed only the minimal complete definition. The full definition of the <code>Monad</code> class actually includes two additional functions: <code>fail</code> and <code>>></code>. 
−  The default implementation of the <tt>fail</tt> function is: 
+  The default implementation of the <code>fail</code> function is: 
−  <pre>fail s = error s</pre> 
+  <haskell> 
−  You do not need to change this for your monad unless you want to provide different behavior for failure or to incorporate failure into the computational strategy of your monad. The <tt>Maybe</tt> monad, for instance, defines <tt>fail</tt> as: 
+  fail s = error s 
+  </haskell> 

+  You do not need to change this for your monad unless you want to provide different behavior for failure or to incorporate failure into the computational strategy of your monad. The <code>Maybe</code> monad, for instance, defines <code>fail</code> as: 

−  <pre>fail _ = Nothing</pre> 
+  <haskell> 
−  so that <tt>fail</tt> returns an instance of the <tt>Maybe</tt> monad with meaningful behavior when it is bound with other functions in the <tt>Maybe</tt> monad. 
+  fail _ = Nothing 
+  </haskell> 

+  so that <code>fail</code> returns an instance of the <code>Maybe</code> monad with meaningful behavior when it is bound with other functions in the <code>Maybe</code> monad. 

−  The <tt>fail</tt> function is not a required part of the mathematical definition of a monad, but it is included in the standard <tt>Monad</tt> class definition because of the role it plays in Haskell's do notation. The <tt>fail</tt> function is called whenever a pattern matching failure occurs in a do block: 
+  The <code>fail</code> function is not a required part of the mathematical definition of a monad, but it is included in the standard <code>Monad</code> class definition because of the role it plays in Haskell's do notation. The <code>fail</code> function is called whenever a pattern matching failure occurs in a do block: 
−  <pre>fn :: Int > Maybe [Int] 
+  <haskell> 
+  fn :: Int > Maybe [Int] 

fn idx = do let l = [Just [1,2,3], Nothing, Just [], Just [7..20]] 
fn idx = do let l = [Just [1,2,3], Nothing, Just [], Just [7..20]] 

−  (x:xs) < l!!idx  a pattern match failure will call "fail" 
+  (x:xs) < l!!idx  a pattern match failure will call "fail" 
−  return xs</pre> 
+  return xs 
−  So in the code above, <tt>fn 0</tt> has the value <tt>Just [2,3]</tt>, but <tt>fn 1</tt> and <tt>fn 2</tt> both have the value <tt>Nothing</tt>. 
+  </haskell> 
+  So in the code above, <code>fn 0</code> has the value <code>Just [2,3]</code>, but <code>fn 1</code> and <code>fn 2</code> both have the value <code>Nothing</code>. 

−  The <tt>>></tt> function is a convenience operator that is used to bind a monadic computation that does not require input from the previous computation in the sequence. It is defined in terms of <tt>>>=</tt>: 
+  The <code>>></code> function is a convenience operator that is used to bind a monadic computation that does not require input from the previous computation in the sequence. It is defined in terms of <code>>>=</code>: 
−  <pre>(>>) :: m a > m b > m b 
+  <haskell> 
−  m >> k = m >>= (\_ > k)</pre> 
+  (>>) :: m a > m b > m b 
+  m >> k = m >>= (\_ > k) 

+  </haskell> 

== No way out == 
== No way out == 

−  You might have noticed that there is no way to get values out of a monad as defined in the standard <tt>Monad</tt> class. That is not an accident. Nothing prevents the monad author from allowing it using functions specific to the monad. For instance, values can be extracted from the <tt>Maybe</tt> monad by pattern matching on <tt>Just x</tt> or using the <tt>fromJust</tt> function. 
+  You might have noticed that there is no way to get values out of a monad as defined in the standard <code>Monad</code> class. That is not an accident. Nothing prevents the monad author from allowing it using functions specific to the monad. For instance, values can be extracted from the <code>Maybe</code> monad by pattern matching on <code>Just x</code> or using the <code>fromJust</code> function. 
−  By not requiring such a function, the Haskell <tt>Monad</tt> class allows the creation of oneway monads. Oneway monads allow values to enter the monad through the <tt>return</tt> function (and sometimes the <tt>fail</tt> function) and they allow computations to be performed within the monad using the bind functions <tt>>>=</tt> and <tt>>></tt>, but they do not allow values back out of the monad. 
+  By not requiring such a function, the Haskell <code>Monad</code> class allows the creation of oneway monads. Oneway monads allow values to enter the monad through the <code>return</code> function (and sometimes the <code>fail</code> function) and they allow computations to be performed within the monad using the bind functions <code>>>=</code> and <code>>></code>, but they do not allow values back out of the monad. 
−  The <tt>IO</tt> monad is a familiar example of a oneway monad in Haskell. Because you can't escape from the <tt>IO</tt> monad, it is impossible to write a function that does a computation in the <tt>IO</tt> monad but whose result type does not include the <tt>IO</tt> type constructor. This means that ''any'' function whose result type does not contain the <tt>IO</tt> type constructor is guaranteed not to use the <tt>IO</tt> monad. Other monads, such as <tt>List</tt> and <tt>Maybe</tt>, do allow values out of the monad. So it is possible to write functions which use these monads internally but return nonmonadic values. 
+  The <code>IO</code> monad is a familiar example of a oneway monad in Haskell. Because you can't escape from the <code>IO</code> monad, it is impossible to write a function that does a computation in the <code>IO</code> monad but whose result type does not include the <code>IO</code> type constructor. This means that ''any'' function whose result type does not contain the <code>IO</code> type constructor is guaranteed not to use the <code>IO</code> monad. Other monads, such as <code>List</code> and <code>Maybe</code>, do allow values out of the monad. So it is possible to write functions which use these monads internally but return nonmonadic values. 
''The wonderful feature of a oneway monad is that it can support sideeffects in its monadic operations but prevent them from destroying the functional properties of the nonmonadic portions of the program.'' 
''The wonderful feature of a oneway monad is that it can support sideeffects in its monadic operations but prevent them from destroying the functional properties of the nonmonadic portions of the program.'' 

−  Consider the simple issue of reading a character from the user. We cannot simply have a function <tt>readChar :: Char</tt>, because it needs to return a different character each time it is called, depending on the input from the user. It is an essential property of Haskell as a pure functional language that all functions return the same value when called twice with the same arguments. But it ''is'' ok to have an I/O function <tt>getChar :: IO Char</tt> in the <tt>IO</tt> monad, because it can only be used in a sequence within the oneway monad. There is no way to get rid of the <tt>IO</tt> type constructor in the signature of any function that uses it, so the <tt>IO</tt> type constructor acts as a kind of tag that identifies all functions that do I/O. Furthermore, such functions are only useful within the <tt>IO</tt> monad. So a oneway monad effectively creates an isolated computational domain in which the rules of a pure functional language can be relaxed. Functional computations can move into the domain, but dangerous sideeffects and nonreferentiallytransparent functions cannot escape from it. 
+  Consider the simple issue of reading a character from the user. We cannot simply have a function <code>readChar :: Char</code>, because it needs to return a different character each time it is called, depending on the input from the user. It is an essential property of Haskell as a pure functional language that all functions return the same value when called twice with the same arguments. But it ''is'' ok to have an I/O function <code>getChar :: IO Char</code> in the <code>IO</code> monad, because it can only be used in a sequence within the oneway monad. There is no way to get rid of the <code>IO</code> type constructor in the signature of any function that uses it, so the <code>IO</code> type constructor acts as a kind of tag that identifies all functions that do I/O. Furthermore, such functions are only useful within the <code>IO</code> monad. So a oneway monad effectively creates an isolated computational domain in which the rules of a pure functional language can be relaxed. Functional computations can move into the domain, but dangerous sideeffects and nonreferentiallytransparent functions cannot escape from it. 
Another common pattern when defining monads is to represent monadic values as functions. Then when the value of a monadic computation is required, the resulting monad is "run" to provide the answer. 
Another common pattern when defining monads is to represent monadic values as functions. Then when the value of a monadic computation is required, the resulting monad is "run" to provide the answer. 

Line 351:  Line 281:  
== Zero and Plus == 
== Zero and Plus == 

−  Beyond the three monad laws stated above, some monads obey additional laws. The monads have a special value <tt>mzero</tt> and an operator <tt>mplus</tt> that obey four additional laws: 
+  Beyond the three monad laws stated above, some monads obey additional laws. The monads have a special value <code>mzero</code> and an operator <code>mplus</code> that obey four additional laws: 
−  # <tt>mzero >>= f == mzero</tt> 
+  # <code>mzero >>= f == mzero</code> 
−  # <tt>m >>= (\x > mzero) == mzero</tt> 
+  # <code>m >>= (\x > mzero) == mzero</code> 
−  # <tt>mzero `mplus` m == m</tt> 
+  # <code>mzero `mplus` m == m</code> 
−  # <tt>m `mplus` mzero == m</tt> 
+  # <code>m `mplus` mzero == m</code> 
−  It is easy to remember the laws for <tt>mzero</tt> and <tt>mplus</tt> if you associate <tt>mzero</tt> with 0, <tt>mplus</tt> with +, and <tt>>>=</tt> with × in ordinary arithmetic. 
+  It is easy to remember the laws for <code>mzero</code> and <code>mplus</code> if you associate <code>mzero</code> with 0, <code>mplus</code> with +, and <code>>>=</code> with × in ordinary arithmetic. 
−  Monads which have a zero and a plus can be declared as instances of the <tt>MonadPlus</tt> class in Haskell: 
+  Monads which have a zero and a plus can be declared as instances of the <code>MonadPlus</code> class in Haskell: 
−  <pre>class (Monad m) => MonadPlus m where 
+  <haskell> 
+  class (Monad m) => MonadPlus m where 

mzero :: m a 
mzero :: m a 

−  mplus :: m a > m a > m a</pre> 
+  mplus :: m a > m a > m a 
−  Continuing to use the <tt>Maybe</tt> monad as an example, we see that the <tt>Maybe</tt> monad is an instance of <tt>MonadPlus</tt>: 
+  </haskell> 
+  Continuing to use the <code>Maybe</code> monad as an example, we see that the <code>Maybe</code> monad is an instance of <code>MonadPlus</code>: 

−  <pre>instance MonadPlus Maybe where 
+  <haskell> 
+  instance MonadPlus Maybe where 

mzero = Nothing 
mzero = Nothing 

Nothing `mplus` x = x 
Nothing `mplus` x = x 

−  x `mplus` _ = x</pre> 
+  x `mplus` _ = x 
−  This identifies <tt>Nothing</tt> as the zero value and says that adding two <tt>Maybe</tt> values together gives the first value that is not <tt>Nothing</tt>. If both input values are <tt>Nothing</tt>, then the result of <tt>mplus</tt> is also <tt>Nothing</tt>. 
+  </haskell> 
+  This identifies <code>Nothing</code> as the zero value and says that adding two <code>Maybe</code> values together gives the first value that is not <code>Nothing</code>. If both input values are <code>Nothing</code>, then the result of <code>mplus</code> is also <code>Nothing</code>. 

−  The List monad also has a zero and a plus. <tt>mzero</tt> is the empty list and <tt>mplus</tt> is the <tt>++</tt> operator. 
+  The List monad also has a zero and a plus. <code>mzero</code> is the empty list and <code>mplus</code> is the <code>++</code> operator. 
−  The <tt>mplus</tt> operator is used to combine monadic values from separate computations into a single monadic value. Within the context of our sheepcloning example, we could use <tt>Maybe</tt>'s <tt>mplus</tt> to define a function, <tt>parent s = (mother s) `mplus` (father s)</tt>, which would return a parent if there is one, and <tt>Nothing</tt> is the sheep has no parents at all. For a sheep with both parents, the function would return one or the other, depending on the exact definition of <tt>mplus</tt> in the <tt>Maybe</tt> monad. 
+  The <code>mplus</code> operator is used to combine monadic values from separate computations into a single monadic value. Within the context of our sheepcloning example, we could use <code>Maybe</code>'s <code>mplus</code> to define a function, <code>parent s = (mother s) `mplus` (father s)</code>, which would return a parent if there is one, and <code>Nothing</code> is the sheep has no parents at all. For a sheep with both parents, the function would return one or the other, depending on the exact definition of <code>mplus</code> in the <code>Maybe</code> monad. 
== Summary == 
== Summary == 

−  Instances of the <tt>Monad</tt> class should conform to the socalled monad laws, which describe algabraic properties of monads. There are three of these laws which state that the <tt>return</tt> function is both a left and a right identity and that the binding operator is associative. Failure to satisfy these laws will result in monads that do not behave properly and may cause subtle problems when using donotation. 
+  Instances of the <code>Monad</code> class should conform to the socalled monad laws, which describe algabraic properties of monads. There are three of these laws which state that the <code>return</code> function is both a left and a right identity and that the binding operator is associative. Failure to satisfy these laws will result in monads that do not behave properly and may cause subtle problems when using donotation. 
−  In addition to the <tt>return</tt> and <tt>>>=</tt> functions, the <tt>Monad</tt> class defines another function, <tt>fail</tt>. The <tt>fail</tt> function is not a technical requirement for inclusion as a monad, but it is often useful in practice and it is included in the <tt>Monad</tt> class because it is used in Haskell's donotation. 
+  In addition to the <code>return</code> and <code>>>=</code> functions, the <code>Monad</code> class defines another function, <code>fail</code>. The <code>fail</code> function is not a technical requirement for inclusion as a monad, but it is often useful in practice and it is included in the <code>Monad</code> class because it is used in Haskell's donotation. 
−  Some monads obey laws beyond the three basic monad laws. An important class of such monads are ones which have a notion of a zero element and a plus operator. Haskell provides a <tt>MonadPlus</tt> class for such monads which define the <tt>mzero</tt> value and the <tt>mplus</tt> operator. 
+  Some monads obey laws beyond the three basic monad laws. An important class of such monads are ones which have a notion of a zero element and a plus operator. Haskell provides a <code>MonadPlus</code> class for such monads which define the <code>mzero</code> value and the <code>mplus</code> operator. 
−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[class.htmlDoing it with class]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[exercises.htmlExercises]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Exercises 
Exercises 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[laws.htmlThe monad laws]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[monadfns.htmlMonad support in Haskell]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Exercises = 
= Exercises = 

Line 403:  Line 323:  
# [[#exercise3Using the List monad]] 
# [[#exercise3Using the List monad]] 

# [[#exercise4Using the Monad class constraint]] 
# [[#exercise4Using the Monad class constraint]] 

−  
−  
−   

This section contains a few simple exercises to hone the reader's monadic reasoning skills and to provide a solid comprehension of the function and use of the Maybe and List monads before looking at monadic programming in more depth. The exercises will build on the previous sheepcloning [[../examples/example2.hsexample]], with which the reader should already be familiar. 
This section contains a few simple exercises to hone the reader's monadic reasoning skills and to provide a solid comprehension of the function and use of the Maybe and List monads before looking at monadic programming in more depth. The exercises will build on the previous sheepcloning [[../examples/example2.hsexample]], with which the reader should already be familiar. 

Line 411:  Line 328:  
== Exercise 1: Do notation == 
== Exercise 1: Do notation == 

−  Rewrite the <tt>maternalGrandfather</tt>, <tt>fathersMaternalGrandmother</tt>, and <tt>mothersPaternalGrandfather</tt> functions in [[../examples/example2.hsExample 2]] using the monadic operators <tt>return</tt> and <tt>>>=</tt>, without using any donotation syntactic sugar. 
+  Rewrite the <code>maternalGrandfather</code>, <code>fathersMaternalGrandmother</code>, and <code>mothersPaternalGrandfather</code> functions in [[../examples/example2.hsExample 2]] using the monadic operators <code>return</code> and <code>>>=</code>, without using any donotation syntactic sugar. 
Line 419:  Line 336:  
== Exercise 2: Combining monadic values == 
== Exercise 2: Combining monadic values == 

−  Write functions <tt>parent</tt> and <tt>grandparent</tt> with signature <tt>Sheep > Maybe Sheep</tt>. They should return one sheep selected from all sheep matching the description, or <tt>Nothing</tt> if there is no such sheep. Hint: the <tt>mplus</tt> operator is useful here. 
+  Write functions <code>parent</code> and <code>grandparent</code> with signature <code>Sheep > Maybe Sheep</code>. They should return one sheep selected from all sheep matching the description, or <code>Nothing</code> if there is no such sheep. Hint: the <code>mplus</code> operator is useful here. 
Click [[solution2.htmlhere]] to see the solution. 
Click [[solution2.htmlhere]] to see the solution. 

Line 425:  Line 342:  
== Exercise 3: Using the List monad == 
== Exercise 3: Using the List monad == 

−  Write functions <tt>parent</tt> and <tt>grandparent</tt> with signature <tt>Sheep > [Sheep]</tt>. They should return all sheep matching the description, or the empty list if there is no such sheep. Hint: the <tt>mplus</tt> operator in the List monad is useful here. Also the <tt>maybeToList</tt> function in the <tt>Maybe</tt> module can be used to convert a value from the Maybe monad to the List monad. 
+  Write functions <code>parent</code> and <code>grandparent</code> with signature <code>Sheep > [Sheep]</code>. They should return all sheep matching the description, or the empty list if there is no such sheep. Hint: the <code>mplus</code> operator in the List monad is useful here. Also the <code>maybeToList</code> function in the <code>Maybe</code> module can be used to convert a value from the Maybe monad to the List monad. 
Click [[solution3.htmlhere]] to see the solution. 
Click [[solution3.htmlhere]] to see the solution. 

Line 431:  Line 348:  
== Exercise 4: Using the Monad class constraint == 
== Exercise 4: Using the Monad class constraint == 

−  Monads promote modularity and code reuse by encapsulating oftenused computational strategies into single blocks of code that can be used to construct many different computations. Less obviously, monads also promote modularity by allowing you to vary the monad in which a computation is done to achieve different variations of the computation. This is achieved by writing functions which are polymorphic in the monad type constructor, using the <tt>(Monad m) =></tt>, <tt>(MonadPlus m) =></tt>, etc. class constraints. 
+  Monads promote modularity and code reuse by encapsulating oftenused computational strategies into single blocks of code that can be used to construct many different computations. Less obviously, monads also promote modularity by allowing you to vary the monad in which a computation is done to achieve different variations of the computation. This is achieved by writing functions which are polymorphic in the monad type constructor, using the <code>(Monad m) =></code>, <code>(MonadPlus m) =></code>, etc. class constraints. 
−  Write functions <tt>parent</tt> and <tt>grandparent</tt> with signature <tt>(MonadPlus m) => Sheep > m Sheep</tt>. They should be useful in both the Maybe and List monads. How does the functions' behavior differ when used with the List monad versus the Maybe monad? If you need to review the use of type classes and class constraints in Haskell, look [http://www.haskell.org/tutorial/classes.html here]. 
+  Write functions <code>parent</code> and <code>grandparent</code> with signature <code>(MonadPlus m) => Sheep > m Sheep</code>. They should be useful in both the Maybe and List monads. How does the functions' behavior differ when used with the List monad versus the Maybe monad? If you need to review the use of type classes and class constraints in Haskell, look [http://www.haskell.org/tutorial/classes.html here]. 
Click [[solution4.htmlhere]] to see the solution. 
Click [[solution4.htmlhere]] to see the solution. 

−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[laws.htmlThe monad laws]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[monadfns.htmlMonad support in Haskell]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Monad support in Haskell 
Monad support in Haskell 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[exercises.htmlExercises]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[introII.htmlPart II  Introduction]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Monad support in Haskell = 
= Monad support in Haskell = 

−  
−  * [[#preludeIn the standard prelude]] 

−  * [[#monadIn the Monad module]] 

−  * [[#summarySummary]] 

−  
−  
−   

Haskell's built in support for monads is split among the standard prelude, which exports the most common monad functions, and the Monad module, which contains lesscommonly used monad functions. The individual monad types are each in their own libraries and are the subject of [[introII.htmlPart II]] of this tutorial. 
Haskell's built in support for monads is split among the standard prelude, which exports the most common monad functions, and the Monad module, which contains lesscommonly used monad functions. The individual monad types are each in their own libraries and are the subject of [[introII.htmlPart II]] of this tutorial. 

Line 475:  Line 362:  
== In the standard prelude == 
== In the standard prelude == 

−  The Haskell 98 [http://www.haskell.org/onlinelibrary/standardprelude.html standard prelude] includes the definition of the <tt>Monad</tt> class as well as a few auxilliary functions for working with monadic data types. 
+  The Haskell 98 [http://www.haskell.org/onlinelibrary/standardprelude.html standard prelude] includes the definition of the <code>Monad</code> class as well as a few auxilliary functions for working with monadic data types. 
−  === The <tt>Monad</tt> class === 
+  === The <code>Monad</code> class === 
−  We have seen the <tt>Monad</tt> class before: 
+  We have seen the <code>Monad</code> class before: 
−  <pre>class Monad m where 
+  <haskell> 
−  (>>=) :: m a > (a > m b) > m b 
+  class Monad m where 
−  (>>) :: m a > m b > m b 
+  (>>=) :: m a > (a > m b) > m b 
−  return :: a > m a 
+  (>>) :: m a > m b > m b 
−  fail :: String > m a 
+  return :: a > m a 
+  fail :: String > m a 

 Minimal complete definition: 
 Minimal complete definition: 

−   (>>=), return 
+   (>>=), return 
−  m >> k = m >>= \_ > k 
+  m >> k = m >>= \_ > k 
−  fail s = error s</pre> 
+  fail s = error s 
+  </haskell> 

=== The sequencing functions === 
=== The sequencing functions === 

−  The <tt>sequence</tt> function takes a list of monadic computations, executes each one in turn and returns a list of the results. If any of the computations fail, then the whole function fails: 
+  The <code>sequence</code> function takes a list of monadic computations, executes each one in turn and returns a list of the results. If any of the computations fail, then the whole function fails: 
−  <pre>sequence :: Monad m => [m a] > m [a] 
+  <haskell> 
+  sequence :: Monad m => [m a] > m [a] 

sequence = foldr mcons (return []) 
sequence = foldr mcons (return []) 

−  where mcons p q = p >>= \x > q >>= \y > return (x:y)</pre> 
+  where mcons p q = p >>= \x > q >>= \y > return (x:y) 
−  The <tt>sequence_</tt> function (notice the underscore) has the same behavior as <tt>sequence</tt> but does not return a list of results. It is useful when only the sideeffects of the monadic computations are important. 
+  </haskell> 
+  The <code>sequence_</code> function (notice the underscore) has the same behavior as <code>sequence</code> but does not return a list of results. It is useful when only the sideeffects of the monadic computations are important. 

−  <pre>sequence_ :: Monad m => [m a] > m () 
+  <haskell> 
−  sequence_ = foldr (>>) (return ())</pre> 
+  sequence_ :: Monad m => [m a] > m () 
+  sequence_ = foldr (>>) (return ()) 

+  </haskell> 

=== The mapping functions === 
=== The mapping functions === 

−  The <tt>mapM</tt> function maps a monadic computation over a list of values and returns a list of the results. It is defined in terms of the list <tt>map</tt> function and the <tt>sequence</tt> function above: 
+  The <code>mapM</code> function maps a monadic computation over a list of values and returns a list of the results. It is defined in terms of the list <code>map</code> function and the <code>sequence</code> function above: 
−  <pre>mapM :: Monad m => (a > m b) > [a] > m [b] 
+  <haskell> 
−  mapM f as = sequence (map f as)</pre> 
+  mapM :: Monad m => (a > m b) > [a] > m [b] 
−  There is also a version with an underscore, <tt>mapM_</tt> which is defined using sequence_. <tt>mapM_</tt> operates the same as <tt>mapM</tt>, but it doesn't return the list of values. It is useful when only the sideeffects of the monadic computation are important. 
+  mapM f as = sequence (map f as) 
+  </haskell> 

+  There is also a version with an underscore, <code>mapM_</code> which is defined using sequence_. <code>mapM_</code> operates the same as <code>mapM</code>, but it doesn't return the list of values. It is useful when only the sideeffects of the monadic computation are important. 

−  <pre>mapM_ :: Monad m => (a > m b) > [a] > m () 
+  <haskell> 
−  mapM_ f as = sequence_ (map f as)</pre> 
+  mapM_ :: Monad m => (a > m b) > [a] > m () 
−  As a simple example of the use the mapping functions, a <tt>putString</tt> function for the <tt>IO</tt> monad could be defined as: 
+  mapM_ f as = sequence_ (map f as) 
+  </haskell> 

+  As a simple example of the use the mapping functions, a <code>putString</code> function for the <code>IO</code> monad could be defined as: 

−  <pre>putString :: [Char] > IO () 
+  <haskell> 
−  putString s = mapM_ putChar s</pre> 
+  putString :: [Char] > IO () 
−  <tt>mapM</tt> can be used within a do block in a manner similar to the way the <tt>map</tt> function is normally used on lists. This is a common pattern with monads — a version of a function for use within a monad (i.e., intended for binding) will have a signature similar to the nonmonadic version but the function outputs will be within the monad: 
+  putString s = mapM_ putChar s 
+  </haskell> 

+  <code>mapM</code> can be used within a do block in a manner similar to the way the <code>map</code> function is normally used on lists. This is a common pattern with monads — a version of a function for use within a monad (i.e., intended for binding) will have a signature similar to the nonmonadic version but the function outputs will be within the monad: 

−  <pre> compare the nonmonadic and monadic signatures 
+  <haskell> 
−  map :: (a > b) > [a] > [b] 
+   compare the nonmonadic and monadic signatures 
−  mapM :: Monad m => (a > m b) > [a] > m [b] </pre> 
+  map :: (a > b) > [a] > [b] 
−  === The reverse binder function (<tt>=<<</tt>) === 
+  mapM :: Monad m => (a > m b) > [a] > m [b] 
+  </haskell> 

+  === The reverse binder function (<code>=<<</code>) === 

−  The prelude also defines a binding function that takes it arguments in the opposite order to the standard binding function. Since the standard binding function is called "<tt>>>=</tt>", the reverse binding function is called "<tt>=<<</tt>". It is useful in circumstances where the binding operator is used as a higherorder term and it is more convenient to have the arguments in the reversed order. Its definition is simply: 
+  The prelude also defines a binding function that takes it arguments in the opposite order to the standard binding function. Since the standard binding function is called "<code>>>=</code>", the reverse binding function is called "<code>=<<</code>". It is useful in circumstances where the binding operator is used as a higherorder term and it is more convenient to have the arguments in the reversed order. Its definition is simply: 
−  <pre>(=<<) :: Monad m => (a > m b) > m a > m b 
+  <haskell> 
−  f =<< x = x >>= f</pre> 
+  (=<<) :: Monad m => (a > m b) > m a > m b 
+  f =<< x = x >>= f 

+  </haskell> 

== In the Monad module == 
== In the Monad module == 

−  The <tt>Monad</tt> module in the standard Haskell 98 libraries exports a number of facilities for more advanced monadic operations. To access these facilities, simply <tt>import Monad</tt> in your Haskell program. 
+  The <code>Monad</code> module in the standard Haskell 98 libraries exports a number of facilities for more advanced monadic operations. To access these facilities, simply <code>import Monad</code> in your Haskell program. 
−  Not all of the function in the <tt>Monad</tt> module are discussed here, but you are encouraged to [http://www.haskell.org/onlinelibrary/monad.html explore the module for yourself] when you feel you are ready to see some of the more esoteric monad functions. 
+  Not all of the function in the <code>Monad</code> module are discussed here, but you are encouraged to [http://www.haskell.org/onlinelibrary/monad.html explore the module for yourself] when you feel you are ready to see some of the more esoteric monad functions. 
−  === The <tt>MonadPlus</tt> class === 
+  === The <code>MonadPlus</code> class === 
−  The <tt>Monad</tt> module defines the <tt>MonadPlus</tt> class for monads with a zero element and a plus operator: 
+  The <code>Monad</code> module defines the <code>MonadPlus</code> class for monads with a zero element and a plus operator: 
−  <pre>class Monad m => MonadPlus m where 
+  <haskell> 
+  class Monad m => MonadPlus m where 

mzero :: m a 
mzero :: m a 

−  mplus :: m a > m a > m a</pre> 
+  mplus :: m a > m a > m a 
+  </haskell> 

=== Monadic versions of list functions === 
=== Monadic versions of list functions === 

−  Several functions are provided which generalize standard listprocessing functions to monads. The <tt>mapM</tt> functions are exported in the standard prelude and were described above. 
+  Several functions are provided which generalize standard listprocessing functions to monads. The <code>mapM</code> functions are exported in the standard prelude and were described above. 
−  <tt>foldM</tt> is a monadic version of <tt>foldl</tt> in which monadic computations built from a list are bound lefttoright. The definition is: 
+  <code>foldM</code> is a monadic version of <code>foldl</code> in which monadic computations built from a list are bound lefttoright. The definition is: 
−  <pre>foldM :: (Monad m) => (a > b > m a) > a > [b] > m a 
+  <haskell> 
+  foldM :: (Monad m) => (a > b > m a) > a > [b] > m a 

foldM f a [] = return a 
foldM f a [] = return a 

−  foldM f a (x:xs) = f a x >>= \y > foldM f y xs</pre> 
+  foldM f a (x:xs) = f a x >>= \y > foldM f y xs 
−  but it is easier to understand the operation of <tt>foldM</tt> if you consider its effect in terms of a do block: 
+  </haskell> 
+  but it is easier to understand the operation of <code>foldM</code> if you consider its effect in terms of a do block: 

−  <pre> this is not valid Haskell code, it is just for illustration 
+  <haskell> 
−  foldM f a1 [x1,x2,...,xn] = do a2 < f a1 x1 
+   this is not valid Haskell code, it is just for illustration 
−  a3 < f a2 x2 
+  foldM f a1 [x1,x2,...,xn] = do a2 < f a1 x1 
+  a3 < f a2 x2 

... 
... 

−  f an xn</pre> 
+  f an xn 
−  Righttoleft binding is achieved by reversing the input list before calling <tt>foldM</tt>. 
+  </haskell> 
+  Righttoleft binding is achieved by reversing the input list before calling <code>foldM</code>. 

−  We can use <tt>foldM</tt> to create a more poweful query function in our sheep cloning example: 
+  We can use <code>foldM</code> to create a more poweful query function in our sheep cloning example: 
Code available in [[../examples/example3.hsexample3.hs]] 
Code available in [[../examples/example3.hsexample3.hs]] 

−  <pre> traceFamily is a generic function to find an ancestor 
+  <haskell> 
−  traceFamily :: Sheep > [ (Sheep > Maybe Sheep) ] > Maybe Sheep 
+   traceFamily is a generic function to find an ancestor 
+  traceFamily :: Sheep > [ (Sheep > Maybe Sheep) ] > Maybe Sheep 

traceFamily s l = foldM getParent s l 
traceFamily s l = foldM getParent s l 

where getParent s f = f s 
where getParent s f = f s 

Line 569:  Line 456:  
 we can define complex queries using traceFamily in an easy, clear way 
 we can define complex queries using traceFamily in an easy, clear way 

mothersPaternalGrandfather s = traceFamily s [mother, father, father] 
mothersPaternalGrandfather s = traceFamily s [mother, father, father] 

−  paternalGrandmother s = traceFamily s [father, mother]</pre> 
+  paternalGrandmother s = traceFamily s [father, mother] 
−  The <tt>traceFamily</tt> function uses <tt>foldM</tt> to create a simple way to trace back in the family tree to any depth and in any pattern. In fact, it is probably clearer to write "<tt>traceFamily s [father, mother]</tt>" than it is to use the <tt>paternalGrandmother</tt> function! 
+  </haskell> 
+  The <code>traceFamily</code> function uses <code>foldM</code> to create a simple way to trace back in the family tree to any depth and in any pattern. In fact, it is probably clearer to write "<code>traceFamily s [father, mother]</code>" than it is to use the <code>paternalGrandmother</code> function! 

−  A more typical use of <tt>foldM</tt> is within a do block: 
+  A more typical use of <code>foldM</code> is within a do block: 
Code available in [[../examples/example4.hsexample4.hs]] 
Code available in [[../examples/example4.hsexample4.hs]] 

−  <pre> a Dict is just a finite map from strings to strings 
+  <haskell> 
+   a Dict is just a finite map from strings to strings 

type Dict = FiniteMap String String 
type Dict = FiniteMap String String 

 this an auxilliary function used with foldl 
 this an auxilliary function used with foldl 

−  addEntry :: Dict > Entry > Dict 
+  addEntry :: Dict > Entry > Dict 
addEntry d e = addToFM d (key e) (value e) 
addEntry d e = addToFM d (key e) (value e) 

 this is an auxiliiary function used with foldM inside the IO monad 
 this is an auxiliiary function used with foldM inside the IO monad 

−  addDataFromFile :: Dict > Handle > IO Dict 
+  addDataFromFile :: Dict > Handle > IO Dict 
−  addDataFromFile dict hdl = do contents < hGetContents hdl 
+  addDataFromFile dict hdl = do contents < hGetContents hdl 
−  entries < return (map read (lines contents)) 
+  entries < return (map read (lines contents)) 
return (foldl (addEntry) dict entries) 
return (foldl (addEntry) dict entries) 

Line 592:  Line 479:  
 command line and then prints it out as an association list 
 command line and then prints it out as an association list 

main :: IO () 
main :: IO () 

−  main = do files < getArgs 
+  main = do files < getArgs 
−  handles < mapM openForReading files 
+  handles < mapM openForReading files 
−  dict < foldM addDataFromFile emptyFM handles 
+  dict < foldM addDataFromFile emptyFM handles 
−  print (fmToList dict)</pre> 
+  print (fmToList dict) 
−  The <tt>filterM</tt> function works like the list <tt>filter</tt> function inside of a monad. It takes a predicate function which returns a Boolean value in the monad and a list of values. It returns, inside the monad, a list of those values for which the predicate was True. 
+  </haskell> 
+  The <code>filterM</code> function works like the list <code>filter</code> function inside of a monad. It takes a predicate function which returns a Boolean value in the monad and a list of values. It returns, inside the monad, a list of those values for which the predicate was True. 

−  <pre>filterM :: Monad m => (a > m Bool) > [a] > m [a] 
+  <haskell> 
+  filterM :: Monad m => (a > m Bool) > [a] > m [a] 

filterM p [] = return [] 
filterM p [] = return [] 

−  filterM p (x:xs) = do b < p x 
+  filterM p (x:xs) = do b < p x 
−  ys < filterM p xs 
+  ys < filterM p xs 
−  return (if b then (x:ys) else ys)</pre> 
+  return (if b then (x:ys) else ys) 
−  Here is an example showing how <tt>filterM</tt> can be used within the <tt>IO</tt> monad to select only the directories from a list: 
+  </haskell> 
+  Here is an example showing how <code>filterM</code> can be used within the <code>IO</code> monad to select only the directories from a list: 

Code available in [[../examples/example5.hsexample5.hs]] 
Code available in [[../examples/example5.hsexample5.hs]] 

−  <pre>import Monad 
+  <haskell> 
+  import Monad 

import Directory 
import Directory 

import System 
import System 

−   NOTE: doesDirectoryExist has type FilePath > IO Bool 
+   NOTE: doesDirectoryExist has type FilePath > IO Bool 
 this program prints only the directories named on the command line 
 this program prints only the directories named on the command line 

main :: IO () 
main :: IO () 

−  main = do names < getArgs 
+  main = do names < getArgs 
−  dirs < filterM doesDirectoryExist names 
+  dirs < filterM doesDirectoryExist names 
−  mapM_ putStrLn dirs</pre> 
+  mapM_ putStrLn dirs 
−  <tt>zipWithM</tt> is a monadic version of the <tt>zipWith</tt> function on lists. <tt>zipWithM_</tt> behaves the same but discards the output of the function. It is useful when only the sideeffects of the monadic computation matter. 
+  </haskell> 
+  <code>zipWithM</code> is a monadic version of the <code>zipWith</code> function on lists. <code>zipWithM_</code> behaves the same but discards the output of the function. It is useful when only the sideeffects of the monadic computation matter. 

−  <pre>zipWithM ::(Monad m) => (a > b > m c) > [a] > [b] > m [c] 
+  <haskell> 
+  zipWithM ::(Monad m) => (a > b > m c) > [a] > [b] > m [c] 

zipWithM f xs ys = sequence (zipWith f xs ys) 
zipWithM f xs ys = sequence (zipWith f xs ys) 

−  zipWithM_ ::(Monad m) => (a > b > m c) > [a] > [b] > m () 
+  zipWithM_ ::(Monad m) => (a > b > m c) > [a] > [b] > m () 
−  zipWithM_ f xs ys = sequence_ (zipWith f xs ys)</pre> 
+  zipWithM_ f xs ys = sequence_ (zipWith f xs ys) 
+  </haskell> 

=== Conditional monadic computations === 
=== Conditional monadic computations === 

−  There are two functions provided for conditionally executing monadic computations. The <tt>when</tt> function takes a boolean argument and a monadic computation with unit "()" type and performs the computation only when the boolean argument is <tt>True</tt>. The <tt>unless</tt> function does the same, except that it performs the computation ''unless'' the boolean argument is <tt>True</tt>. 
+  There are two functions provided for conditionally executing monadic computations. The <code>when</code> function takes a boolean argument and a monadic computation with unit "()" type and performs the computation only when the boolean argument is <code>True</code>. The <code>unless</code> function does the same, except that it performs the computation ''unless'' the boolean argument is <code>True</code>. 
−  <pre>when :: (Monad m) => Bool > m () > m () 
+  <haskell> 
+  when :: (Monad m) => Bool > m () > m () 

when p s = if p then s else return () 
when p s = if p then s else return () 

−  unless :: (Monad m) => Bool > m () > m () 
+  unless :: (Monad m) => Bool > m () > m () 
−  unless p s = when (not p) s</pre> 
+  unless p s = when (not p) s 
−  === <tt>ap</tt> and the lifting functions === 
+  </haskell> 
+  === <code>ap</code> and the lifting functions === 

''Lifting'' is a monadic operation that converts a nonmonadic function into an equivalent function that operates on monadic values. We say that a function is "lifted into the monad" by the lifting operators. A lifted function is useful for operating on monad values outside of a do block and can also allow for cleaner code within a do block. 
''Lifting'' is a monadic operation that converts a nonmonadic function into an equivalent function that operates on monadic values. We say that a function is "lifted into the monad" by the lifting operators. A lifted function is useful for operating on monad values outside of a do block and can also allow for cleaner code within a do block. 

−  The simplest lifting operator is <tt>liftM</tt>, which lifts a function of a single argument into a monad. 
+  The simplest lifting operator is <code>liftM</code>, which lifts a function of a single argument into a monad. 
−  <pre>liftM :: (Monad m) => (a > b) > (m a > m b) 
+  <haskell> 
−  liftM f = \a > do { a' < a; return (f a') }</pre> 
+  liftM :: (Monad m) => (a > b) > (m a > m b) 
−  Lifting operators are also provided for functions with more arguments. <tt>liftM2</tt> lifts functions of two arguments: 
+  liftM f = \a > do { a' < a; return (f a') } 
+  </haskell> 

+  Lifting operators are also provided for functions with more arguments. <code>liftM2</code> lifts functions of two arguments: 

−  <pre>liftM2 :: (Monad m) => (a > b > c) > (m a > m b > m c) 
+  <haskell> 
−  liftM2 f = \a b > do { a' < a; b' < b; return (f a' b') }</pre> 
+  liftM2 :: (Monad m) => (a > b > c) > (m a > m b > m c) 
−  The same pattern is applied to give the definitions to lift functions of more arguments. Functions up to <tt>liftM5</tt> are defined in the <tt>Monad</tt> module. 
+  liftM2 f = \a b > do { a' < a; b' < b; return (f a' b') } 
+  </haskell> 

+  The same pattern is applied to give the definitions to lift functions of more arguments. Functions up to <code>liftM5</code> are defined in the <code>Monad</code> module. 

−  To see how the lifting operators allow more concise code, consider a computation in the <tt>Maybe</tt> monad in which you want to use a function <tt>swapNames::String > String</tt>. You could do: 
+  To see how the lifting operators allow more concise code, consider a computation in the <code>Maybe</code> monad in which you want to use a function <code>swapNames::String > String</code>. You could do: 
−  <pre>getName :: String > Maybe String 
+  <haskell> 
−  getName name = do let db = [("John", "Smith, John"), ("Mike", "Caine, Michael")] 
+  getName :: String > Maybe String 
−  tempName < lookup name db 
+  getName name = do let db = [("John", "Smith, John"), ("Mike", "Caine, Michael")] 
−  return (swapNames tempName)</pre> 
+  tempName < lookup name db 
−  But making use of the <tt>liftM</tt> function, we can use <tt>liftM swapNames</tt> as a function of type <tt>Maybe String > Maybe String</tt>: 
+  return (swapNames tempName) 
+  </haskell> 

+  But making use of the <code>liftM</code> function, we can use <code>liftM swapNames</code> as a function of type <code>Maybe String > Maybe String</code>: 

Code available in [[../examples/example6.hsexample6.hs]] 
Code available in [[../examples/example6.hsexample6.hs]] 

−  <pre>getName :: String > Maybe String 
+  <haskell> 
−  getName name = do let db = [("John", "Smith, John"), ("Mike", "Caine, Michael")] 
+  getName :: String > Maybe String 
−  liftM swapNames (lookup name db)</pre> 
+  getName name = do let db = [("John", "Smith, John"), ("Mike", "Caine, Michael")] 
+  liftM swapNames (lookup name db) 

+  </haskell> 

The difference is even greater when lifting functions with more arguments. 
The difference is even greater when lifting functions with more arguments. 

−  The lifting functions also enable very concise constructions using higherorder functions. To understand this example code, you might need to review the definition of the monad functions for the [[listmonad.html#definitionList monad]] (particularly <tt>>>=</tt>). Imagine how you might implement this function without lifting the operator: 
+  The lifting functions also enable very concise constructions using higherorder functions. To understand this example code, you might need to review the definition of the monad functions for the [[listmonad.html#definitionList monad]] (particularly <code>>>=</code>). Imagine how you might implement this function without lifting the operator: 
Code available in [[../examples/example7.hsexample7.hs]] 
Code available in [[../examples/example7.hsexample7.hs]] 

−  <pre> allCombinations returns a list containing the result of 
+  <haskell> 
+   allCombinations returns a list containing the result of 

 folding the binary operator through all combinations 
 folding the binary operator through all combinations 

 of elements of the given lists 
 of elements of the given lists 

Line 674:  Line 561:  
 and allCombinations (*) [[0,1],[1,2],[3,5]] would be 
 and allCombinations (*) [[0,1],[1,2],[3,5]] would be 

 [0*1*3,0*1*5,0*2*3,0*2*5,1*1*3,1*1*5,1*2*3,1*2*5], or [0,0,0,0,3,5,6,10] 
 [0*1*3,0*1*5,0*2*3,0*2*5,1*1*3,1*1*5,1*2*3,1*2*5], or [0,0,0,0,3,5,6,10] 

−  allCombinations :: (a > a > a) > [[a]] > [a] 
+  allCombinations :: (a > a > a) > [[a]] > [a] 
allCombinations fn [] = [] 
allCombinations fn [] = [] 

−  allCombinations fn (l:ls) = foldl (liftM2 fn) l ls</pre> 
+  allCombinations fn (l:ls) = foldl (liftM2 fn) l ls 
−  There is a related function called <tt>ap</tt> that is sometimes more convenient to use than the lifting functions. <tt>ap</tt> is simply the function application operator (<tt>$</tt>) lifted into the monad: 
+  </haskell> 
+  There is a related function called <code>ap</code> that is sometimes more convenient to use than the lifting functions. <code>ap</code> is simply the function application operator (<code>$</code>) lifted into the monad: 

−  <pre>ap :: (Monad m) => m (a > b) > m a > m b 
+  <haskell> 
−  ap = liftM2 ($)</pre> 
+  ap :: (Monad m) => m (a > b) > m a > m b 
−  Note that <tt>liftM2 f x y</tt> is equivalent to <tt>return f `ap` x `ap` y</tt>, and so on for functions of more arguments. <tt>ap</tt> is useful when working with higherorder functions and monads. 
+  ap = liftM2 ($) 
+  </haskell> 

+  Note that <code>liftM2 f x y</code> is equivalent to <code>return f `ap` x `ap` y</code>, and so on for functions of more arguments. <code>ap</code> is useful when working with higherorder functions and monads. 

−  The effect of <tt>ap</tt> depends on the strategy of the monad in which it is used. So for example <tt>[(*2),(+3)] `ap` [0,1,2]</tt> is equal to <tt>[0,2,4,3,4,5]</tt> and <tt>(Just (*2)) `ap` (Just 3)</tt> is <tt>Just 6</tt>. Here is a simple example that shows how <tt>ap</tt> can be useful when doing higherorder computations: 
+  The effect of <code>ap</code> depends on the strategy of the monad in which it is used. So for example <code>[(*2),(+3)] `ap` [0,1,2]</code> is equal to <code>[0,2,4,3,4,5]</code> and <code>(Just (*2)) `ap` (Just 3)</code> is <code>Just 6</code>. Here is a simple example that shows how <code>ap</code> can be useful when doing higherorder computations: 
Code available in [[../examples/example8.hsexample8.hs]] 
Code available in [[../examples/example8.hsexample8.hs]] 

−  <pre> lookup the commands and fold ap into the command list to 
+  <haskell> 
+   lookup the commands and fold ap into the command list to 

 compute a result. 
 compute a result. 

main :: IO () 
main :: IO () 

−  main = do let fns = [("double",(2*)), ("halve",(`div`2)), 
+  main = do let fns = [("double",(2*)), ("halve",(`div`2)), 
−  ("square",(\x>x*x)), ("negate", negate), 
+  ("square",(\x>x*x)), ("negate", negate), 
−  ("incr",(+1)), ("decr",(+(1))) 
+  ("incr",(+1)), ("decr",(+(1))) 
] 
] 

−  args < getArgs 
+  args < getArgs 
let val = read (args!!0) 
let val = read (args!!0) 

cmds = map ((flip lookup) fns) (words (args!!1)) 
cmds = map ((flip lookup) fns) (words (args!!1)) 

−  print $ foldl (flip ap) (Just val) cmds</pre> 
+  print $ foldl (flip ap) (Just val) cmds 
−  === Functions for use with <tt>MonadPlus</tt> === 
+  </haskell> 
+  === Functions for use with <code>MonadPlus</code> === 

−  There are two functions in the <tt>Monad</tt> module that are used with monads that have a zero and a plus. The first function is <tt>msum</tt>, which is analogous to the <tt>sum</tt> function on lists of integers. <tt>msum</tt> operates on lists of monadic values and folds the <tt>mplus</tt> operator into the list using the <tt>mzero</tt> element as the initial value: 
+  There are two functions in the <code>Monad</code> module that are used with monads that have a zero and a plus. The first function is <code>msum</code>, which is analogous to the <code>sum</code> function on lists of integers. <code>msum</code> operates on lists of monadic values and folds the <code>mplus</code> operator into the list using the <code>mzero</code> element as the initial value: 
−  <pre>msum :: MonadPlus m => [m a] > m a 
+  <haskell> 
−  msum xs = foldr mplus mzero xs</pre> 
+  msum :: MonadPlus m => [m a] > m a 
−  In the List monad, <tt>msum</tt> is equivalent to <tt>concat</tt>. In the <tt>Maybe</tt> monad, <tt>msum</tt> returns the first non<tt>Nothing</tt> value from a list. Likewise, the behavior in other monads will depend on the exact nature of their <tt>mzero</tt> and <tt>mplus</tt> definitions. 
+  msum xs = foldr mplus mzero xs 
+  </haskell> 

+  In the List monad, <code>msum</code> is equivalent to <code>concat</code>. In the <code>Maybe</code> monad, <code>msum</code> returns the first non<code>Nothing</code> value from a list. Likewise, the behavior in other monads will depend on the exact nature of their <code>mzero</code> and <code>mplus</code> definitions. 

−  <tt>msum</tt> allows many recursive functions and folds to be expressed more concisely. In the <tt>Maybe</tt> monad, for example, we can write: 
+  <code>msum</code> allows many recursive functions and folds to be expressed more concisely. In the <code>Maybe</code> monad, for example, we can write: 
Code available in [[../examples/example9.hsexample9.hs]] 
Code available in [[../examples/example9.hsexample9.hs]] 

−  <pre>type Variable = String 
+  <haskell> 
+  type Variable = String 

type Value = String 
type Value = String 

type EnvironmentStack = [[(Variable,Value)]] 
type EnvironmentStack = [[(Variable,Value)]] 

Line 716:  Line 603:  
 lookupVar retrieves a variable's value from the environment stack 
 lookupVar retrieves a variable's value from the environment stack 

 It uses msum in the Maybe monad to return the first nonNothing value. 
 It uses msum in the Maybe monad to return the first nonNothing value. 

−  lookupVar :: Variable > EnvironmentStack > Maybe Value 
+  lookupVar :: Variable > EnvironmentStack > Maybe Value 
−  lookupVar var stack = msum $ map (lookup var) stack</pre> 
+  lookupVar var stack = msum $ map (lookup var) stack 
+  </haskell> 

instead of: 
instead of: 

−  <pre>lookupVar :: Variable > EnvironmentStack > Maybe Value 
+  <haskell> 
+  lookupVar :: Variable > EnvironmentStack > Maybe Value 

lookupVar var [] = Nothing 
lookupVar var [] = Nothing 

lookupVar var (e:es) = let val = lookup var e 
lookupVar var (e:es) = let val = lookup var e 

−  in maybe (lookupVar var es) Just val</pre> 
+  in maybe (lookupVar var es) Just val 
−  The second function for use with monads with a zero and a plus is the <tt>guard</tt> function: 
+  </haskell> 
+  The second function for use with monads with a zero and a plus is the <code>guard</code> function: 

−  <pre>guard :: MonadPlus m => Bool > m () 
+  <haskell> 
−  guard p = if p then return () else mzero</pre> 
+  guard :: MonadPlus m => Bool > m () 
−  The trick to understanding this function is to recall the law for monads with zero and plus that states <tt>mzero >>= f == mzero</tt>. So, placing a <tt>guard</tt> function in a sequence of monadic operations will force any execution in which the guard is <tt>False</tt> to be <tt>mzero</tt>. This is similar to the way that guard predicates in a list comprehension cause values that fail the predicate to become <tt>[]</tt>. 
+  guard p = if p then return () else mzero 
+  </haskell> 

+  The trick to understanding this function is to recall the law for monads with zero and plus that states <code>mzero >>= f == mzero</code>. So, placing a <code>guard</code> function in a sequence of monadic operations will force any execution in which the guard is <code>False</code> to be <code>mzero</code>. This is similar to the way that guard predicates in a list comprehension cause values that fail the predicate to become <code>[]</code>. 

−  Here is an example demonstrating the use of the <tt>guard</tt> function in the <tt>Maybe</tt> monad. 
+  Here is an example demonstrating the use of the <code>guard</code> function in the <code>Maybe</code> monad. 
Code available in [[../examples/example10.hsexample10.hs]] 
Code available in [[../examples/example10.hsexample10.hs]] 

−  <pre>data Record = Rec {name::String, age::Int} deriving Show 
+  <haskell> 
+  data Record = Rec {name::String, age::Int} deriving Show 

type DB = [Record] 
type DB = [Record] 

Line 742:  Line 629:  
 clearer to simply use filter. When the filter criteria are more complex, 
 clearer to simply use filter. When the filter criteria are more complex, 

 guard becomes more useful. 
 guard becomes more useful. 

−  getYoungerThan :: Int > DB > [Record] 
+  getYoungerThan :: Int > DB > [Record] 
−  getYoungerThan limit db = mapMaybe (\r > do { guard (age r < limit); return r }) db</pre> 
+  getYoungerThan limit db = mapMaybe (\r > do { guard (age r < limit); return r }) db 
+  </haskell> 

== Summary == 
== Summary == 

−  Haskell provides a number of functions which are useful for working with monads in the standard libraries. The <tt>Monad</tt> class and most common monad functions are in the standard prelude. The <tt>MonadPlus</tt> class and less commonlyused (but still very useful!) functions are defined in the <tt>Monad</tt> module. Many other types in the Haskell libraries are declared as instances of <tt>Monad</tt> and <tt>MonadPlus</tt> in their respective modules. 
+  Haskell provides a number of functions which are useful for working with monads in the standard libraries. The <code>Monad</code> class and most common monad functions are in the standard prelude. The <code>MonadPlus</code> class and less commonlyused (but still very useful!) functions are defined in the <code>Monad</code> module. Many other types in the Haskell libraries are declared as instances of <code>Monad</code> and <code>MonadPlus</code> in their respective modules. 
−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[exercises.htmlExercises]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[introII.htmlPart II  Introduction]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Part II  Introduction 
Part II  Introduction 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[monadfns.htmlMonad support in Haskell]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[identitymonad.htmlThe Identity monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
−  
−   

= Introduction = 
= Introduction = 

Line 774:  Line 648:  
<th align="left">Monad</th> 
<th align="left">Monad</th> 

<th align="left">Type of computation</th> 
<th align="left">Type of computation</th> 

−  <th align="left">Combination strategy for <tt>>>=</tt></th> 
+  <th align="left">Combination strategy for <code>>>=</code></th> 
</tr> 
</tr> 

</thead> 
</thead> 

Line 786:  Line 660:  
<td align="left">[[maybemonad.htmlMaybe]]</td> 
<td align="left">[[maybemonad.htmlMaybe]]</td> 

<td align="left">Computations which may not return a result</td> 
<td align="left">Computations which may not return a result</td> 

−  <td align="left"><tt>Nothing</tt> input gives <tt>Nothing</tt> output<br /> 
+  <td align="left"><code>Nothing</code> input gives <code>Nothing</code> output<br /> 
−  <tt>Just x</tt> input uses <tt>x</tt> as input to the bound function.</td> 
+  <code>Just x</code> input uses <code>x</code> as input to the bound function.</td> 
</tr> 
</tr> 

<tr class="odd"> 
<tr class="odd"> 

Line 823:  Line 697:  
<td align="left">Computations which can be interrupted and restarted</td> 
<td align="left">Computations which can be interrupted and restarted</td> 

<td align="left">The bound function is inserted into the continuation chain.</td> 
<td align="left">The bound function is inserted into the continuation chain.</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[monadfns.htmlMonad support in Haskell]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[identitymonad.htmlThe Identity monad]]</td> 

</tr> 
</tr> 

</tbody> 
</tbody> 

Line 841:  Line 702:  
The Identity monad 
The Identity monad 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[introII.htmlPart II  Introduction]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[maybemonad.htmlThe Maybe monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The Identity monad = 
= The Identity monad = 

−  
−  * [[#overviewOverview]] 

−  * [[#motivationMotivation]] 

−  * [[#definitionDefinition]] 

−  * [[#exampleExample]] 

−  
−  
−   

== Overview == 
== Overview == 

Line 870:  Line 713:  
Binding strategy: 
Binding strategy: 

−  The bound function is applied to the input value. <tt>Identity x >>= f == Identity (f x)</tt> 
+  The bound function is applied to the input value. <code>Identity x >>= f == Identity (f x)</code> 
Useful for: 
Useful for: 

Line 890:  Line 733:  
== Definition == 
== Definition == 

−  <pre>newtype Identity a = Identity { runIdentity :: a } 
+  <haskell> 
+  newtype Identity a = Identity { runIdentity :: a } 

instance Monad Identity where 
instance Monad Identity where 

return a = Identity a  i.e. return = id 
return a = Identity a  i.e. return = id 

−  (Identity x) >>= f = f x  i.e. x >>= f = f x </pre> 
+  (Identity x) >>= f = f x  i.e. x >>= f = f x 
−  The <tt>runIdentity</tt> label is used in the type definition because it follows a style of monad definition that explicitly represents monad values as computations. In this style, a monadic computation is built up using the monadic operators and then the value of the computation is extracted using the <tt>run******</tt> function. Because the Identity monad does not do any computation, its definition is trivial. For a better example of this style of monad, see the [[statemonad.htmlState]] monad. 
+  </haskell> 
+  The <code>runIdentity</code> label is used in the type definition because it follows a style of monad definition that explicitly represents monad values as computations. In this style, a monadic computation is built up using the monadic operators and then the value of the computation is extracted using the <code>run******</code> function. Because the Identity monad does not do any computation, its definition is trivial. For a better example of this style of monad, see the [[statemonad.htmlState]] monad. 

== Example == 
== Example == 

Line 901:  Line 744:  
A typical use of the Identity monad is to derive a monad from a monad transformer. 
A typical use of the Identity monad is to derive a monad from a monad transformer. 

−  <pre> derive the State monad using the StateT monad transformer 
+  <haskell> 
−  type State s a = StateT s Identity a</pre> 
+   derive the State monad using the StateT monad transformer 
−  +  type State s a = StateT s Identity a 

−   
+  </haskell> 
−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[introII.htmlPart II  Introduction]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[maybemonad.htmlThe Maybe monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
The Maybe monad 
The Maybe monad 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[identitymonad.htmlThe Identity monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[errormonad.htmlThe Error monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The Maybe monad = 
= The Maybe monad = 

−  
−  * [[#overviewOverview]] 

−  * [[#motivationMotivation]] 

−  * [[#definitionDefinition]] 

−  * [[#exampleExample]] 

−  
−  
−   

== Overview == 
== Overview == 

Line 931:  Line 756:  
Computation type: 
Computation type: 

−  Computations which may return <tt>Nothing</tt> 
+  Computations which may return <code>Nothing</code> 
Binding strategy: 
Binding strategy: 

−  <tt>Nothing</tt> values bypass the bound function, other values are used as inputs to the bound function. 
+  <code>Nothing</code> values bypass the bound function, other values are used as inputs to the bound function. 
Useful for: 
Useful for: 

−  Building computations from sequences of functions that may return <tt>Nothing</tt>. Complex database queries or dictionary lookups are good examples. 
+  Building computations from sequences of functions that may return <code>Nothing</code>. Complex database queries or dictionary lookups are good examples. 
Zero and plus: 
Zero and plus: 

−  <tt>Nothing</tt> is the zero. The plus operation returns the first non<tt>Nothing</tt> value or <tt>Nothing</tt> is both inputs are <tt>Nothing</tt>. 
+  <code>Nothing</code> is the zero. The plus operation returns the first non<code>Nothing</code> value or <code>Nothing</code> if both inputs are <code>Nothing</code>. 
Example type: 
Example type: 

Line 951:  Line 776:  
== Motivation == 
== Motivation == 

−  The Maybe monad embodies the strategy of combining a chain of computations that may each return <tt>Nothing</tt> by ending the chain early if any step produces <tt>Nothing</tt> as output. It is useful when a computation entails a sequence of steps that depend on one another, and in which some steps may fail to return a value. 
+  The Maybe monad embodies the strategy of combining a chain of computations that may each return <code>Nothing</code> by ending the chain early if any step produces <code>Nothing</code> as output. It is useful when a computation entails a sequence of steps that depend on one another, and in which some steps may fail to return a value. 
[[Image:info.png]] If you ever find yourself writing code like this:<br /> 
[[Image:info.png]] If you ever find yourself writing code like this:<br /> 

−  <pre>case ... of 
+  <haskell> 
−  Nothing > Nothing 
+  case ... of 
−  Just x > case ... of 
+  Nothing > Nothing 
−  Nothing > Nothing 
+  Just x > case ... of 
−  Just y > ...</pre> 
+  Nothing > Nothing 
−  you should consider using the monadic properties of <tt>Maybe</tt> to improve the code. 
+  Just y > ... 
+  </haskell> 

+  you should consider using the monadic properties of <code>Maybe</code> to improve the code. 

== Definition == 
== Definition == 

−  <pre>data Maybe a = Nothing  Just a 
+  <haskell> 
+  data Maybe a = Nothing  Just a 

instance Monad Maybe where 
instance Monad Maybe where 

return = Just 
return = Just 

fail = Nothing 
fail = Nothing 

−  Nothing >>= f = Nothing 
+  Nothing >>= f = Nothing 
−  (Just x) >>= f = f x 
+  (Just x) >>= f = f x 
instance MonadPlus Maybe where 
instance MonadPlus Maybe where 

mzero = Nothing 
mzero = Nothing 

Nothing `mplus` x = x 
Nothing `mplus` x = x 

−  x `mplus` _ = x</pre> 
+  x `mplus` _ = x 
+  </haskell> 

== Example == 
== Example == 

Line 983:  Line 808:  
Code available in [[../examples/example11.hsexample11.hs]] 
Code available in [[../examples/example11.hsexample11.hs]] 

−  <pre>data MailPref = HTML  Plain 
+  <haskell> 
+  data MailPref = HTML  Plain 

data MailSystem = ... 
data MailSystem = ... 

−  getMailPrefs :: MailSystem > String > Maybe MailPref 
+  getMailPrefs :: MailSystem > String > Maybe MailPref 
getMailPrefs sys name = 
getMailPrefs sys name = 

do let nameDB = fullNameDB sys 
do let nameDB = fullNameDB sys 

nickDB = nickNameDB sys 
nickDB = nickNameDB sys 

prefDB = prefsDB sys 
prefDB = prefsDB sys 

−  addr < (lookup name nameDB) `mplus` (lookup name nickDB) 
+  addr < (lookup name nameDB) `mplus` (lookup name nickDB) 
−  lookup addr prefDB</pre> 
+  lookup addr prefDB 
−  +  </haskell> 

−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[identitymonad.htmlThe Identity monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[errormonad.htmlThe Error monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
The Error monad 
The Error monad 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[maybemonad.htmlThe Maybe monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[listmonad.htmlThe List monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The Error monad = 
= The Error monad = 

−  
−  * [[#overviewOverview]] 

−  * [[#motivationMotivation]] 

−  * [[#definitionDefinition]] 

−  * [[#exampleExample]] 

−  
−  
−   

== Overview == 
== Overview == 

Line 1,042:  Line 849:  
The Error monad (also called the Exception monad) embodies the strategy of combining computations that can throw exceptions by bypassing bound functions from the point an exception is thrown to the point that it is handled. 
The Error monad (also called the Exception monad) embodies the strategy of combining computations that can throw exceptions by bypassing bound functions from the point an exception is thrown to the point that it is handled. 

−  The [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Error.html <tt>MonadError</tt>] class is parameterized over the type of error information and the monad type constructor. It is common to use <tt>Either String</tt> as the monad type constructor for an error monad in which error descriptions take the form of strings. In that case and many other common cases the resulting monad is already defined as an instance of the <tt>MonadError</tt> class. You can also define your own error type and/or use a monad type constructor other than <tt>Either String</tt> or <tt>Either IOError</tt>. In these cases you will have to explicitly define instances of the <tt>Error</tt> and/or <tt>MonadError</tt> classes. 
+  The [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Error.html <code>MonadError</code>] class is parameterized over the type of error information and the monad type constructor. It is common to use <code>Either String</code> as the monad type constructor for an error monad in which error descriptions take the form of strings. In that case and many other common cases the resulting monad is already defined as an instance of the <code>MonadError</code> class. You can also define your own error type and/or use a monad type constructor other than <code>Either String</code> or <code>Either IOError</code>. In these cases you will have to explicitly define instances of the <code>Error</code> and/or <code>MonadError</code> classes. 
== Definition == 
== Definition == 

−  The definition of the <tt>MonadError</tt> class below uses multiparameter type classes and funDeps, which are language extensions not found in standard Haskell 98. You don't need to understand them to take advantage of the <tt>MonadError</tt> class. 
+  The definition of the <code>MonadError</code> class below uses multiparameter type classes and funDeps, which are language extensions not found in standard Haskell 98. You don't need to understand them to take advantage of the <code>MonadError</code> class. 
−  <pre>class Error a where 
+  <haskell> 
+  class Error a where 

noMsg :: a 
noMsg :: a 

−  strMsg :: String > a 
+  strMsg :: String > a 
−  class (Monad m) => MonadError e m  m > e where 
+  class (Monad m) => MonadError e m  m > e where 
−  throwError :: e > m a 
+  throwError :: e > m a 
−  catchError :: m a > (e > m a) > m a</pre> 
+  catchError :: m a > (e > m a) > m a 
−  <tt>throwError</tt> is used within a monadic computation to begin exception processing. <tt>catchError</tt> provides a handler function to handle previous errors and return to normal execution. A common idiom is: 
+  </haskell> 
+  <code>throwError</code> is used within a monadic computation to begin exception processing. <code>catchError</code> provides a handler function to handle previous errors and return to normal execution. A common idiom is: 

−  <pre>do { action1; action2; action3 } `catchError` handler </pre> 
+  <haskell> 
−  where the <tt>action</tt> functions can call <tt>throwError</tt>. Note that <tt>handler</tt> and the doblock must have the same return type. 
+  do { action1; action2; action3 } `catchError` handler 
+  </haskell> 

+  where the <code>action</code> functions can call <code>throwError</code>. Note that <code>handler</code> and the doblock must have the same return type. 

−  The definition of the <tt>Either e</tt> type constructor as an instance of the <tt>MonadError</tt> class is straightforward. Following convention, <tt>Left</tt> is used for error values and <tt>Right</tt> is used for nonerror (right) values. 
+  The definition of the <code>Either e</code> type constructor as an instance of the <code>MonadError</code> class is straightforward. Following convention, <code>Left</code> is used for error values and <code>Right</code> is used for nonerror (right) values. 
−  <pre>instance MonadError (Either e) where 
+  <haskell> 
+  instance MonadError (Either e) where 

throwError = Left 
throwError = Left 

(Left e) `catchError` handler = handler e 
(Left e) `catchError` handler = handler e 

−  a `catchError` _ = a </pre> 
+  a `catchError` _ = a 
+  </haskell> 

== Example == 
== Example == 

−  Here is an example that demonstrates the use of a custom <tt>Error</tt> data type with the <tt>ErrorMonad</tt>'s <tt>throwError</tt> and <tt>catchError</tt> exception mechanism. The example attempts to parse hexadecimal numbers and throws an exception if an invalid character is encountered. We use a custom <tt>Error</tt> data type to record the location of the parse error. The exception is caught by a calling function and handled by printing an informative error message. 
+  Here is an example that demonstrates the use of a custom <code>Error</code> data type with the <code>ErrorMonad</code>'s <code>throwError</code> and <code>catchError</code> exception mechanism. The example attempts to parse hexadecimal numbers and throws an exception if an invalid character is encountered. We use a custom <code>Error</code> data type to record the location of the parse error. The exception is caught by a calling function and handled by printing an informative error message. 
Code available in [[../examples/example12.hsexample12.hs]] 
Code available in [[../examples/example12.hsexample12.hs]] 

−  <pre> This is the type of our parse error representation. 
+  <haskell> 
+   This is the type of our parse error representation. 

data ParseError = Err {location::Int, reason::String} 
data ParseError = Err {location::Int, reason::String} 

 We make it an instance of the Error class 
 We make it an instance of the Error class 

instance Error ParseError where 
instance Error ParseError where 

−  noMsg = Err 0 "Parse Error" 
+  noMsg = Err 0 "Parse Error" 
strMsg s = Err 0 s 
strMsg s = Err 0 s 

Line 1,090:  Line 897:  
 an Integer in the ParseMonad monad and throws an error on an 
 an Integer in the ParseMonad monad and throws an error on an 

 invalid character 
 invalid character 

−  parseHexDigit :: Char > Int > ParseMonad Integer 
+  parseHexDigit :: Char > Int > ParseMonad Integer 
parseHexDigit c idx = if isHexDigit c then 
parseHexDigit c idx = if isHexDigit c then 

return (toInteger (digitToInt c)) 
return (toInteger (digitToInt c)) 

else 
else 

−  throwError (Err idx ("Invalid character '" ++ [c] ++ "'")) 
+  throwError (Err idx ("Invalid character '" ++ [c] ++ "'")) 
 parseHex parses a string containing a hexadecimal number into 
 parseHex parses a string containing a hexadecimal number into 

 an Integer in the ParseMonad monad. A parse error from parseHexDigit 
 an Integer in the ParseMonad monad. A parse error from parseHexDigit 

 will cause an exceptional return from parseHex. 
 will cause an exceptional return from parseHex. 

−  parseHex :: String > ParseMonad Integer 
+  parseHex :: String > ParseMonad Integer 
parseHex s = parseHex' s 0 1 
parseHex s = parseHex' s 0 1 

where parseHex' [] val _ = return val 
where parseHex' [] val _ = return val 

−  parseHex' (c:cs) val idx = do d < parseHexDigit c idx 
+  parseHex' (c:cs) val idx = do d < parseHexDigit c idx 
parseHex' cs ((val * 16) + d) (idx + 1) 
parseHex' cs ((val * 16) + d) (idx + 1) 

 toString converts an Integer into a String in the ParseMonad monad 
 toString converts an Integer into a String in the ParseMonad monad 

−  toString :: Integer > ParseMonad String 
+  toString :: Integer > ParseMonad String 
toString n = return $ show n 
toString n = return $ show n 

Line 1,113:  Line 920:  
 number. A parse error on the input String will generate a 
 number. A parse error on the input String will generate a 

 descriptive error message as the output String. 
 descriptive error message as the output String. 

−  convert :: String > String 
+  convert :: String > String 
−  convert s = let (Right str) = do {n < parseHex s; toString n} `catchError` printError 
+  convert s = let (Right str) = do {n < parseHex s; toString n} `catchError` printError 
in str 
in str 

−  where printError e = return $ "At index " ++ (show (location e)) ++ ":" ++ (reason e)</pre> 
+  where printError e = return $ "At index " ++ (show (location e)) ++ ":" ++ (reason e) 
−  +  </haskell> 

−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[maybemonad.htmlThe Maybe monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[listmonad.htmlThe List monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
The List monad 
The List monad 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[errormonad.htmlThe Error monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[iomonad.htmlThe IO monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The List monad = 
= The List monad = 

−  
−  * [[#overviewOverview]] 

−  * [[#motivationMotivation]] 

−  * [[#definitionDefinition]] 

−  * [[#exampleExample]] 

−  
−  
−   

== Overview == 
== Overview == 

Line 1,156:  Line 945:  
Zero and plus: 
Zero and plus: 

−  <tt>[]</tt> is the zero and <tt>++</tt> is the plus operation. 
+  <code>[]</code> is the zero and <code>++</code> is the plus operation. 
Example type: 
Example type: 

−  <tt>[a]</tt> 
+  <code>[a]</code> 
== Motivation == 
== Motivation == 

Line 1,168:  Line 957:  
== Definition == 
== Definition == 

−  <pre>instance Monad [] where 
+  <haskell> 
−  m >>= f = concatMap f m 
+  instance Monad [] where 
+  m >>= f = concatMap f m 

return x = [x] 
return x = [x] 

fail s = [] 
fail s = [] 

Line 1,175:  Line 964:  
instance MonadPlus [] where 
instance MonadPlus [] where 

mzero = [] 
mzero = [] 

−  mplus = (++)</pre> 
+  mplus = (++) 
+  </haskell> 

== Example == 
== Example == 

Line 1,182:  Line 971:  
Code available in [[../examples/example13.hsexample13.hs]] 
Code available in [[../examples/example13.hsexample13.hs]] 

−  <pre> we can parse three different types of terms 
+  <haskell> 
+   we can parse three different types of terms 

data Parsed = Digit Integer  Hex Integer  Word String deriving Show 
data Parsed = Digit Integer  Hex Integer  Word String deriving Show 

 attempts to add a character to the parsed representation of a hex digit 
 attempts to add a character to the parsed representation of a hex digit 

−  parseHexDigit :: Parsed > Char > [Parsed] 
+  parseHexDigit :: Parsed > Char > [Parsed] 
parseHexDigit (Hex n) c = if isHexDigit c then 
parseHexDigit (Hex n) c = if isHexDigit c then 

return (Hex ((n*16) + (toInteger (digitToInt c)))) 
return (Hex ((n*16) + (toInteger (digitToInt c)))) 

Line 1,194:  Line 983:  
 attempts to add a character to the parsed representation of a decimal digit 
 attempts to add a character to the parsed representation of a decimal digit 

−  parseDigit :: Parsed > Char > [Parsed] 
+  parseDigit :: Parsed > Char > [Parsed] 
parseDigit (Digit n) c = if isDigit c then 
parseDigit (Digit n) c = if isDigit c then 

return (Digit ((n*10) + (toInteger (digitToInt c)))) 
return (Digit ((n*10) + (toInteger (digitToInt c)))) 

Line 1,202:  Line 991:  
 attempts to add a character to the parsed representation of a word 
 attempts to add a character to the parsed representation of a word 

−  parseWord :: Parsed > Char > [Parsed] 
+  parseWord :: Parsed > Char > [Parsed] 
parseWord (Word s) c = if isAlpha c then 
parseWord (Word s) c = if isAlpha c then 

return (Word (s ++ [c])) 
return (Word (s ++ [c])) 

Line 1,211:  Line 1,000:  
 tries to parse the digit as a hex value, a decimal value and a word 
 tries to parse the digit as a hex value, a decimal value and a word 

 the result is a list of possible parses 
 the result is a list of possible parses 

−  parse :: Parsed > Char > [Parsed] 
+  parse :: Parsed > Char > [Parsed] 
parse p c = (parseHexDigit p c) `mplus` (parseDigit p c) `mplus` (parseWord p c) 
parse p c = (parseHexDigit p c) `mplus` (parseDigit p c) `mplus` (parseWord p c) 

 parse an entire String and return a list of the possible parsed values 
 parse an entire String and return a list of the possible parsed values 

−  parseArg :: String > [Parsed] 
+  parseArg :: String > [Parsed] 
−  parseArg s = do init < (return (Hex 0)) `mplus` (return (Digit 0)) `mplus` (return (Word "")) 
+  parseArg s = do init < (return (Hex 0)) `mplus` (return (Digit 0)) `mplus` (return (Word "")) 
−  foldM parse init s</pre> 
+  foldM parse init s 
−  +  </haskell> 

−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[errormonad.htmlThe Error monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[iomonad.htmlThe IO monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
The IO monad 
The IO monad 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[listmonad.htmlThe List monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[statemonad.htmlThe State monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The IO monad = 
= The IO monad = 

−  
−  * [[#overviewOverview]] 

−  * [[#motivationMotivation]] 

−  * [[#definitionDefinition]] 

−  * [[#exampleExample]] 

−  
−  
−   

== Overview == 
== Overview == 

Line 1,273:  Line 1,044:  
Throughout this tutorial, we have referred to monadic values as computations. However, values in the IO monad are often called I/O actions and we will use that terminology here. 
Throughout this tutorial, we have referred to monadic values as computations. However, values in the IO monad are often called I/O actions and we will use that terminology here. 

−  In Haskell, the toplevel <tt>main</tt> function must have type <tt>IO ()</tt>, so that programs are typically structured at the top level as an imperativestyle sequence of I/O actions and calls to functionalstyle code. The functions exported from the <tt>IO</tt> module do not perform I/O themselves. They return I/O actions, which describe an I/O operation to be performed. The I/O actions are combined within the IO monad (in a purely functional manner) to create more complex I/O actions, resulting in the final I/O action that is the <tt>main</tt> value of the program. 
+  In Haskell, the toplevel <code>main</code> function must have type <code>IO ()</code>, so that programs are typically structured at the top level as an imperativestyle sequence of I/O actions and calls to functionalstyle code. The functions exported from the <code>IO</code> module do not perform I/O themselves. They return I/O actions, which describe an I/O operation to be performed. The I/O actions are combined within the IO monad (in a purely functional manner) to create more complex I/O actions, resulting in the final I/O action that is the <code>main</code> value of the program. 
−  The standard prelude and the [http://www.haskell.org/onlinelibrary/io.html <tt>IO</tt> module] define many functions that can be used within the IO monad and any Haskell programmer will undoubtedly be familiar with some of them. This tutorial will only discuss the monadic aspects of the IO monad, not the full range of functions available to perform I/O. 
+  The standard prelude and the [http://www.haskell.org/onlinelibrary/io.html <code>IO</code> module] define many functions that can be used within the IO monad and any Haskell programmer will undoubtedly be familiar with some of them. This tutorial will only discuss the monadic aspects of the IO monad, not the full range of functions available to perform I/O. 
−  The <tt>IO</tt> type constructor is a member of the <tt>Monad</tt> class and the <tt>MonadError</tt> class, where errors are of the type <tt>IOError</tt>. <tt>fail</tt> is defined to throw an error built from the string argument. Within the <tt>IO</tt> monad you can use the exception mechanisms from the <tt>Control.Monad.Error</tt> module in the Monad Template Library if you import the module. The same mechanisms have alternative names exported by the <tt>IO</tt> module: <tt>ioError</tt> and <tt>catch</tt>. 
+  The <code>IO</code> type constructor is a member of the <code>Monad</code> class and the <code>MonadError</code> class, where errors are of the type <code>IOError</code>. <code>fail</code> is defined to throw an error built from the string argument. Within the <code>IO</code> monad you can use the exception mechanisms from the <code>Control.Monad.Error</code> module in the Monad Template Library if you import the module. The same mechanisms have alternative names exported by the <code>IO</code> module: <code>ioError</code> and <code>catch</code>. 
−  <pre>instance Monad IO where 
+  <haskell> 
−  return a = ...  function from a > IO a 
+  instance Monad IO where 
−  m >>= k = ...  executes the I/O action m and binds the value to k's input 
+  return a = ...  function from a > IO a 
+  m >>= k = ...  executes the I/O action m and binds the value to k's input 

fail s = ioError (userError s) 
fail s = ioError (userError s) 

data IOError = ... 
data IOError = ... 

−  ioError :: IOError > IO a 
+  ioError :: IOError > IO a 
ioError = ... 
ioError = ... 

−  userError :: String > IOError 
+  userError :: String > IOError 
userError = ... 
userError = ... 

−  catch :: IO a > (IOError > IO a) > IO a 
+  catch :: IO a > (IOError > IO a) > IO a 
catch = ... 
catch = ... 

−  try :: IO a > IO (Either IOError a) 
+  try :: IO a > IO (Either IOError a) 
−  try f = catch (do r < f 
+  try f = catch (do r < f 
return (Right r)) 
return (Right r)) 

−  (return . Left)</pre> 
+  (return . Left) 
−  The <tt>IO</tt> monad is incorporated into the Monad Template Library framework as an instance of the <tt>MonadError</tt> class. 
+  </haskell> 
+  The <code>IO</code> monad is incorporated into the Monad Template Library framework as an instance of the <code>MonadError</code> class. 

−  <pre>instance Error IOError where 
+  <haskell> 
+  instance Error IOError where 

... 
... 

instance MonadError IO where 
instance MonadError IO where 

throwError = ioError 
throwError = ioError 

−  catchError = catch</pre> 
+  catchError = catch 
−  The <tt>IO</tt> module exports a convenience function called <tt>try</tt> that executes an I/O action and returns <tt>Right result</tt> if the action succeeded or <tt>Left IOError</tt> if an I/O error was caught. 
+  </haskell> 
+  The <code>IO</code> module exports a convenience function called <code>try</code> that executes an I/O action and returns <code>Right result</code> if the action succeeded or <code>Left IOError</code> if an I/O error was caught. 

== Example == 
== Example == 

−  This example shows a partial implementation of the "tr" command that copies the standard input stream to the standard output stream with character translations controlled by commandline arguments. It demonstrates the use of the exception handling mechanisms of the <tt>MonadError</tt> class with the <tt>IO</tt> monad. 
+  This example shows a partial implementation of the "tr" command that copies the standard input stream to the standard output stream with character translations controlled by commandline arguments. It demonstrates the use of the exception handling mechanisms of the <code>MonadError</code> class with the <code>IO</code> monad. 
Code available in [[../examples/example14.hsexample14.hs]] 
Code available in [[../examples/example14.hsexample14.hs]] 

−  <pre>import Monad 
+  <haskell> 
+  import Monad 

import System 
import System 

import IO 
import IO 

Line 1,321:  Line 1,092:  
 translate char in set1 to corresponding char in set2 
 translate char in set1 to corresponding char in set2 

−  translate :: String > String > Char > Char 
+  translate :: String > String > Char > Char 
translate [] _ c = c 
translate [] _ c = c 

translate (x:xs) [] c = if x == c then ' ' else translate xs [] c 
translate (x:xs) [] c = if x == c then ' ' else translate xs [] c 

Line 1,328:  Line 1,099:  
 translate an entire string 
 translate an entire string 

−  translateString :: String > String > String > String 
+  translateString :: String > String > String > String 
translateString set1 set2 str = map (translate set1 set2) str 
translateString set1 set2 str = map (translate set1 set2) str 

−  usage :: IOError > IO () 
+  usage :: IOError > IO () 
−  usage e = do putStrLn "Usage: ex14 set1 set2" 
+  usage e = do putStrLn "Usage: ex14 set1 set2" 
−  putStrLn "Translates characters in set1 on stdin to the corresponding" 
+  putStrLn "Translates characters in set1 on stdin to the corresponding" 
−  putStrLn "characters from set2 and writes the translation to stdout." 
+  putStrLn "characters from set2 and writes the translation to stdout." 
 translates stdin to stdout based on commandline arguments 
 translates stdin to stdout based on commandline arguments 

main :: IO () 
main :: IO () 

−  main = (do [set1,set2] < getArgs 
+  main = (do [set1,set2] < getArgs 
−  contents < hGetContents stdin 
+  contents < hGetContents stdin 
putStr $ translateString set1 set2 contents) 
putStr $ translateString set1 set2 contents) 

−  `catchError` usage</pre> 
+  `catchError` usage 
−  +  </haskell> 

−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[listmonad.htmlThe List monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[statemonad.htmlThe State monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
The State monad 
The State monad 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[iomonad.htmlThe IO monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[readermonad.htmlThe Reader monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The State monad = 
= The State monad = 

−  
−  * [[#overviewOverview]] 

−  * [[#motivationMotivation]] 

−  * [[#definitionDefinition]] 

−  * [[#exampleExample]] 

−  
−  
−   

== Overview == 
== Overview == 

Line 1,391:  Line 1,144:  
A pure functional language cannot update values in place because it violates referential transparency. A common idiom to simulate such stateful computations is to "thread" a state parameter through a sequence of functions: 
A pure functional language cannot update values in place because it violates referential transparency. A common idiom to simulate such stateful computations is to "thread" a state parameter through a sequence of functions: 

−  <pre>data MyType = MT Int Bool Char Int deriving Show 
+  <haskell> 
+  data MyType = MT Int Bool Char Int deriving Show 

−  makeRandomValue :: StdGen > (MyType, StdGen) 
+  makeRandomValue :: StdGen > (MyType, StdGen) 
makeRandomValue g = let (n,g1) = randomR (1,100) g 
makeRandomValue g = let (n,g1) = randomR (1,100) g 

(b,g2) = random g1 
(b,g2) = random g1 

(c,g3) = randomR ('a','z') g2 
(c,g3) = randomR ('a','z') g2 

(m,g4) = randomR (n,n) g3 
(m,g4) = randomR (n,n) g3 

−  in (MT n b c m, g4)</pre> 
+  in (MT n b c m, g4) 
+  </haskell> 

This approach works, but such code can be errorprone, messy and difficult to maintain. The State monad hides the threading of the state parameter inside the binding operation, simultaneously making the code easier to write, easier to read and easier to modify. 
This approach works, but such code can be errorprone, messy and difficult to maintain. The State monad hides the threading of the state parameter inside the binding operation, simultaneously making the code easier to write, easier to read and easier to modify. 

Line 1,405:  Line 1,158:  
The definition shown here uses multiparameter type classes and funDeps, which are not standard Haskell 98. It is not necessary to fully understand these details to make use of the State monad. 
The definition shown here uses multiparameter type classes and funDeps, which are not standard Haskell 98. It is not necessary to fully understand these details to make use of the State monad. 

−  <pre>newtype State s a = State { runState :: (s > (a,s)) } 
+  <haskell> 
+  newtype State s a = State { runState :: (s > (a,s)) } 

instance Monad (State s) where 
instance Monad (State s) where 

−  return a = State $ \s > (a,s) 
+  return a = State $ \s > (a,s) 
−  (State x) >>= f = State $ \s > let (v,s') = x s in runState (f v) s' </pre> 
+  (State x) >>= f = State $ \s > let (v,s') = x s in runState (f v) s' 
−  Values in the State monad are represented as transition functions from an initial state to a (value,newState) pair and a new type definition is provided to describe this construct: <tt>State s a</tt> is the type of a value of type <tt>a</tt> inside the State monad with state of type <tt>s</tt>. 
+  </haskell> 
+  Values in the State monad are represented as transition functions from an initial state to a (value,newState) pair and a new type definition is provided to describe this construct: <code>State s a</code> is the type of a value of type <code>a</code> inside the State monad with state of type <code>s</code>. 

−  The type constructor <tt>State s</tt> is an instance of the <tt>Monad</tt> class. The <tt>return</tt> function simply creates a state transition function which sets the value but leaves the state unchanged. The binding operator creates a state transition function that applies its righthand argument to the value and new state from its lefthand argument. 
+  The type constructor <code>State s</code> is an instance of the <code>Monad</code> class. The <code>return</code> function simply creates a state transition function which sets the value but leaves the state unchanged. The binding operator creates a state transition function that applies its righthand argument to the value and new state from its lefthand argument. 
−  <pre>class MonadState m s  m > s where 
+  <haskell> 
+  class MonadState m s  m > s where 

get :: m s 
get :: m s 

−  put :: s > m () 
+  put :: s > m () 
instance MonadState (State s) s where 
instance MonadState (State s) s where 

−  get = State $ \s > (s,s) 
+  get = State $ \s > (s,s) 
−  put s = State $ \_ > ((),s) </pre> 
+  put s = State $ \_ > ((),s) 
−  The <tt>MonadState</tt> class provides a standard but very simple interface for State monads. The <tt>get</tt> function retrieves the state by copying it as the value. The <tt>put</tt> function sets the state of the monad and does not yield a value. 
+  </haskell> 
+  The <code>MonadState</code> class provides a standard but very simple interface for State monads. The <code>get</code> function retrieves the state by copying it as the value. The <code>put</code> function sets the state of the monad and does not yield a value. 

−  There are many additional functions provide which perform more complex computations built on top of <tt>get</tt> and put. The most useful one is <tt>gets</tt> which retrieves a function of the state. The others are listed in the [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.State.html documentation] for the State monad library. 
+  There are many additional functions provide which perform more complex computations built on top of <code>get</code> and put. The most useful one is <code>gets</code> which retrieves a function of the state. The others are listed in the [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.State.html documentation] for the State monad library. 
== Example == 
== Example == 

Line 1,431:  Line 1,184:  
Code available in [[../examples/example15.hsexample15.hs]] 
Code available in [[../examples/example15.hsexample15.hs]] 

−  <pre>data MyType = MT Int Bool Char Int deriving Show 
+  <haskell> 
+  data MyType = MT Int Bool Char Int deriving Show 

{ Using the State monad, we can define a function that returns 
{ Using the State monad, we can define a function that returns 

Line 1,437:  Line 1,190:  
the same time. 
the same time. 

} 
} 

−  getAny :: (Random a) => State StdGen a 
+  getAny :: (Random a) => State StdGen a 
−  getAny = do g < get 
+  getAny = do g < get 
−  (x,g') < return $ random g 
+  (x,g') < return $ random g 
put g' 
put g' 

return x 
return x 

 similar to getAny, but it bounds the random value returned 
 similar to getAny, but it bounds the random value returned 

−  getOne :: (Random a) => (a,a) > State StdGen a 
+  getOne :: (Random a) => (a,a) > State StdGen a 
−  getOne bounds = do g < get 
+  getOne bounds = do g < get 
−  (x,g') < return $ randomR bounds g 
+  (x,g') < return $ randomR bounds g 
put g' 
put g' 

return x 
return x 

Line 1,454:  Line 1,207:  
random generator states through the code. 
random generator states through the code. 

} 
} 

−  makeRandomValueST :: StdGen > (MyType, StdGen) 
+  makeRandomValueST :: StdGen > (MyType, StdGen) 
−  makeRandomValueST = runState (do n < getOne (1,100) 
+  makeRandomValueST = runState (do n < getOne (1,100) 
−  b < getAny 
+  b < getAny 
−  c < getOne ('a','z') 
+  c < getOne ('a','z') 
−  m < getOne (n,n) 
+  m < getOne (n,n) 
−  return (MT n b c m))</pre> 
+  return (MT n b c m)) 
−  +  </haskell> 

−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[iomonad.htmlThe IO monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[readermonad.htmlThe Reader monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
The Reader monad 
The Reader monad 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[statemonad.htmlThe State monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[writermonad.htmlThe Writer monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The Reader monad = 
= The Reader monad = 

−  
−  * [[#overviewOverview]] 

−  * [[#motivationMotivation]] 

−  * [[#definitionDefinition]] 

−  * [[#exampleExample]] 

−  
−  
−   

== Overview == 
== Overview == 

Line 1,515:  Line 1,250:  
The definition shown here uses multiparameter type classes and funDeps, which are not standard Haskell 98. It is not necessary to fully understand these details to make use of the Reader monad. 
The definition shown here uses multiparameter type classes and funDeps, which are not standard Haskell 98. It is not necessary to fully understand these details to make use of the Reader monad. 

−  <pre>newtype Reader e a = Reader { runReader :: (e > a) } 
+  <haskell> 
+  newtype Reader e a = Reader { runReader :: (e > a) } 

instance Monad (Reader e) where 
instance Monad (Reader e) where 

−  return a = Reader $ \e > a 
+  return a = Reader $ \e > a 
−  (Reader r) >>= f = Reader $ \e > f (r e) e </pre> 
+  (Reader r) >>= f = Reader $ \e > f (r e) e 
−  Values in the Reader monad are functions from an environment to a value. To extract the final value from a computation in the Reader monad, you simply apply <tt>(runReader reader)</tt> to an environment value. 
+  </haskell> 
+  Values in the Reader monad are functions from an environment to a value. To extract the final value from a computation in the Reader monad, you simply apply <code>(runReader reader)</code> to an environment value. 

−  The <tt>return</tt> function creates a <tt>Reader</tt> that ignores the environment and produces the given value. The binding operator produces a <tt>Reader</tt> that uses the environment to extract the value its lefthand side and then applies the bound function to that value in the same environment. 
+  The <code>return</code> function creates a <code>Reader</code> that ignores the environment and produces the given value. The binding operator produces a <code>Reader</code> that uses the environment to extract the value its lefthand side and then applies the bound function to that value in the same environment. 
−  <pre>class MonadReader e m  m > e where 
+  <haskell> 
+  class MonadReader e m  m > e where 

ask :: m e 
ask :: m e 

−  local :: (e > e) > m a > m a 
+  local :: (e > e) > m a > m a 
instance MonadReader (Reader e) where 
instance MonadReader (Reader e) where 

ask = Reader id 
ask = Reader id 

−  local f c = Reader $ \e > runReader c (f e) 
+  local f c = Reader $ \e > runReader c (f e) 
−  asks :: (MonadReader e m) => (e > a) > m a 
+  asks :: (MonadReader e m) => (e > a) > m a 
−  asks sel = ask >>= return . sel</pre> 
+  asks sel = ask >>= return . sel 
−  The <tt>MonadReader</tt> class provides a number of convenience functions that are very useful when working with a Reader monad. The <tt>ask</tt> function retrieves the environment and the <tt>local</tt> function executes a computation in a modified environment. The <tt>asks</tt> function is a convenience function that retrieves a function of the current environment, and is typically used with a selector or lookup function. 
+  </haskell> 
+  The <code>MonadReader</code> class provides a number of convenience functions that are very useful when working with a Reader monad. The <code>ask</code> function retrieves the environment and the <code>local</code> function executes a computation in a modified environment. The <code>asks</code> function is a convenience function that retrieves a function of the current environment, and is typically used with a selector or lookup function. 

== Example == 
== Example == 

−  Consider the problem of instantiating templates which contain variable substitutions and included templates. Using the Reader monad, we can maintain an environment of all known templates and all known variable bindings. Then, when a variable substitution is encountered, we can use the <tt>asks</tt> function to lookup the value of the variable. When a template is included with new variable definitions, we can use the <tt>local</tt> function to resolve the template in a modified environment that contains the additional variable bindings. 
+  Consider the problem of instantiating templates which contain variable substitutions and included templates. Using the Reader monad, we can maintain an environment of all known templates and all known variable bindings. Then, when a variable substitution is encountered, we can use the <code>asks</code> function to lookup the value of the variable. When a template is included with new variable definitions, we can use the <code>local</code> function to resolve the template in a modified environment that contains the additional variable bindings. 
Code available in [[../examples/example16.hsexample16.hs]] 
Code available in [[../examples/example16.hsexample16.hs]] 

−  <pre> This the abstract syntax representation of a template 
+  <haskell> 
+   This the abstract syntax representation of a template 

 Text Variable Quote Include Compound 
 Text Variable Quote Include Compound 

data Template = T String  V Template  Q Template  I Template [Definition]  C [Template] 
data Template = T String  V Template  Q Template  I Template [Definition]  C [Template] 

Line 1,553:  Line 1,288:  
 lookup a variable from the environment 
 lookup a variable from the environment 

−  lookupVar :: String > Environment > Maybe String 
+  lookupVar :: String > Environment > Maybe String 
lookupVar name env = lookup name (variables env) 
lookupVar name env = lookup name (variables env) 

 lookup a template from the environment 
 lookup a template from the environment 

−  lookupTemplate :: String > Environment > Maybe Template 
+  lookupTemplate :: String > Environment > Maybe Template 
lookupTemplate name env = lookup name (templates env) 
lookupTemplate name env = lookup name (templates env) 

 add a list of resolved definitions to the environment 
 add a list of resolved definitions to the environment 

−  addDefs :: [(String,String)] > Environment > Environment 
+  addDefs :: [(String,String)] > Environment > Environment 
addDefs defs env = env {variables = defs ++ (variables env)} 
addDefs defs env = env {variables = defs ++ (variables env)} 

 resolve a Definition and produce a (name,value) pair 
 resolve a Definition and produce a (name,value) pair 

−  resolveDef :: Definition > Reader Environment (String,String) 
+  resolveDef :: Definition > Reader Environment (String,String) 
−  resolveDef (D t d) = do name < resolve t 
+  resolveDef (D t d) = do name < resolve t 
−  value < resolve d 
+  value < resolve d 
return (name,value) 
return (name,value) 

 resolve a template into a string 
 resolve a template into a string 

−  resolve :: Template > Reader Environment (String) 
+  resolve :: Template > Reader Environment (String) 
resolve (T s) = return s 
resolve (T s) = return s 

−  resolve (V t) = do varName < resolve t 
+  resolve (V t) = do varName < resolve t 
−  varValue < asks (lookupVar varName) 
+  varValue < asks (lookupVar varName) 
−  return $ maybe "" id varValue 
+  return $ maybe "" id varValue 
−  resolve (Q t) = do tmplName < resolve t 
+  resolve (Q t) = do tmplName < resolve t 
−  body < asks (lookupTemplate tmplName) 
+  body < asks (lookupTemplate tmplName) 
−  return $ maybe "" show body 
+  return $ maybe "" show body 
−  resolve (I t ds) = do tmplName < resolve t 
+  resolve (I t ds) = do tmplName < resolve t 
−  body < asks (lookupTemplate tmplName) 
+  body < asks (lookupTemplate tmplName) 
case body of 
case body of 

−  Just t' > do defs < mapM resolveDef ds 
+  Just t' > do defs < mapM resolveDef ds 
local (addDefs defs) (resolve t') 
local (addDefs defs) (resolve t') 

−  Nothing > return "" 
+  Nothing > return "" 
−  resolve (C ts) = (liftM concat) (mapM resolve ts)</pre> 
+  resolve (C ts) = (liftM concat) (mapM resolve ts) 
−  To use the Reader monad to resolve a template <tt>t</tt> into a <tt>String</tt>, you simply need to do <tt>runReader (resolve t) env</tt>. 
+  </haskell> 
−  +  To use the Reader monad to resolve a template <code>t</code> into a <code>String</code>, you simply need to do <code>runReader (resolve t) env</code>. 

−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[statemonad.htmlThe State monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[writermonad.htmlThe Writer monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

The Writer monad 
The Writer monad 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[readermonad.htmlThe Reader monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[contmonad.htmlThe Continuation monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The Writer monad = 
= The Writer monad = 

−  
−  * [[#overviewOverview]] 

−  * [[#motivationMotivation]] 

−  * [[#definitionDefinition]] 

−  * [[#exampleExample]] 

−  
−  
−   

== Overview == 
== Overview == 

Line 1,643:  Line 1,360:  
The definition shown here uses multiparameter type classes and funDeps, which are not standard Haskell 98. It is not necessary to fully understand these details to make use of the Writer monad. 
The definition shown here uses multiparameter type classes and funDeps, which are not standard Haskell 98. It is not necessary to fully understand these details to make use of the Writer monad. 

−  [[Image:info.png]] To fully understand this definition, you need to know about Haskell's <tt>Monoid</tt> class, which represents a mathematical structure called a monoid in the same way that the <tt>Monad</tt> class represents the monad structure. 
+  [[Image:info.png]] To fully understand this definition, you need to know about Haskell's <code>Monoid</code> class, which represents a mathematical structure called a monoid in the same way that the <code>Monad</code> class represents the monad structure. 
−  The good news is that monoids are simpler than monads. A monoid is a set of objects, a single identity element, and an associative binary operator over the set of objects. A monoid must obey some mathematical laws, such that applying the operator to any values from the set gives another value in the set, and whenever one operand of the operator is the identity element the result is equal to the other operand. You may notice that these laws are the same as the laws governing <tt>mzero</tt> and <tt>mplus</tt> for instances of <tt>MonadPlus</tt>. That is because monads with a zero and plus are monads that are also monoids! 
+  The good news is that monoids are simpler than monads. A monoid is a set of objects, a single identity element, and an associative binary operator over the set of objects. A monoid must obey some mathematical laws, such that applying the operator to any values from the set gives another value in the set, and whenever one operand of the operator is the identity element the result is equal to the other operand. You may notice that these laws are the same as the laws governing <code>mzero</code> and <code>mplus</code> for instances of <code>MonadPlus</code>. That is because monads with a zero and plus are monads that are also monoids! 
Some examples of mathematical monoids are the natural numbers with identity element 0 and binary operator for addition, and also the natural numbers with identity element 1 and binary operator for multiplication. 
Some examples of mathematical monoids are the natural numbers with identity element 0 and binary operator for addition, and also the natural numbers with identity element 1 and binary operator for multiplication. 

−  In Haskell, a monoid consists of a type, an identity element, and a binary operator. Haskell defines the <tt>Monoid</tt> class (in Data.Monoid) to provide a standard convention for working with monoids: the identity element is named <tt>mempty</tt> and the operator is named <tt>mappend</tt>. 
+  In Haskell, a monoid consists of a type, an identity element, and a binary operator. Haskell defines the <code>Monoid</code> class (in Data.Monoid) to provide a standard convention for working with monoids: the identity element is named <code>mempty</code> and the operator is named <code>mappend</code>. 
−  The most commonly used standard monoid in Haskell is the list, but functions of type <tt>(a > a)</tt> also form a monoid. 
+  The most commonly used standard monoid in Haskell is the list, but functions of type <code>(a > a)</code> also form a monoid. 
−  [[Image:warn.png]] Care should be taken when using a list as the monoid for a Writer, as there may be a performance penalty associated with the <tt>mappend</tt> operation as the output grows. In that case, a data structure that supports fast append operations would be a more appropriate choice. 
+  [[Image:warn.png]] Care should be taken when using a list as the monoid for a Writer, as there may be a performance penalty associated with the <code>mappend</code> operation as the output grows. In that case, a data structure that supports fast append operations would be a more appropriate choice. 
−  <pre>newtype Writer w a = Writer { runWriter :: (a,w) } 
+  <haskell> 
+  newtype Writer w a = Writer { runWriter :: (a,w) } 

−  instance (Monoid w) => Monad (Writer w) where 
+  instance (Monoid w) => Monad (Writer w) where 
return a = Writer (a,mempty) 
return a = Writer (a,mempty) 

−  (Writer (a,w)) >>= f = let (a',w') = runWriter $ f a in Writer (a',w `mappend` w')</pre> 
+  (Writer (a,w)) >>= f = let (a',w') = runWriter $ f a in Writer (a',w `mappend` w') 
−  The Writer monad maintains a (value,log) pair, where the log type must be a monoid. The <tt>return</tt> function simply returns the value along with an empty log. Binding executes the bound function using the current value as input, and appends any log output to the existing log. 
+  </haskell> 
+  The Writer monad maintains a (value,log) pair, where the log type must be a monoid. The <code>return</code> function simply returns the value along with an empty log. Binding executes the bound function using the current value as input, and appends any log output to the existing log. 

−  <pre>class (Monoid w, Monad m) => MonadWriter w m  m > w where 
+  <haskell> 
−  pass :: m (a,w > w) > m a 
+  class (Monoid w, Monad m) => MonadWriter w m  m > w where 
−  listen :: m a > m (a,w) 
+  pass :: m (a,w > w) > m a 
−  tell :: w > m () 
+  listen :: m a > m (a,w) 
+  tell :: w > m () 

−  instance (Monoid w) => MonadWriter (Writer w) where 
+  instance (Monoid w) => MonadWriter (Writer w) where 
pass (Writer ((a,f),w)) = Writer (a,f w) 
pass (Writer ((a,f),w)) = Writer (a,f w) 

listen (Writer (a,w)) = Writer ((a,w),w) 
listen (Writer (a,w)) = Writer ((a,w),w) 

tell s = Writer ((),s) 
tell s = Writer ((),s) 

−  listens :: (MonadWriter w m) => (w > w) > m a > m (a,w) 
+  listens :: (MonadWriter w m) => (w > w) > m a > m (a,w) 
−  listens f m = do (a,w) < m; return (a,f w) 
+  listens f m = do (a,w) < m; return (a,f w) 
−  censor :: (MonadWriter w m) => (w > w) > m a > m a 
+  censor :: (MonadWriter w m) => (w > w) > m a > m a 
−  censor f m = pass $ do a < m; return (a,f)</pre> 
+  censor f m = pass $ do a < m; return (a,f) 
−  The <tt>MonadWriter</tt> class provides a number of convenience functions for working with Writer monads. The simplest and most useful is <tt>tell</tt>, which adds one or more entries to the log. The <tt>listen</tt> function turns a Writer that returns a value <tt>a</tt> and produces output <tt>w</tt> into a Writer that produces a value <tt>(a,w)</tt> and still produces output <tt>w</tt>. This allows the computation to "listen" to the log output generated by a Writer. 
+  </haskell> 
+  The <code>MonadWriter</code> class provides a number of convenience functions for working with Writer monads. The simplest and most useful is <code>tell</code>, which adds one or more entries to the log. The <code>listen</code> function turns a Writer that returns a value <code>a</code> and produces output <code>w</code> into a Writer that produces a value <code>(a,w)</code> and still produces output <code>w</code>. This allows the computation to "listen" to the log output generated by a Writer. 

−  The <tt>pass</tt> function is slightly more complicated. It converts a Writer that produces a value <tt>(a,f)</tt> and output <tt>w</tt> into a Writer that produces a value <tt>a</tt> and output <tt>f w</tt>. This is somewhat cumbersome, so the helper function <tt>censor</tt> is normally used. The <tt>censor</tt> function takes a function and a Writer and produces a new Writer whose output is the same but whose log entry has been modified by the function. 
+  The <code>pass</code> function is slightly more complicated. It converts a Writer that produces a value <code>(a,f)</code> and output <code>w</code> into a Writer that produces a value <code>a</code> and output <code>f w</code>. This is somewhat cumbersome, so the helper function <code>censor</code> is normally used. The <code>censor</code> function takes a function and a Writer and produces a new Writer whose output is the same but whose log entry has been modified by the function. 
−  The <tt>listens</tt> function operates just like <tt>listen</tt> except that the log part of the value is modified by the supplied function. 
+  The <code>listens</code> function operates just like <code>listen</code> except that the log part of the value is modified by the supplied function. 
== Example == 
== Example == 

Line 1,689:  Line 1,406:  
Code available in [[../examples/example17.hsexample17.hs]] 
Code available in [[../examples/example17.hsexample17.hs]] 

−  <pre> this is the format of our log entries 
+  <haskell> 
+   this is the format of our log entries 

data Entry = Log {count::Int, msg::String} deriving Eq 
data Entry = Log {count::Int, msg::String} deriving Eq 

 add a message to the log 
 add a message to the log 

−  logMsg :: String > Writer [Entry] () 
+  logMsg :: String > Writer [Entry] () 
logMsg s = tell [Log 1 s] 
logMsg s = tell [Log 1 s] 

 this handles one packet 
 this handles one packet 

−  filterOne :: [Rule] > Packet > Writer [Entry] (Maybe Packet) 
+  filterOne :: [Rule] > Packet > Writer [Entry] (Maybe Packet) 
−  filterOne rules packet = do rule < return (match rules packet) 
+  filterOne rules packet = do 
−  case rule of 
+  rule < return (match rules packet) 
−  Nothing > do logMsg ("DROPPING UNMATCHED PACKET: " ++ (show packet)) 
+  case rule of 
−  return Nothing 
+  Nothing > do 
−  (Just r) > do when (logIt r) (logMsg ("MATCH: " ++ (show r) ++ " <=> " ++ (show packet))) 
+  logMsg $ "DROPPING UNMATCHED PACKET: " ++ (show packet) 
−  case r of 
+  return Nothing 
−  (Rule Accept _ _) > return (Just packet) 
+  (Just r) > do 
−  (Rule Reject _ _) > return Nothing</pre> 
+  when (logIt r) $ logMsg ("MATCH: " ++ (show r) ++ " <=> " ++ (show packet)) 
+  case r of (Rule Accept _ _) > return $ Just packet 

+  (Rule Reject _ _) > return Nothing 

+  </haskell> 

That was pretty simple, but what if we want to merge duplicate consecutive log entries? None of the existing functions allow us to modify the output from previous stages of the computation, but we can use a "delayed logging" trick to only add a log entry only after we get a new entry that doesn't match the ones before it. 
That was pretty simple, but what if we want to merge duplicate consecutive log entries? None of the existing functions allow us to modify the output from previous stages of the computation, but we can use a "delayed logging" trick to only add a log entry only after we get a new entry that doesn't match the ones before it. 

Code available in [[../examples/example17.hsexample17.hs]] 
Code available in [[../examples/example17.hsexample17.hs]] 

−  <pre> merge identical entries at the end of the log 
+  <haskell> 
+   merge identical entries at the end of the log 

 This function uses [Entry] as both the log type and the result type. 
 This function uses [Entry] as both the log type and the result type. 

 When two identical messages are merged, the result is just the message 
 When two identical messages are merged, the result is just the message 

 with an incremented count. When two different messages are merged, 
 with an incremented count. When two different messages are merged, 

 the first message is logged and the second is returned as the result. 
 the first message is logged and the second is returned as the result. 

−  mergeEntries :: [Entry] > [Entry] > Writer [Entry] [Entry] 
+  mergeEntries :: [Entry] > [Entry] > Writer [Entry] [Entry] 
mergeEntries [] x = return x 
mergeEntries [] x = return x 

mergeEntries x [] = return x 
mergeEntries x [] = return x 

Line 1,732:  Line 1,449:  
 log output is the result of folding the merge operator into the individual 
 log output is the result of folding the merge operator into the individual 

 log entries (using 'initial' as the initial log value). 
 log entries (using 'initial' as the initial log value). 

−  groupSame :: (Monoid a) => a > (a > a > Writer a a) > [b] > (b > Writer a c) > Writer a [c] 
+  groupSame :: (Monoid a) => a > (a > a > Writer a a) > [b] > (b > Writer a c) > Writer a [c] 
groupSame initial merge [] _ = do tell initial 
groupSame initial merge [] _ = do tell initial 

return [] 
return [] 

−  groupSame initial merge (x:xs) fn = do (result,output) < return (runWriter (fn x)) 
+  groupSame initial merge (x:xs) fn = do (result,output) < return (runWriter (fn x)) 
−  new < merge initial output 
+  new < merge initial output 
−  rest < groupSame new merge xs fn 
+  rest < groupSame new merge xs fn 
return (result:rest) 
return (result:rest) 

 this filters a list of packets, producing a filtered packet list and a log of 
 this filters a list of packets, producing a filtered packet list and a log of 

 the activity in which consecutive messages are merged 
 the activity in which consecutive messages are merged 

−  filterAll :: [Rule] > [Packet] > Writer [Entry] [Packet] 
+  filterAll :: [Rule] > [Packet] > Writer [Entry] [Packet] 
−  filterAll rules packets = do tell [Log 1 "STARTING PACKET FILTER"] 
+  filterAll rules packets = do tell [Log 1 "STARTING PACKET FILTER"] 
−  out < groupSame [] mergeEntries packets (filterOne rules) 
+  out < groupSame [] mergeEntries packets (filterOne rules) 
−  tell [Log 1 "STOPPING PACKET FILTER"] 
+  tell [Log 1 "STOPPING PACKET FILTER"] 
−  return (catMaybes out)</pre> 
+  return (catMaybes out) 
−  +  </haskell> 

−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[readermonad.htmlThe Reader monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[contmonad.htmlThe Continuation monad]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
The Continuation monad 
The Continuation monad 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[writermonad.htmlThe Writer monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: Part III  Introduction</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= The Continuation monad = 
= The Continuation monad = 

−  
−  * [[#overviewOverview]] 

−  * [[#motivationMotivation]] 

−  * [[#definitionDefinition]] 

−  * [[#exampleExample]] 

−  
−  
−   

== Overview == 
== Overview == 

Line 1,798:  Line 1,497:  
Before using the Continuation monad, be sure that you have a firm understanding of continuationpassing style (CPS) and that continuations represent the best solution to your particular design problem. Many algorithms which require continuations in other languages do not require them in Haskell, due to Haskell's lazy semantics. 
Before using the Continuation monad, be sure that you have a firm understanding of continuationpassing style (CPS) and that continuations represent the best solution to your particular design problem. Many algorithms which require continuations in other languages do not require them in Haskell, due to Haskell's lazy semantics. 

−  Continuations represent the ''future'' of a computation, as a function from an intermediate result to the final result. In continuationpassing style, computations are built up from sequences of nested continuations, terminated by a final continuation (often <tt>id</tt>) which produces the final result. Since continuations are functions which represent the future of a computation, manipulation of the continuation functions can achieve complex manipulations of the future of the computation, such as interrupting a computation in the middle, aborting a portion of a computation, restarting a computation and interleaving execution of computations. The Continuation monad adapts CPS to the structure of a monad. 
+  Continuations represent the ''future'' of a computation, as a function from an intermediate result to the final result. In continuationpassing style, computations are built up from sequences of nested continuations, terminated by a final continuation (often <code>id</code>) which produces the final result. Since continuations are functions which represent the future of a computation, manipulation of the continuation functions can achieve complex manipulations of the future of the computation, such as interrupting a computation in the middle, aborting a portion of a computation, restarting a computation and interleaving execution of computations. The Continuation monad adapts CPS to the structure of a monad. 
== Definition == 
== Definition == 

−  <pre>newtype Cont r a = Cont { runCont :: ((a > r) > r) }  r is the final result type of the whole computation 
+  <haskell> 
+  newtype Cont r a = Cont { runCont :: ((a > r) > r) }  r is the final result type of the whole computation 

instance Monad (Cont r) where 
instance Monad (Cont r) where 

−  return a = Cont $ \k > k a  i.e. return a = \k > k a 
+  return a = Cont $ \k > k a  i.e. return a = \k > k a 
−  (Cont c) >>= f = Cont $ \k > c (\a > runCont (f a) k)  i.e. c >>= f = \k > c (\a > f a k) </pre> 
+  (Cont c) >>= f = Cont $ \k > c (\a > runCont (f a) k)  i.e. c >>= f = \k > c (\a > f a k) 
−  The Continuation monad represents computations in continuationpassing style. <tt>Cont r a</tt> is a CPS computation that produces an intermediate result of type <tt>a</tt> within a CPS computation whose final result type is <tt>r</tt>. 
+  </haskell> 
+  The Continuation monad represents computations in continuationpassing style. <code>Cont r a</code> is a CPS computation that produces an intermediate result of type <code>a</code> within a CPS computation whose final result type is <code>r</code>. 

−  The <tt>return</tt> function simply creates a continuation which passes the value on. The <tt>>>=</tt> operator adds the bound function into the continuation chain. 
+  The <code>return</code> function simply creates a continuation which passes the value on. The <code>>>=</code> operator adds the bound function into the continuation chain. 
−  <pre>class (Monad m) => MonadCont m where 
+  <haskell> 
−  callCC :: ((a > m b) > m a) > m a 
+  class (Monad m) => MonadCont m where 
+  callCC :: ((a > m b) > m a) > m a 

instance MonadCont (Cont r) where 
instance MonadCont (Cont r) where 

−  callCC f = Cont $ \k > runCont (f (\a > Cont $ \_ > k a)) k</pre> 
+  callCC f = Cont $ \k > runCont (f (\a > Cont $ \_ > k a)) k 
−  The <tt>MonadCont</tt> class provides the <tt>callCC</tt> function, which provides an escape continuation mechanism for use with Continuation monads. Escape continuations allow you to abort the current computation and return a value immediately. They achieve a similar effect to <tt>throwError</tt> and catchError within an <tt>Error</tt> monad. 
+  </haskell> 
+  The <code>MonadCont</code> class provides the <code>callCC</code> function, which provides an escape continuation mechanism for use with Continuation monads. Escape continuations allow you to abort the current computation and return a value immediately. They achieve a similar effect to <code>throwError</code> and catchError within an <code>Error</code> monad. 

−  <tt>callCC</tt> calls a function with the current continuation as its argument (hence the name). The standard idiom used with <tt>callCC</tt> is to provide a lambdaexpression to name the continuation. Then calling the named continuation anywhere within its scope will escape from the computation, even if it is many layers deep within nested computations. 
+  <code>callCC</code> calls a function with the current continuation as its argument (hence the name). The standard idiom used with <code>callCC</code> is to provide a lambdaexpression to name the continuation. Then calling the named continuation anywhere within its scope will escape from the computation, even if it is many layers deep within nested computations. 
−  In addition to the escape mechanism provided by <tt>callCC</tt>, the Continuation monad can be used to implement other, more powerful continuation manipulations. These other mechanisms have fairly specialized uses, however — and abuse of them can easily create fiendishly obfuscated code — so they will not be covered here. 
+  In addition to the escape mechanism provided by <code>callCC</code>, the Continuation monad can be used to implement other, more powerful continuation manipulations. These other mechanisms have fairly specialized uses, however — and abuse of them can easily create fiendishly obfuscated code — so they will not be covered here. 
== Example == 
== Example == 

Line 1,828:  Line 1,527:  
Code available in [[../examples/example18.hsexample18.hs]] 
Code available in [[../examples/example18.hsexample18.hs]] 

−  <pre>{ We use the continuation monad to perform "escapes" from code blocks. 
+  <haskell> 
+  { We use the continuation monad to perform "escapes" from code blocks. 

This function implements a complicated control structure to process 
This function implements a complicated control structure to process 

numbers: 
numbers: 

Line 1,838:  Line 1,537:  
20019999 n digits of (n/2) 
20019999 n digits of (n/2) 

200001999999 (n/2) backwards none 
200001999999 (n/2) backwards none 

−  >= 2000000 sum of digits of (n/2) digits of (n/2) 
+  >= 2000000 sum of digits of (n/2) digits of (n/2) 
} 
} 

−  fun :: Int > String 
+  fun :: Int > String 
fun n = (`runCont` id) $ do 
fun n = (`runCont` id) $ do 

−  str < callCC $ \exit1 > do  define "exit1" 
+  str < callCC $ \exit1 > do  define "exit1" 
−  when (n < 10) (exit1 (show n)) 
+  when (n < 10) (exit1 (show n)) 
let ns = map digitToInt (show (n `div` 2)) 
let ns = map digitToInt (show (n `div` 2)) 

−  n' < callCC $ \exit2 > do  define "exit2" 
+  n' < callCC $ \exit2 > do  define "exit2" 
−  when ((length ns) < 3) (exit2 (length ns)) 
+  when ((length ns) < 3) (exit2 (length ns)) 
−  when ((length ns) < 5) (exit2 n) 
+  when ((length ns) < 5) (exit2 n) 
−  when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns) 
+  when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns) 
exit1 (dropWhile (=='0') ns') escape 2 levels 
exit1 (dropWhile (=='0') ns') escape 2 levels 

return $ sum ns 
return $ sum ns 

−  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
+  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
−  return $ "Answer: " ++ str</pre> 
+  return $ "Answer: " ++ str 
−  +  </haskell> 

−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[writermonad.htmlThe Writer monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: Part III  Introduction</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
Part III  Introduction 
Part III  Introduction 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[contmonad.htmlThe Continuation monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[hardway.htmlCombining monads the hard way]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Introduction = 
= Introduction = 

−  
−  
−   

Part I has introduced the monad concept and Part II has provided an understanding of a number of common, useful monads in the standard Haskell libraries. This is not enough to put monads into heavy practice, however, because in the real world you often want computations which combine aspects of more than one monad at the same time, such as stateful, nondetermistic computations or computations which make use of continuations and perform I/O. When one computation is a strict subset of the other, it is possible to perform the monad computations separately, unless the subcomputation is performed in a oneway monad. 
Part I has introduced the monad concept and Part II has provided an understanding of a number of common, useful monads in the standard Haskell libraries. This is not enough to put monads into heavy practice, however, because in the real world you often want computations which combine aspects of more than one monad at the same time, such as stateful, nondetermistic computations or computations which make use of continuations and perform I/O. When one computation is a strict subset of the other, it is possible to perform the monad computations separately, unless the subcomputation is performed in a oneway monad. 

Line 1,876:  Line 1,562:  
Monad transformers are the topic of Part III, and they are explained by revisiting earlier examples to see how monad transformers can be used to add more realistic capabilities to them. It may be helpful to review the earlier examples as they are reexamined. 
Monad transformers are the topic of Part III, and they are explained by revisiting earlier examples to see how monad transformers can be used to add more realistic capabilities to them. It may be helpful to review the earlier examples as they are reexamined. 

−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[contmonad.htmlThe Continuation monad]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[hardway.htmlCombining monads the hard way]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Combining monads the hard way 
Combining monads the hard way 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[introIII.htmlPart III  Introduction]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[transformers.htmlMonad transformers]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Combining monads the hard way = 
= Combining monads the hard way = 

−  
−  * [[#nestedNested Monads]] 

−  * [[#combinedCombined Monads]] 

−  
−  
−   

Before we investigate the use of monad transformers, we will see how monads can be combined without using transformers. This is a useful excercise to develop insights into the issues that arise when combining monads and provides a baseline from which the advantages of the transformer approach can be measured. We use the code from [[contmonad.html#exampleexample 18]] (the Continuation monad) to illustrate these issues, so you may want to review it before continuing. 
Before we investigate the use of monad transformers, we will see how monads can be combined without using transformers. This is a useful excercise to develop insights into the issues that arise when combining monads and provides a baseline from which the advantages of the transformer approach can be measured. We use the code from [[contmonad.html#exampleexample 18]] (the Continuation monad) to illustrate these issues, so you may want to review it before continuing. 

Line 1,920:  Line 1,577:  
Code available in [[../examples/example19.hsexample19.hs]] 
Code available in [[../examples/example19.hsexample19.hs]] 

−  <pre>fun :: IO String 
+  <haskell> 
−  fun = do n < (readLn::IO Int)  this is an IO monad block 
+  fun :: IO String 
+  fun = do n < (readLn::IO Int)  this is an IO monad block 

return $ (`runCont` id) $ do  this is a Cont monad block 
return $ (`runCont` id) $ do  this is a Cont monad block 

−  str < callCC $ \exit1 > do 
+  str < callCC $ \exit1 > do 
−  when (n < 10) (exit1 (show n)) 
+  when (n < 10) (exit1 (show n)) 
let ns = map digitToInt (show (n `div` 2)) 
let ns = map digitToInt (show (n `div` 2)) 

−  n' < callCC $ \exit2 > do 
+  n' < callCC $ \exit2 > do 
−  when ((length ns) < 3) (exit2 (length ns)) 
+  when ((length ns) < 3) (exit2 (length ns)) 
−  when ((length ns) < 5) (exit2 n) 
+  when ((length ns) < 5) (exit2 n) 
−  when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns) 
+  when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns) 
exit1 (dropWhile (=='0') ns') 
exit1 (dropWhile (=='0') ns') 

return $ sum ns 
return $ sum ns 

−  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
+  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
−  return $ "Answer: " ++ str</pre> 
+  return $ "Answer: " ++ str 
+  </haskell> 

== Combined Monads == 
== Combined Monads == 

−  What about computations with more complicated structure? If the nesting pattern cannot be used, we need a way to combine the attributes of two or more monads in a single computation. This is accomplished by doing computations within a monad in which the values are themselves monadic values in another monad. For example, we might perform computations in the Continuation monad of type <tt>Cont (IO String) a</tt> if we need to perform I/O within the computation in the Continuation monad. We could use a monad of type <tt>State (Either Err a) a</tt> to combine the features of the State and Error monads in a single computation. 
+  What about computations with more complicated structure? If the nesting pattern cannot be used, we need a way to combine the attributes of two or more monads in a single computation. This is accomplished by doing computations within a monad in which the values are themselves monadic values in another monad. For example, we might perform computations in the Continuation monad of type <code>Cont (IO String) a</code> if we need to perform I/O within the computation in the Continuation monad. We could use a monad of type <code>State (Either Err a) a</code> to combine the features of the State and Error monads in a single computation. 
Consider a slight modification to our example in which we perform the same I/O at the beginning, but we may require additional input in the middle of the computation in the Continuation monad. In this case, we will allow the user to specify part of the output value when the input value is within a certain range. Because the I/O depends on part of the computation in the Continuation monad and part of the computation in the Continuation monad depends on the result of the I/O, we cannot use the nested monad pattern. 
Consider a slight modification to our example in which we perform the same I/O at the beginning, but we may require additional input in the middle of the computation in the Continuation monad. In this case, we will allow the user to specify part of the output value when the input value is within a certain range. Because the I/O depends on part of the computation in the Continuation monad and part of the computation in the Continuation monad depends on the result of the I/O, we cannot use the nested monad pattern. 

−  Instead, we make the computation in the Continuation monad use values from the IO monad. What used to be <tt>Int</tt> and <tt>String</tt> values are now of type <tt>IO Int</tt> and <tt>IO String</tt>. We can't extract values from the IO monad — it's a oneway monad — so we may need to nest little doblocks of the IO monad within the Continuation monad to manipulate the values. We use a helper function <tt>toIO</tt> to make it clearer when we are creating values in the IO monad nested within the Continuation monad. 
+  Instead, we make the computation in the Continuation monad use values from the IO monad. What used to be <code>Int</code> and <code>String</code> values are now of type <code>IO Int</code> and <code>IO String</code>. We can't extract values from the IO monad — it's a oneway monad — so we may need to nest little doblocks of the IO monad within the Continuation monad to manipulate the values. We use a helper function <code>toIO</code> to make it clearer when we are creating values in the IO monad nested within the Continuation monad. 
Code available in [[../examples/example20.hsexample20.hs]] 
Code available in [[../examples/example20.hsexample20.hs]] 

−  <pre>toIO :: a > IO a 
+  <haskell> 
+  toIO :: a > IO a 

toIO x = return x 
toIO x = return x 

fun :: IO String 
fun :: IO String 

−  fun = do n < (readLn::IO Int)  this is an IO monad block 
+  fun = do n < (readLn::IO Int)  this is an IO monad block 
convert n 
convert n 

−  convert :: Int > IO String 
+  convert :: Int > IO String 
convert n = (`runCont` id) $ do  this is a Cont monad block 
convert n = (`runCont` id) $ do  this is a Cont monad block 

−  str < callCC $ \exit1 > do  str has type IO String 
+  str < callCC $ \exit1 > do  str has type IO String 
−  when (n < 10) (exit1 $ toIO (show n)) 
+  when (n < 10) (exit1 $ toIO (show n)) 
let ns = map digitToInt (show (n `div` 2)) 
let ns = map digitToInt (show (n `div` 2)) 

−  n' < callCC $ \exit2 > do  n' has type IO Int 
+  n' < callCC $ \exit2 > do  n' has type IO Int 
−  when ((length ns) < 3) (exit2 (toIO (length ns))) 
+  when ((length ns) < 3) (exit2 (toIO (length ns))) 
−  when ((length ns) < 5) (exit2 $ do putStrLn "Enter a number:" 
+  when ((length ns) < 5) (exit2 $ do putStrLn "Enter a number:" 
−  x < (readLn::IO Int) 
+  x < (readLn::IO Int) 
return x) 
return x) 

−  when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns) 
+  when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns) 
exit1 $ toIO (dropWhile (=='0') ns') 
exit1 $ toIO (dropWhile (=='0') ns') 

return (toIO (sum ns)) 
return (toIO (sum ns)) 

−  return $ do num < n'  this is an IO monad block 
+  return $ do num < n'  this is an IO monad block 
−  return $ "(ns = " ++ (show ns) ++ ") " ++ (show num) 
+  return $ "(ns = " ++ (show ns) ++ ") " ++ (show num) 
−  return $ do s < str  this is an IO monad block 
+  return $ do s < str  this is an IO monad block 
−  return $ "Answer: " ++ s</pre> 
+  return $ "Answer: " ++ s 
+  </haskell> 

Even this trivial example has gotten confusing and ugly when we tried to combine different monads in the same computation. It works, but it isn't pretty. Comparing the code sidebyside shows the degree to which the manual monad combination strategy pollutes the code. 
Even this trivial example has gotten confusing and ugly when we tried to combine different monads in the same computation. It works, but it isn't pretty. Comparing the code sidebyside shows the degree to which the manual monad combination strategy pollutes the code. 

Line 1,974:  Line 1,631:  
Manually combined monads from example 20 
Manually combined monads from example 20 

−  <pre>fun = do n < (readLn::IO Int) 
+  <haskell> 
+  fun = do n < (readLn::IO Int) 

return $ (`runCont` id) $ do 
return $ (`runCont` id) $ do 

−  str < callCC $ \exit1 > do 
+  str < callCC $ \exit1 > do 
−  when (n < 10) (exit1 (show n)) 
+  when (n < 10) (exit1 (show n)) 
let ns = map digitToInt (show (n `div` 2)) 
let ns = map digitToInt (show (n `div` 2)) 

−  n' < callCC $ \exit2 > do 
+  n' < callCC $ \exit2 > do 
−  when ((length ns) < 3) (exit2 (length ns)) 
+  when ((length ns) < 3) (exit2 (length ns)) 
−  when ((length ns) < 5) (exit2 n) 
+  when ((length ns) < 5) (exit2 n) 
−  when ((length ns) < 7) $ do 
+  when ((length ns) < 7) $ do 
let ns' = map intToDigit (reverse ns) 
let ns' = map intToDigit (reverse ns) 

exit1 (dropWhile (=='0') ns') 
exit1 (dropWhile (=='0') ns') 

return $ sum ns 
return $ sum ns 

−  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
+  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
−  return $ "Answer: " ++ str</pre> 
+  return $ "Answer: " ++ str 
−  <pre>convert n = (`runCont` id) $ do 
+  </haskell> 
−  str < callCC $ \exit1 > do 
+  <haskell> 
−  when (n < 10) (exit1 $ toIO (show n)) 
+  convert n = (`runCont` id) $ do 
+  str < callCC $ \exit1 > do 

+  when (n < 10) (exit1 $ toIO (show n)) 

let ns = map digitToInt (show (n `div` 2)) 
let ns = map digitToInt (show (n `div` 2)) 

−  n' < callCC $ \exit2 > do 
+  n' < callCC $ \exit2 > do 
−  when ((length ns) < 3) (exit2 (toIO (length ns))) 
+  when ((length ns) < 3) (exit2 (toIO (length ns))) 
−  when ((length ns) < 5) (exit2 $ do 
+  when ((length ns) < 5) (exit2 $ do 
−  putStrLn "Enter a number:" 
+  putStrLn "Enter a number:" 
−  x < (readLn::IO Int) 
+  x < (readLn::IO Int) 
return x) 
return x) 

−  when ((length ns) < 7) $ do 
+  when ((length ns) < 7) $ do 
let ns' = map intToDigit (reverse ns) 
let ns' = map intToDigit (reverse ns) 

exit1 $ toIO (dropWhile (=='0') ns') 
exit1 $ toIO (dropWhile (=='0') ns') 

return (toIO (sum ns)) 
return (toIO (sum ns)) 

−  return $ do num < n' 
+  return $ do num < n' 
−  return $ "(ns = " ++ (show ns) ++ ") " ++ (show num) 
+  return $ "(ns = " ++ (show ns) ++ ") " ++ (show num) 
−  return $ do s < str 
+  return $ do s < str 
−  return $ "Answer: " ++ s</pre> 
+  return $ "Answer: " ++ s 
−  +  </haskell> 

−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[introIII.htmlPart III  Introduction]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[transformers.htmlMonad transformers]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

−  
Monad transformers 
Monad transformers 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[hardway.htmlCombining monads the hard way]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[standardxformers.htmlStandard monad transformers]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Monad transformers = 
= Monad transformers = 

−  
−  * [[#typeTransformer type constructors]] 

−  * [[#liftingLifting]] 

−  
−  
−   

Monad transformers are special variants of standard monads that facilitate the combining of monads. Their type constructors are parameterized over a monad type constructor, and they produce combined monadic types. 
Monad transformers are special variants of standard monads that facilitate the combining of monads. Their type constructors are parameterized over a monad type constructor, and they produce combined monadic types. 

Line 2,031:  Line 1,672:  
== Transformer type constructors == 
== Transformer type constructors == 

−  Type constructors play a fundamental role in Haskell's monad support. Recall that <tt>Reader r a</tt> is the type of values of type <tt>a</tt> within a Reader monad with environment of type <tt>r</tt>. The type constructor <tt>Reader r</tt> is an instance of the <tt>Monad</tt> class, and the <tt>runReader::(r>a)</tt> function performs a computation in the Reader monad and returns the result of type <tt>a</tt>. 
+  Type constructors play a fundamental role in Haskell's monad support. Recall that <code>Reader r a</code> is the type of values of type <code>a</code> within a Reader monad with environment of type <code>r</code>. The type constructor <code>Reader r</code> is an instance of the <code>Monad</code> class, and the <code>runReader::(r>a)</code> function performs a computation in the Reader monad and returns the result of type <code>a</code>. 
−  A transformer version of the Reader monad, called <tt>ReaderT</tt>, exists which adds a monad type constructor as an addition parameter. <tt>ReaderT r m a</tt> is the type of values of the combined monad in which Reader is the base monad and <tt>m</tt> is the inner monad. <tt>ReaderT r m</tt> is an instance of the monad class, and the <tt>runReaderT::(r > m a)</tt> function performs a computation in the combined monad and returns a result of type <tt>m a</tt>. 
+  A transformer version of the Reader monad, called <code>ReaderT</code>, exists which adds a monad type constructor as an addition parameter. <code>ReaderT r m a</code> is the type of values of the combined monad in which Reader is the base monad and <code>m</code> is the inner monad. <code>ReaderT r m</code> is an instance of the monad class, and the <code>runReaderT::(r > m a)</code> function performs a computation in the combined monad and returns a result of type <code>m a</code>. 
−  Using the transformer versions of the monads, we can produce combined monads very simply. <tt>ReaderT r IO</tt> is a combined Reader+IO monad. We can also generate the nontransformer version of a monad from the transformer version by applying it to the Identity monad. So <tt>ReaderT r Identity</tt> is the same monad as <tt>Reader r</tt>. 
+  Using the transformer versions of the monads, we can produce combined monads very simply. <code>ReaderT r IO</code> is a combined Reader+IO monad. We can also generate the nontransformer version of a monad from the transformer version by applying it to the Identity monad. So <code>ReaderT r Identity</code> is the same monad as <code>Reader r</code>. 
[[Image:info.png]] If your code produces kind errors during compilation, it means that you are not using the type cosntructors properly. Make sure that you have supplied the correct number of parameters to the type constructors and that you have not left out any parenthesis in complex type expressions. 
[[Image:info.png]] If your code produces kind errors during compilation, it means that you are not using the type cosntructors properly. Make sure that you have supplied the correct number of parameters to the type constructors and that you have not left out any parenthesis in complex type expressions. 

Line 2,043:  Line 1,684:  
When using combined monads created by the monad transformers, we avoid having to explicitly manage the inner monad types, resulting in clearer, simpler code. Instead of creating additional doblocks within the computation to manipulate values in the inner monad type, we can use lifting operations to bring functions from the inner monad into the combined monad. 
When using combined monads created by the monad transformers, we avoid having to explicitly manage the inner monad types, resulting in clearer, simpler code. Instead of creating additional doblocks within the computation to manipulate values in the inner monad type, we can use lifting operations to bring functions from the inner monad into the combined monad. 

−  Recall the <tt>liftM</tt> family of functions which are used to lift nonmonadic functions into a monad. Each monad transformer provides a <tt>lift</tt> function that is used to lift a monadic computation into a combined monad. Many transformers also provide a <tt>liftIO</tt> function, which is a version of <tt>lift</tt> that is optimized for lifting computations in the <tt>IO</tt> monad. To see this in action, we will continue to develop our previous example in the Continuation monad. 
+  Recall the <code>liftM</code> family of functions which are used to lift nonmonadic functions into a monad. Each monad transformer provides a <code>lift</code> function that is used to lift a monadic computation into a combined monad. Many transformers also provide a <code>liftIO</code> function, which is a version of <code>lift</code> that is optimized for lifting computations in the <code>IO</code> monad. To see this in action, we will continue to develop our previous example in the Continuation monad. 
Code available in [[../examples/example21.hsexample21.hs]] 
Code available in [[../examples/example21.hsexample21.hs]] 

−  <pre>fun :: IO String 
+  <haskell> 
+  fun :: IO String 

fun = (`runContT` return) $ do 
fun = (`runContT` return) $ do 

−  n < liftIO (readLn::IO Int) 
+  n < liftIO (readLn::IO Int) 
−  str < callCC $ \exit1 > do  define "exit1" 
+  str < callCC $ \exit1 > do  define "exit1" 
−  when (n < 10) (exit1 (show n)) 
+  when (n < 10) (exit1 (show n)) 
let ns = map digitToInt (show (n `div` 2)) 
let ns = map digitToInt (show (n `div` 2)) 

−  n' < callCC $ \exit2 > do  define "exit2" 
+  n' < callCC $ \exit2 > do  define "exit2" 
−  when ((length ns) < 3) (exit2 (length ns)) 
+  when ((length ns) < 3) (exit2 (length ns)) 
−  when ((length ns) < 5) $ do liftIO $ putStrLn "Enter a number:" 
+  when ((length ns) < 5) $ do liftIO $ putStrLn "Enter a number:" 
−  x < liftIO (readLn::IO Int) 
+  x < liftIO (readLn::IO Int) 
exit2 x 
exit2 x 

−  when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns) 
+  when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns) 
exit1 (dropWhile (=='0') ns') escape 2 levels 
exit1 (dropWhile (=='0') ns') escape 2 levels 

return $ sum ns 
return $ sum ns 

−  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
+  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
−  return $ "Answer: " ++ str</pre> 
+  return $ "Answer: " ++ str 
−  Compare this function using <tt>ContT</tt>, the transformer version of <tt>Cont</tt>, with the original version to see how unobtrusive the changes become when using the monad transformer. 
+  </haskell> 
+  Compare this function using <code>ContT</code>, the transformer version of <code>Cont</code>, with the original version to see how unobtrusive the changes become when using the monad transformer. 

Nested monads from example 19 
Nested monads from example 19 

Line 2,069:  Line 1,710:  
Monads combined with a transformer from example 21 
Monads combined with a transformer from example 21 

−  <pre>fun = do n < (readLn::IO Int) 
+  <haskell> 
+  fun = do n < (readLn::IO Int) 

return $ (`runCont` id) $ do 
return $ (`runCont` id) $ do 

−  str < callCC $ \exit1 > do 
+  str < callCC $ \exit1 > do 
−  when (n < 10) (exit1 (show n)) 
+  when (n < 10) (exit1 (show n)) 
let ns = map digitToInt (show (n `div` 2)) 
let ns = map digitToInt (show (n `div` 2)) 

−  n' < callCC $ \exit2 > do 
+  n' < callCC $ \exit2 > do 
−  when ((length ns) < 3) (exit2 (length ns)) 
+  when ((length ns) < 3) (exit2 (length ns)) 
−  when ((length ns) < 5) (exit2 n) 
+  when ((length ns) < 5) (exit2 n) 
−  when ((length ns) < 7) $ do 
+  when ((length ns) < 7) $ do 
let ns' = map intToDigit (reverse ns) 
let ns' = map intToDigit (reverse ns) 

exit1 (dropWhile (=='0') ns') 
exit1 (dropWhile (=='0') ns') 

return $ sum ns 
return $ sum ns 

−  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
+  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
−  return $ "Answer: " ++ str</pre> 
+  return $ "Answer: " ++ str 
−  <pre>fun = (`runContT` return) $ do 
+  </haskell> 
−  n < liftIO (readLn::IO Int) 
+  <haskell> 
−  str < callCC $ \exit1 > do 
+  fun = (`runContT` return) $ do 
−  when (n < 10) (exit1 (show n)) 
+  n < liftIO (readLn::IO Int) 
+  str < callCC $ \exit1 > do 

+  when (n < 10) (exit1 (show n)) 

let ns = map digitToInt (show (n `div` 2)) 
let ns = map digitToInt (show (n `div` 2)) 

−  n' < callCC $ \exit2 > do 
+  n' < callCC $ \exit2 > do 
−  when ((length ns) < 3) (exit2 (length ns)) 
+  when ((length ns) < 3) (exit2 (length ns)) 
−  when ((length ns) < 5) $ do 
+  when ((length ns) < 5) $ do 
−  liftIO $ putStrLn "Enter a number:" 
+  liftIO $ putStrLn "Enter a number:" 
−  x < liftIO (readLn::IO Int) 
+  x < liftIO (readLn::IO Int) 
exit2 x 
exit2 x 

−  when ((length ns) < 7) $ do 
+  when ((length ns) < 7) $ do 
let ns' = map intToDigit (reverse ns) 
let ns' = map intToDigit (reverse ns) 

exit1 (dropWhile (=='0') ns') 
exit1 (dropWhile (=='0') ns') 

return $ sum ns 
return $ sum ns 

−  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
+  return $ "(ns = " ++ (show ns) ++ ") " ++ (show n') 
−  return $ "Answer: " ++ str</pre> 
+  return $ "Answer: " ++ str 
+  </haskell> 

The impact of adding the I/O in the middle of the computation is narrowly confined when using the monad transformer. Contrast this with the [[hardway.html#comparisonchanges]] required to achieve the same result using a manually combined monad. 
The impact of adding the I/O in the middle of the computation is narrowly confined when using the monad transformer. Contrast this with the [[hardway.html#comparisonchanges]] required to achieve the same result using a manually combined monad. 

−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[hardway.htmlCombining monads the hard way]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[standardxformers.htmlStandard monad transformers]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Standard monad transformers 
Standard monad transformers 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[transformers.htmlMonad transformers]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[xformeranatomy.htmlAnatomy of a monad transformer]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Standard monad transformers = 
= Standard monad transformers = 

−  
−  * [[#classesThe MonadTrans and MonadIO classes]] 

−  * [[#libraryTransformer versions of standard monads]] 

−  
−  
−   

Haskell's base libraries provide support for monad transformers in the form of classes which represent monad transformers and special transformer versions of standard monads. 
Haskell's base libraries provide support for monad transformers in the form of classes which represent monad transformers and special transformer versions of standard monads. 

Line 2,139:  Line 1,751:  
== The MonadTrans and MonadIO classes == 
== The MonadTrans and MonadIO classes == 

−  The <tt>MonadTrans</tt> class is defined in [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Trans.html Control.Monad.Trans] and provides the single function <tt>lift</tt>. The <tt>lift</tt> function lifts a monadic computation in the inner monad into the combined monad. 
+  The <code>MonadTrans</code> class is defined in [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Trans.html Control.Monad.Trans] and provides the single function <code>lift</code>. The <code>lift</code> function lifts a monadic computation in the inner monad into the combined monad. 
−  <pre>class MonadTrans t where 
+  <haskell> 
−  lift :: (Monad m) => m a > t m a</pre> 
+  class MonadTrans t where 
−  Monads which provide optimized support for lifting IO operations are defined as members of the <tt>MonadIO</tt> class, which defines the <tt>liftIO</tt> function. 
+  lift :: (Monad m) => m a > t m a 
+  </haskell> 

+  Monads which provide optimized support for lifting IO operations are defined as members of the <code>MonadIO</code> class, which defines the <code>liftIO</code> function. 

−  <pre>class (Monad m) => MonadIO m where 
+  <haskell> 
−  liftIO :: IO a > m a</pre> 
+  class (Monad m) => MonadIO m where 
+  liftIO :: IO a > m a 

+  </haskell> 

== Transformer versions of standard monads == 
== Transformer versions of standard monads == 

−  The standard monads of the monad template library all have transformer versions which are defined consistently with their nontransformer versions. However, it is not the case the all monad transformers apply the same transformation. We have seen that the <tt>ContT</tt> transformer turns continuations of the form <tt>(a>r)>r</tt> into continuations of the form <tt>(a>m r)>m r</tt>. The <tt>StateT</tt> transformer is different. It turns state transformer functions of the form <tt>s>(a,s)</tt> into state transformer functions of the form <tt>s>m (a,s)</tt>. In general, there is no magic formula to create a transformer version of a monad — the form of each transformer depends on what makes sense in the context of its nontransformer type. 
+  The standard monads of the monad template library all have transformer versions which are defined consistently with their nontransformer versions. However, it is not the case the all monad transformers apply the same transformation. We have seen that the <code>ContT</code> transformer turns continuations of the form <code>(a>r)>r</code> into continuations of the form <code>(a>m r)>m r</code>. The <code>StateT</code> transformer is different. It turns state transformer functions of the form <code>s>(a,s)</code> into state transformer functions of the form <code>s>m (a,s)</code>. In general, there is no magic formula to create a transformer version of a monad — the form of each transformer depends on what makes sense in the context of its nontransformer type. 
<table> 
<table> 

−  <thead> 

<tr class="header"> 
<tr class="header"> 

<th align="left">Standard Monad</th> 
<th align="left">Standard Monad</th> 

Line 2,159:  Line 1,770:  
<th align="left">Combined Type</th> 
<th align="left">Combined Type</th> 

</tr> 
</tr> 

−  </thead> 

−  <tbody> 

<tr class="odd"> 
<tr class="odd"> 

<td align="left">[[errormonad.htmlError]]</td> 
<td align="left">[[errormonad.htmlError]]</td> 

<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Error.html#ErrorT ErrorT]</td> 
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Error.html#ErrorT ErrorT]</td> 

−  <td align="left"><tt>Either e a</tt></td> 
+  <td align="left"><code>Either e a</code></td> 
−  <td align="left"><tt>m (Either e a)</tt></td> 
+  <td align="left"><code>m (Either e a)</code></td> 
</tr> 
</tr> 

<tr class="even"> 
<tr class="even"> 

<td align="left">[[statemonad.htmlState]]</td> 
<td align="left">[[statemonad.htmlState]]</td> 

<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.State.html#StateT StateT]</td> 
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.State.html#StateT StateT]</td> 

−  <td align="left"><tt>s > (a,s)</tt></td> 
+  <td align="left"><code>s > (a,s)</code></td> 
−  <td align="left"><tt>s > m (a,s)</tt></td> 
+  <td align="left"><code>s > m (a,s)</code></td> 
</tr> 
</tr> 

<tr class="odd"> 
<tr class="odd"> 

<td align="left">[[readermonad.htmlReader]]</td> 
<td align="left">[[readermonad.htmlReader]]</td> 

<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Reader.html#ReaderT ReaderT]</td> 
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Reader.html#ReaderT ReaderT]</td> 

−  <td align="left"><tt>r > a</tt></td> 
+  <td align="left"><code>r > a</code></td> 
−  <td align="left"><tt>r > m a</tt></td> 
+  <td align="left"><code>r > m a</code></td> 
</tr> 
</tr> 

<tr class="even"> 
<tr class="even"> 

<td align="left">[[writermonad.htmlWriter]]</td> 
<td align="left">[[writermonad.htmlWriter]]</td> 

<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Writer.html#WriterT WriterT]</td> 
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Writer.html#WriterT WriterT]</td> 

−  <td align="left"><tt>(a,w)</tt></td> 
+  <td align="left"><code>(a,w)</code></td> 
−  <td align="left"><tt>m (a,w)</tt></td> 
+  <td align="left"><code>m (a,w)</code></td> 
</tr> 
</tr> 

<tr class="odd"> 
<tr class="odd"> 

<td align="left">[[contmonad.htmlCont]]</td> 
<td align="left">[[contmonad.htmlCont]]</td> 

<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Cont.html#ContT ContT]</td> 
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Cont.html#ContT ContT]</td> 

−  <td align="left"><tt>(a > r) > r</tt></td> 
+  <td align="left"><code>(a > r) > r</code></td> 
−  <td align="left"><tt>(a > m r) > m r</tt></td> 
+  <td align="left"><code>(a > m r) > m r</code></td> 
</tr> 
</tr> 

−  </tbody> 

</table> 
</table> 

−  [[Image:info.png]] Order is important when combining monads. <tt>StateT s (Error e)</tt> is different than <tt>ErrorT e (State s)</tt>. The first produces a combined type of <tt>s > Error e (a,s)</tt>, in which the computation can either return a new state or generate an error. The second combination produces a combined type of <tt>s > (Error e a,s)</tt>, in which the computation always returns a new state, and the value can be an error or a normal value.<br /> 
+  [[Image:info.png]] Order is important when combining monads. <code>StateT s (Error e)</code> is different than <code>ErrorT e (State s)</code>. The first produces a combined type of <code>s > Error e (a,s)</code>, in which the computation can either return a new state or generate an error. The second combination produces a combined type of <code>s > (Error e a,s)</code>, in which the computation always returns a new state, and the value can be an error or a normal value.<br /> 
−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[transformers.htmlStandard monad transformers]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[xformeranatomy.htmlAnatomy of a monad transformer]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Anatomy of a monad transformer 
Anatomy of a monad transformer 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[standardxformers.htmlStandard monad transformers]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[xformerexamples.htmlMore examples with monad transformers]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Anatomy of a monad transformer = 
= Anatomy of a monad transformer = 

−  * [[#monadCombined monad definition]] 
+  In this section, we will take a detailed look at the implementation of one of the more interesting transformers in the standard library, <code>StateT</code>. Studying this transformer will build insight into the transformer mechanism that you can call upon when using monad transformers in your code. You might want to review the section on the [[statemonad.htmlState monad]] before continuing. 
−  * [[#liftDefining the lifting function]] 

−  * [[#functorFunctors]] 

−  
−  
−   

−  
−  In this section, we will take a detailed look at the implementation of one of the more interesting transformers in the standard library, <tt>StateT</tt>. Studying this transformer will build insight into the transformer mechanism that you can call upon when using monad transformers in your code. You might want to review the section on the [[statemonad.htmlState monad]] before continuing. 

== Combined monad definition == 
== Combined monad definition == 

Line 2,230:  Line 1,815:  
Just as the State monad was built upon the definition 
Just as the State monad was built upon the definition 

−  <pre>newtype State s a = State { runState :: (s > (a,s)) }</pre> 
+  <haskell> 
+  newtype State s a = State { runState :: (s > (a,s)) } 

+  </haskell> 

the StateT transformer is built upon the definition 
the StateT transformer is built upon the definition 

−  <pre>newtype StateT s m a = StateT { runStateT :: (s > m (a,s)) }</pre> 
+  <haskell> 
−  <tt>State s</tt> is an instance of both the <tt>Monad</tt> class and the <tt>MonadState s</tt> class, so <tt>StateT s m</tt> should also be members of the <tt>Monad</tt> and <tt>MonadState s</tt> classes. Furthermore, if <tt>m</tt> is an instance of <tt>MonadPlus</tt>, <tt>StateT s m</tt> should also be a member of <tt>MonadPlus</tt>. 
+  newtype StateT s m a = StateT { runStateT :: (s > m (a,s)) } 
+  </haskell> 

+  <code>State s</code> is an instance of both the <code>Monad</code> class and the <code>MonadState s</code> class, so <code>StateT s m</code> should also be members of the <code>Monad</code> and <code>MonadState s</code> classes. Furthermore, if <code>m</code> is an instance of <code>MonadPlus</code>, <code>StateT s m</code> should also be a member of <code>MonadPlus</code>. 

−  To define <tt>StateT s m</tt> as a <tt>Monad</tt> instance: 
+  To define <code>StateT s m</code> as a <code>Monad</code> instance: 
−  <pre>newtype StateT s m a = StateT { runStateT :: (s > m (a,s)) } 
+  <haskell> 
+  newtype StateT s m a = StateT { runStateT :: (s > m (a,s)) } 

−  instance (Monad m) => Monad (StateT s m) where 
+  instance (Monad m) => Monad (StateT s m) where 
−  return a = StateT $ \s > return (a,s) 
+  return a = StateT $ \s > return (a,s) 
−  (StateT x) >>= f = StateT $ \s > do (v,s') < x s  get new value, state 
+  (StateT x) >>= f = StateT $ \s > do (v,s') < x s  get new value, state 
−  (StateT x') < return $ f v  apply bound function to get new state transformation fn 
+  (StateT x') < return $ f v  apply bound function to get new state transformation fn 
−  x' s'  apply the state transformation fn to the new state</pre> 
+  x' s'  apply the state transformation fn to the new state 
−  Compare this to the definition for [[statemonad.html#definition<tt>State s</tt>]]. Our definition of <tt>return</tt> makes use of the <tt>return</tt> function of the inner monad, and the binding operator uses a doblock to perform a computation in the inner monad. 
+  </haskell> 
+  Compare this to the definition for [[statemonad.html#definition<code>State s</code>]]. Our definition of <code>return</code> makes use of the <code>return</code> function of the inner monad, and the binding operator uses a doblock to perform a computation in the inner monad. 

−  We also want to declare all combined monads that use the <tt>StateT</tt> transformer to be instaces of the <tt>MonadState</tt> class, so we will have to give definitions for <tt>get</tt> and <tt>put</tt>: 
+  We also want to declare all combined monads that use the <code>StateT</code> transformer to be instaces of the <code>MonadState</code> class, so we will have to give definitions for <code>get</code> and <code>put</code>: 
−  <pre>instance (Monad m) => MonadState s (StateT s m) where 
+  <haskell> 
−  get = StateT $ \s > return (s,s) 
+  instance (Monad m) => MonadState s (StateT s m) where 
−  put s = StateT $ \_ > return ((),s)</pre> 
+  get = StateT $ \s > return (s,s) 
−  Finally, we want to declare all combined monads in which <tt>StateT</tt> is used with an instance of <tt>MonadPlus</tt> to be instances of <tt>MonadPlus</tt>: 
+  put s = StateT $ \_ > return ((),s) 
+  </haskell> 

+  Finally, we want to declare all combined monads in which <code>StateT</code> is used with an instance of <code>MonadPlus</code> to be instances of <code>MonadPlus</code>: 

−  <pre>instance (MonadPlus m) => MonadPlus (StateT s m) where 
+  <haskell> 
−  mzero = StateT $ \s > mzero 
+  instance (MonadPlus m) => MonadPlus (StateT s m) where 
−  (StateT x1) `mplus` (StateT x2) = StateT $ \s > (x1 s) `mplus` (x2 s)</pre> 
+  mzero = StateT $ \s > mzero 
+  (StateT x1) `mplus` (StateT x2) = StateT $ \s > (x1 s) `mplus` (x2 s) 

+  </haskell> 

== Defining the lifting function == 
== Defining the lifting function == 

−  The final step to make our monad transformer fully integrated with Haskell's monad classes is to make <tt>StateT s</tt> an instance of the <tt>MonadTrans</tt> class by providing a <tt>lift</tt> function: 
+  The final step to make our monad transformer fully integrated with Haskell's monad classes is to make <code>StateT s</code> an instance of the <code>MonadTrans</code> class by providing a <code>lift</code> function: 
−  <pre>instance MonadTrans (StateT s) where 
+  <haskell> 
−  lift c = StateT $ \s > c >>= (\x > return (x,s))</pre> 
+  instance MonadTrans (StateT s) where 
−  The <tt>lift</tt> function creates a <tt>StateT</tt> state transformation function that binds the computation in the inner monad to a function that packages the result with the input state. The result is that a function that returns a list (i.e., a computation in the List monad) can be lifted into <tt>StateT s []</tt>, where it becomes a function that returns a <tt>StateT (s > [(a,s)])</tt>. That is, the lifted computation produces ''multiple'' (value,state) pairs from its input state. The effect of this is to "fork" the computation in StateT, creating a different branch of the computation for each value in the list returned by the lifted function. Of course, applying <tt>StateT</tt> to a different monad will produce different semantics for the <tt>lift</tt> function. 
+  lift c = StateT $ \s > c >>= (\x > return (x,s)) 
+  </haskell> 

+  The <code>lift</code> function creates a <code>StateT</code> state transformation function that binds the computation in the inner monad to a function that packages the result with the input state. The result is that a function that returns a list (i.e., a computation in the List monad) can be lifted into <code>StateT s []</code>, where it becomes a function that returns a <code>StateT (s > [(a,s)])</code>. That is, the lifted computation produces ''multiple'' (value,state) pairs from its input state. The effect of this is to "fork" the computation in StateT, creating a different branch of the computation for each value in the list returned by the lifted function. Of course, applying <code>StateT</code> to a different monad will produce different semantics for the <code>lift</code> function. 

== Functors == 
== Functors == 

Line 2,269:  Line 1,854:  
We have examined the implementation of one monad transformer above, and it was stated earlier that there was no magic formula to produce transformer versions of monads. Each transformer's implementation will depend on the nature of the computational effects it is adding to the inner monad. 
We have examined the implementation of one monad transformer above, and it was stated earlier that there was no magic formula to produce transformer versions of monads. Each transformer's implementation will depend on the nature of the computational effects it is adding to the inner monad. 

−  Despite this, there is some theoretical foundation to the theory of monad transformers. Certain transformers can be grouped according to how they use the inner monad, and the transformers within each group can be derived using monadic functions and functors. Functors, roughly, are types which support a mapping operation <tt>fmap :: (a>b) > f a > f b</tt>. To learn more about it, check out Mark Jones' influential [http://wwwinternal.cse.ogi.edu/~mpj/pubs/springschool95.ps paper] that inspired the Haskell monad template library. 
+  Despite this, there is some theoretical foundation to the theory of monad transformers. Certain transformers can be grouped according to how they use the inner monad, and the transformers within each group can be derived using monadic functions and functors. Functors, roughly, are types which support a mapping operation <code>fmap :: (a>b) > f a > f b</code>. To learn more about it, check out Mark Jones' influential [http://wwwinternal.cse.ogi.edu/~mpj/pubs/springschool95.ps paper] that inspired the Haskell monad template library. 
−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[standardxformers.htmlStandard monad transformers]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[xformerexamples.htmlMore examples with monad transformers]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

More examples with monad transformers 
More examples with monad transformers 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[xformeranatomy.htmlAnatomy of a monad transformer]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[stacking.htmlManaging the transformer stack]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= More examples with monad transformers = 
= More examples with monad transformers = 

−  
−  * [[#example22WriterT with IO]] 

−  * [[#example23ReaderT with IO]] 

−  * [[#example24StateT with List]] 

−  
−  
−   

At this point, you should know everything you need to begin using monads and monad transformers in your programs. The best way to build proficiency is to work on actual code. As your monadic programs become more abitious, you may find it awkward to mix additional transformers into your combined monads. This will be addressed in the next section, but first you should master the basic process of applying a single transformer to a base monad. 
At this point, you should know everything you need to begin using monads and monad transformers in your programs. The best way to build proficiency is to work on actual code. As your monadic programs become more abitious, you may find it awkward to mix additional transformers into your combined monads. This will be addressed in the next section, but first you should master the basic process of applying a single transformer to a base monad. 

Line 2,300:  Line 1,868:  
Code available in [[../examples/example22.hsexample22.hs]] 
Code available in [[../examples/example22.hsexample22.hs]] 

−  <pre> this is the format of our log entries 
+  <haskell> 
+   this is the format of our log entries 

data Entry = Log {timestamp::ClockTime, msg::String} deriving Eq 
data Entry = Log {timestamp::ClockTime, msg::String} deriving Eq 

instance Show Entry where 
instance Show Entry where 

−  show (Log t s) = (show t) ++ "  " ++ s 
+  show (Log t s) = (show t) ++ "  " ++ s 
 this is the combined monad type 
 this is the combined monad type 

Line 2,310:  Line 1,878:  
 add a message to the log 
 add a message to the log 

−  logMsg :: String > LogWriter () 
+  logMsg :: String > LogWriter () 
−  logMsg s = do t < liftIO getClockTime 
+  logMsg s = do t < liftIO getClockTime 
tell [Log t s] 
tell [Log t s] 

 this handles one packet 
 this handles one packet 

−  filterOne :: [Rule] > Packet > LogWriter (Maybe Packet) 
+  filterOne :: [Rule] > Packet > LogWriter (Maybe Packet) 
−  filterOne rules packet = do rule < return (match rules packet) 
+  filterOne rules packet = do rule < return (match rules packet) 
case rule of 
case rule of 

−  Nothing > do logMsg ("DROPPING UNMATCHED PACKET: " ++ (show packet)) 
+  Nothing > do logMsg ("DROPPING UNMATCHED PACKET: " ++ (show packet)) 
return Nothing 
return Nothing 

−  (Just r) > do when (logIt r) (logMsg ("MATCH: " ++ (show r) ++ " <=> " ++ (show packet))) 
+  (Just r) > do when (logIt r) (logMsg ("MATCH: " ++ (show r) ++ " <=> " ++ (show packet))) 
case r of 
case r of 

−  (Rule Accept _ _) > return (Just packet) 
+  (Rule Accept _ _) > return (Just packet) 
−  (Rule Reject _ _) > return Nothing 
+  (Rule Reject _ _) > return Nothing 
 this filters a list of packets, producing a filtered packet list 
 this filters a list of packets, producing a filtered packet list 

 and a log of the activity 
 and a log of the activity 

−  filterAll :: [Rule] > [Packet] > LogWriter [Packet] 
+  filterAll :: [Rule] > [Packet] > LogWriter [Packet] 
−  filterAll rules packets = do logMsg "STARTING PACKET FILTER" 
+  filterAll rules packets = do logMsg "STARTING PACKET FILTER" 
−  out < mapM (filterOne rules) packets 
+  out < mapM (filterOne rules) packets 
−  logMsg "STOPPING PACKET FILTER" 
+  logMsg "STOPPING PACKET FILTER" 
return (catMaybes out) 
return (catMaybes out) 

Line 2,337:  Line 1,905:  
 a log generated during the computation. 
 a log generated during the computation. 

main :: IO () 
main :: IO () 

−  main = do args < getArgs 
+  main = do args < getArgs 
−  ruleData < readFile (args!!0) 
+  ruleData < readFile (args!!0) 
−  packetData < readFile (args!!1) 
+  packetData < readFile (args!!1) 
let rules = (read ruleData)::[Rule] 
let rules = (read ruleData)::[Rule] 

packets = (read packetData)::[Packet] 
packets = (read packetData)::[Packet] 

−  (out,log) < runWriterT (filterAll rules packets) 
+  (out,log) < runWriterT (filterAll rules packets) 
−  putStrLn "ACCEPTED PACKETS" 
+  putStrLn "ACCEPTED PACKETS" 
putStr (unlines (map show out)) 
putStr (unlines (map show out)) 

−  putStrLn "\n\nFIREWALL LOG" 
+  putStrLn "\n\nFIREWALL LOG" 
−  putStr (unlines (map show log))</pre> 
+  putStr (unlines (map show log)) 
+  </haskell> 

== ReaderT with IO == 
== ReaderT with IO == 

Line 2,353:  Line 1,921:  
== StateT with List == 
== StateT with List == 

−  The previous examples have all been using the IO monad as the inner monad. Here is a more interesting example: combining <tt>StateT</tt> with the List monad to produce a monad for stateful nondeterministic computations. 
+  The previous examples have all been using the IO monad as the inner monad. Here is a more interesting example: combining <code>StateT</code> with the List monad to produce a monad for stateful nondeterministic computations. 
We will apply this powerful monad combination to the task of solving constraint satisfaction problems (in this case, a logic problem). The idea behind it is to have a number of variables that can take on different values and a number of predicates involving those variables that must be satisfied. The current variable assignments and the predicates make up the state of the computation, and the nondeterministic nature of the List monad allows us to easily test all combinations of variable assignments. 
We will apply this powerful monad combination to the task of solving constraint satisfaction problems (in this case, a logic problem). The idea behind it is to have a number of variables that can take on different values and a number of predicates involving those variables that must be satisfied. The current variable assignments and the predicates make up the state of the computation, and the nondeterministic nature of the List monad allows us to easily test all combinations of variable assignments. 

Line 2,361:  Line 1,929:  
Code available in [[../examples/example24.hsexample24.hs]] 
Code available in [[../examples/example24.hsexample24.hs]] 

−  <pre> First, we develop a language to express logic problems 
+  <haskell> 
+   First, we develop a language to express logic problems 

type Var = String 
type Var = String 

type Value = String 
type Value = String 

Line 2,374:  Line 1,942:  
 test for a variable NOT equaling a value 
 test for a variable NOT equaling a value 

−  isNot :: Var > Value > Predicate 
+  isNot :: Var > Value > Predicate 
isNot var value = Not (Is var value) 
isNot var value = Not (Is var value) 

 if a is true, then b must also be true 
 if a is true, then b must also be true 

−  implies :: Predicate > Predicate > Predicate 
+  implies :: Predicate > Predicate > Predicate 
implies a b = Not (a `And` (Not b)) 
implies a b = Not (a `And` (Not b)) 

 exclusive or 
 exclusive or 

−  orElse :: Predicate > Predicate > Predicate 
+  orElse :: Predicate > Predicate > Predicate 
orElse a b = (a `And` (Not b)) `Or` ((Not a) `And` b) 
orElse a b = (a `And` (Not b)) `Or` ((Not a) `And` b) 

 Check a predicate with the given variable bindings. 
 Check a predicate with the given variable bindings. 

 An unbound variable causes a Nothing return value. 
 An unbound variable causes a Nothing return value. 

−  check :: Predicate > Variables > Maybe Bool 
+  check :: Predicate > Variables > Maybe Bool 
−  check (Is var value) vars = do val < lookup var vars 
+  check (Is var value) vars = do val < lookup var vars 
return (val == value) 
return (val == value) 

−  check (Equal v1 v2) vars = do val1 < lookup v1 vars 
+  check (Equal v1 v2) vars = do val1 < lookup v1 vars 
−  val2 < lookup v2 vars 
+  val2 < lookup v2 vars 
return (val1 == val2) 
return (val1 == val2) 

−  check (And p1 p2) vars = liftM2 (&&) (check p1 vars) (check p2 vars) 
+  check (And p1 p2) vars = liftM2 (&&) (check p1 vars) (check p2 vars) 
check (Or p1 p2) vars = liftM2 () (check p1 vars) (check p2 vars) 
check (Or p1 p2) vars = liftM2 () (check p1 vars) (check p2 vars) 

−  check (Not p) vars = liftM (not) (check p vars)</pre> 
+  check (Not p) vars = liftM (not) (check p vars) 
+  </haskell> 

The next thing we will need is some code for representing and solving constraint satisfaction problems. This is where we will define our combined monad. 
The next thing we will need is some code for representing and solving constraint satisfaction problems. This is where we will define our combined monad. 

Code available in [[../examples/example24.hsexample24.hs]] 
Code available in [[../examples/example24.hsexample24.hs]] 

−  <pre> this is the type of our logic problem 
+  <haskell> 
+   this is the type of our logic problem 

data ProblemState = PS {vars::Variables, constraints::[Predicate]} 
data ProblemState = PS {vars::Variables, constraints::[Predicate]} 

Line 2,407:  Line 1,975:  
 lookup a variable 
 lookup a variable 

−  getVar :: Var > NDS (Maybe Value) 
+  getVar :: Var > NDS (Maybe Value) 
−  getVar v = do vs < gets vars 
+  getVar v = do vs < gets vars 
return $ lookup v vs 
return $ lookup v vs 

 set a variable 
 set a variable 

−  setVar :: Var > Value > NDS () 
+  setVar :: Var > Value > NDS () 
−  setVar v x = do st < get 
+  setVar v x = do st < get 
−  vs' < return $ filter ((v/=).fst) (vars st) 
+  vs' < return $ filter ((v/=).fst) (vars st) 
put $ st {vars=(v,x):vs'} 
put $ st {vars=(v,x):vs'} 

Line 2,422:  Line 1,990:  
 allows us to accept partial solutions, then we can use a value of 
 allows us to accept partial solutions, then we can use a value of 

 False at the end to signify that all solutions should be complete. 
 False at the end to signify that all solutions should be complete. 

−  isConsistent :: Bool > NDS Bool 
+  isConsistent :: Bool > NDS Bool 
−  isConsistent partial = do cs < gets constraints 
+  isConsistent partial = do cs < gets constraints 
−  vs < gets vars 
+  vs < gets vars 
−  let results = map (\p>check p vs) cs 
+  let results = map (\p>check p vs) cs 
return $ and (map (maybe partial id) results) 
return $ and (map (maybe partial id) results) 

 Return only the variable bindings that are complete consistent solutions. 
 Return only the variable bindings that are complete consistent solutions. 

getFinalVars :: NDS Variables 
getFinalVars :: NDS Variables 

−  getFinalVars = do c < isConsistent False 
+  getFinalVars = do c < isConsistent False 
guard c 
guard c 

gets vars 
gets vars 

Line 2,437:  Line 2,005:  
 an initial problem state and then returning the first solution in the result list, 
 an initial problem state and then returning the first solution in the result list, 

 or Nothing if there was no solution. 
 or Nothing if there was no solution. 

−  getSolution :: NDS a > ProblemState > Maybe a 
+  getSolution :: NDS a > ProblemState > Maybe a 
getSolution c i = listToMaybe (evalStateT c i) 
getSolution c i = listToMaybe (evalStateT c i) 

 Get a list of all possible solutions to the problem by evaluating the solver 
 Get a list of all possible solutions to the problem by evaluating the solver 

 computation with an initial problem state. 
 computation with an initial problem state. 

−  getAllSolutions :: NDS a > ProblemState > [a] 
+  getAllSolutions :: NDS a > ProblemState > [a] 
−  getAllSolutions c i = evalStateT c i</pre> 
+  getAllSolutions c i = evalStateT c i 
+  </haskell> 

We are ready to apply the predicate language and stateful nondeterministic monad to solving a logic problem. For this example, we will use the wellknown Kalotan puzzle which appeared in ''Mathematical BrainTeasers'', Dover Publications (1976), by J. A. H. Hunter. 
We are ready to apply the predicate language and stateful nondeterministic monad to solving a logic problem. For this example, we will use the wellknown Kalotan puzzle which appeared in ''Mathematical BrainTeasers'', Dover Publications (1976), by J. A. H. Hunter. 

Line 2,451:  Line 2,019:  
Code available in [[../examples/example24.hsexample24.hs]] 
Code available in [[../examples/example24.hsexample24.hs]] 

−  <pre> if a male says something, it must be true 
+  <haskell> 
−  said :: Var > Predicate > Predicate 
+   if a male says something, it must be true 
−  said v p = (v `Is` "male") `implies` p 
+  said :: Var > Predicate > Predicate 
+  said v p = (v `Is` "male") `implies` p 

 if a male says two things, they must be true 
 if a male says two things, they must be true 

 if a female says two things, one must be true and one must be false 
 if a female says two things, one must be true and one must be false 

−  saidBoth :: Var > Predicate > Predicate > Predicate 
+  saidBoth :: Var > Predicate > Predicate > Predicate 
−  saidBoth v p1 p2 = And ((v `Is` "male") `implies` (p1 `And` p2)) 
+  saidBoth v p1 p2 = And ((v `Is` "male") `implies` (p1 `And` p2)) 
−  ((v `Is` "female") `implies` (p1 `orElse` p2)) 
+  ((v `Is` "female") `implies` (p1 `orElse` p2)) 
 lying is saying something is true when it isn't or saying something isn't true when it is 
 lying is saying something is true when it isn't or saying something isn't true when it is 

−  lied :: Var > Predicate > Predicate 
+  lied :: Var > Predicate > Predicate 
lied v p = ((v `said` p) `And` (Not p)) `orElse` ((v `said` (Not p)) `And` p) 
lied v p = ((v `said` p) `And` (Not p)) `orElse` ((v `said` (Not p)) `And` p) 

 Test consistency over all allowed settings of the variable. 
 Test consistency over all allowed settings of the variable. 

−  tryAllValues :: Var > NDS () 
+  tryAllValues :: Var > NDS () 
−  tryAllValues var = do (setVar var "male") `mplus` (setVar var "female") 
+  tryAllValues var = do (setVar var "male") `mplus` (setVar var "female") 
−  c < isConsistent True 
+  c < isConsistent True 
−  guard c</pre> 
+  guard c 
+  </haskell> 

All that remains to be done is to define the puzzle in the predicate language and get a solution that satisfies all of the predicates: 
All that remains to be done is to define the puzzle in the predicate language and get a solution that satisfies all of the predicates: 

Code available in [[../examples/example24.hsexample24.hs]] 
Code available in [[../examples/example24.hsexample24.hs]] 

−  <pre> Define the problem, try all of the variable assignments and print a solution. 
+  <haskell> 
+   Define the problem, try all of the variable assignments and print a solution. 

main :: IO () 
main :: IO () 

main = do let variables = [] 
main = do let variables = [] 

−  constraints = [ Not (Equal "parent1" "parent2"), 
+  constraints = [ Not (Equal "parent1" "parent2"), 
−  "parent1" `said` ("child" `said` ("child" `Is` "male")), 
+  "parent1" `said` ("child" `said` ("child" `Is` "male")), 
−  saidBoth "parent2" ("child" `Is` "female") 
+  saidBoth "parent2" ("child" `Is` "female") 
−  ("child" `lied` ("child" `Is` "male")) ] 
+  ("child" `lied` ("child" `Is` "male")) ] 
problem = PS variables constraints 
problem = PS variables constraints 

−  print $ (`getSolution` problem) $ do tryAllValues "parent1" 
+  print $ (`getSolution` problem) $ do tryAllValues "parent1" 
−  tryAllValues "parent2" 
+  tryAllValues "parent2" 
−  tryAllValues "child" 
+  tryAllValues "child" 
−  getFinalVars</pre> 
+  getFinalVars 
−  Each call to <tt>tryAllValues</tt> will fork the solution space, assigning the named variable to be <tt>"male"</tt> in one fork and <tt>"female"</tt> in the other. The forks which produce inconsistent variable assignments are eliminated (using the <tt>guard</tt> function). The call to <tt>getFinalVars</tt> applies <tt>guard</tt> again to eliminate inconsistent variable assignments and returns the remaining assignments as the value of the computation. 
+  </haskell> 
−  +  Each call to <code>tryAllValues</code> will fork the solution space, assigning the named variable to be <code>"male"</code> in one fork and <code>"female"</code> in the other. The forks which produce inconsistent variable assignments are eliminated (using the <code>guard</code> function). The call to <code>getFinalVars</code> applies <code>guard</code> again to eliminate inconsistent variable assignments and returns the remaining assignments as the value of the computation. 

−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[xformeranatomy.htmlAnatomy of a monad transformer]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[stacking.htmlManaging the transformer stack]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Managing the transformer stack 
Managing the transformer stack 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[xformerexamples.htmlMore examples with monad transformers]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[beyond.htmlContinuing Exploration]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Managing the transformer stack = 
= Managing the transformer stack = 

−  
−  * [[#orderSelecting the correct order]] 

−  * [[#exampleAn example with multiple transformers]] 

−  * [[#liftingHeavy lifting]] 

−  
−  
−   

As the number of monads combined together increases, it becomes increasingly important to manage the stack of monad transformers well. 
As the number of monads combined together increases, it becomes increasingly important to manage the stack of monad transformers well. 

Line 2,514:  Line 2,065:  
== Selecting the correct order == 
== Selecting the correct order == 

−  Once you have decided on the monad features you need, you must choose the correct order in which to apply the monad transformers to achieve the results you want. For instance you may know that you want a combined monad that is an instance of <tt>MonadError</tt> and <tt>MonadState</tt>, but should you apply <tt>StateT</tt> to the <tt>Error</tt> monad or <tt>ErrorT</tt> to the <tt>State</tt> monad? 
+  Once you have decided on the monad features you need, you must choose the correct order in which to apply the monad transformers to achieve the results you want. For instance you may know that you want a combined monad that is an instance of <code>MonadError</code> and <code>MonadState</code>, but should you apply <code>StateT</code> to the <code>Error</code> monad or <code>ErrorT</code> to the <code>State</code> monad? 
−  The decision depends on the exact semantics you want for your combined monad. Applying <tt>StateT</tt> to the <tt>Error</tt> monad gives a state transformer function of type <tt>s > Error e (a,s)</tt>. Applying <tt>ErrorT</tt> to the <tt>State</tt> monad gives a state transformer function of type <tt>s > (Error e a,s)</tt>. Which order to choose depends on the role of errors in your computation. If an error means no state could be produced, you would apply <tt>StateT</tt> to <tt>Error</tt>. If an error means no value could be produced, but the state remains valid, then you would apply <tt>ErrorT</tt> to <tt>State</tt>. 
+  The decision depends on the exact semantics you want for your combined monad. Applying <code>StateT</code> to the <code>Error</code> monad gives a state transformer function of type <code>s > Error e (a,s)</code>. Applying <code>ErrorT</code> to the <code>State</code> monad gives a state transformer function of type <code>s > (Error e a,s)</code>. Which order to choose depends on the role of errors in your computation. If an error means no state could be produced, you would apply <code>StateT</code> to <code>Error</code>. If an error means no value could be produced, but the state remains valid, then you would apply <code>ErrorT</code> to <code>State</code>. 
Choosing the correct order requires understanding the transformation carried out by each monad transformer, and how that transformation affects the semantics of the combined monad. 
Choosing the correct order requires understanding the transformation carried out by each monad transformer, and how that transformation affects the semantics of the combined monad. 

Line 2,522:  Line 2,073:  
== An example with multiple transformers == 
== An example with multiple transformers == 

−  The following example demonstrates the use of multiple monad transformers. The code uses the StateT monad transformer along with the List monad to produce a combined monad for doing stateful nondeterministic computations. In this case, however, we have added the <tt>WriterT</tt> monad transformer to perform logging during the computation. The problem we will apply this monad to is the famous Nqueens problem: to place N queens on a chess board so that no queen can attack another. 
+  The following example demonstrates the use of multiple monad transformers. The code uses the StateT monad transformer along with the List monad to produce a combined monad for doing stateful nondeterministic computations. In this case, however, we have added the <code>WriterT</code> monad transformer to perform logging during the computation. The problem we will apply this monad to is the famous Nqueens problem: to place N queens on a chess board so that no queen can attack another. 
−  The first decision is in what order to apply the monad transformers. <tt>StateT s (WriterT w [])</tt> yields a type like: <tt>s > [((a,s),w)]</tt>. <tt>WriterT w (StateT s [])</tt> yields a type like: <tt>s > [((a,w),s)]</tt>. In this case, there is little difference between the two orders, so we will choose the second arbitrarily. 
+  The first decision is in what order to apply the monad transformers. <code>StateT s (WriterT w [])</code> yields a type like: <code>s > [((a,s),w)]</code>. <code>WriterT w (StateT s [])</code> yields a type like: <code>s > [((a,w),s)]</code>. In this case, there is little difference between the two orders, so we will choose the second arbitrarily. 
−  Our combined monad is an instance of both <tt>MonadState</tt> and <tt>MonadWriter</tt>, so we can freely mix use of <tt>get</tt>, <tt>put</tt>, and <tt>tell</tt> in our monadic computations. 
+  Our combined monad is an instance of both <code>MonadState</code> and <code>MonadWriter</code>, so we can freely mix use of <code>get</code>, <code>put</code>, and <code>tell</code> in our monadic computations. 
Code available in [[../examples/example25.hsexample25.hs]] 
Code available in [[../examples/example25.hsexample25.hs]] 

−  <pre> this is the type of our problem description 
+  <haskell> 
+   this is the type of our problem description 

data NQueensProblem = NQP {board::Board, 
data NQueensProblem = NQP {board::Board, 

ranks::[Rank], files::[File], 
ranks::[Rank], files::[File], 

Line 2,536:  Line 2,087:  
 initial state = empty board, all ranks, files, and diagonals free 
 initial state = empty board, all ranks, files, and diagonals free 

−  initialState = let fileA = map (\r>Pos A r) [1..8] 
+  initialState = let fileA = map (\r>Pos A r) [1..8] 
−  rank8 = map (\f>Pos f 8) [A .. H] 
+  rank8 = map (\f>Pos f 8) [A .. H] 
−  rank1 = map (\f>Pos f 1) [A .. H] 
+  rank1 = map (\f>Pos f 1) [A .. H] 
asc = map Ascending (nub (fileA ++ rank1)) 
asc = map Ascending (nub (fileA ++ rank1)) 

desc = map Descending (nub (fileA ++ rank8)) 
desc = map Descending (nub (fileA ++ rank8)) 

Line 2,549:  Line 2,100:  
 an initial problem state and then returning the first solution in the result list, 
 an initial problem state and then returning the first solution in the result list, 

 or Nothing if there was no solution. 
 or Nothing if there was no solution. 

−  getSolution :: NDS a > NQueensProblem > Maybe (a,[String]) 
+  getSolution :: NDS a > NQueensProblem > Maybe (a,[String]) 
getSolution c i = listToMaybe (evalStateT (runWriterT c) i) 
getSolution c i = listToMaybe (evalStateT (runWriterT c) i) 

 add a Queen to the board in a specific position 
 add a Queen to the board in a specific position 

−  addQueen :: Position > NDS () 
+  addQueen :: Position > NDS () 
−  addQueen p = do (Board b) < gets board 
+  addQueen p = do (Board b) < gets board 
−  rs < gets ranks 
+  rs < gets ranks 
−  fs < gets files 
+  fs < gets files 
−  as < gets asc 
+  as < gets asc 
−  ds < gets desc 
+  ds < gets desc 
let b' = (Piece Black Queen, p):b 
let b' = (Piece Black Queen, p):b 

rs' = delete (rank p) rs 
rs' = delete (rank p) rs 

Line 2,565:  Line 2,116:  
as' = delete a as 
as' = delete a as 

ds' = delete d ds 
ds' = delete d ds 

−  tell ["Added Queen at " ++ (show p)] 
+  tell ["Added Queen at " ++ (show p)] 
put (NQP (Board b') rs' fs' as' ds') 
put (NQP (Board b') rs' fs' as' ds') 

 test if a position is in the set of allowed diagonals 
 test if a position is in the set of allowed diagonals 

−  inDiags :: Position > NDS Bool 
+  inDiags :: Position > NDS Bool 
inDiags p = do let (a,d) = getDiags p 
inDiags p = do let (a,d) = getDiags p 

−  as < gets asc 
+  as < gets asc 
−  ds < gets desc 
+  ds < gets desc 
−  return $ (elem a as) && (elem d ds) 
+  return $ (elem a as) && (elem d ds) 
 add a Queen to the board in all allowed positions 
 add a Queen to the board in all allowed positions 

addQueens :: NDS () 
addQueens :: NDS () 

−  addQueens = do rs < gets ranks 
+  addQueens = do rs < gets ranks 
−  fs < gets files 
+  fs < gets files 
−  allowed < filterM inDiags [Pos f r  f < fs, r < rs] 
+  allowed < filterM inDiags [Pos f r  f < fs, r < rs] 
−  tell [show (length allowed) ++ " possible choices"] 
+  tell [show (length allowed) ++ " possible choices"] 
msum (map addQueen allowed) 
msum (map addQueen allowed) 

Line 2,586:  Line 2,137:  
 then get the board and print the solution along with the log 
 then get the board and print the solution along with the log 

main :: IO () 
main :: IO () 

−  main = do args < getArgs 
+  main = do args < getArgs 
let n = read (args!!0) 
let n = read (args!!0) 

cmds = replicate n addQueens 
cmds = replicate n addQueens 

Line 2,592:  Line 2,143:  
gets board 
gets board 

case sol of 
case sol of 

−  Just (b,l) > do putStr $ show b  show the solution 
+  Just (b,l) > do putStr $ show b  show the solution 
putStr $ unlines l  show the log 
putStr $ unlines l  show the log 

−  Nothing > putStrLn "No solution"</pre> 
+  Nothing > putStrLn "No solution" 
−  The program operates in a similar manner to the previous example, which solved the kalotan puzzle. In this example, however, we do not test for consistency using the <tt>guard</tt> function. Instead, we only create branches that correspond to allowed queen positions. We use the added logging facility to log the number of possible choices at each step and the position in which the queen was placed. 
+  </haskell> 
+  The program operates in a similar manner to the previous example, which solved the kalotan puzzle. In this example, however, we do not test for consistency using the <code>guard</code> function. Instead, we only create branches that correspond to allowed queen positions. We use the added logging facility to log the number of possible choices at each step and the position in which the queen was placed. 

== Heavy lifting == 
== Heavy lifting == 

Line 2,601:  Line 2,152:  
There is one subtle problem remaining with our use of multiple monad transformers. Did you notice that all of the computations in the previous example are done in the combined monad, even if they only used features of one monad? The code for these functions in tied unneccessarily to the definition of the combined monad, which decreases their reusability. 
There is one subtle problem remaining with our use of multiple monad transformers. Did you notice that all of the computations in the previous example are done in the combined monad, even if they only used features of one monad? The code for these functions in tied unneccessarily to the definition of the combined monad, which decreases their reusability. 

−  This is where the <tt>lift</tt> function from the <tt>MonadTrans</tt> class comes into its own. The <tt>lift</tt> function gives us the ability to write our code in a clear, modular, reusable manner and then lift the computations into the combined monad as needed. 
+  This is where the <code>lift</code> function from the <code>MonadTrans</code> class comes into its own. The <code>lift</code> function gives us the ability to write our code in a clear, modular, reusable manner and then lift the computations into the combined monad as needed. 
Instead of writing brittle code like: 
Instead of writing brittle code like: 

−  <pre>logString :: String > StateT MyState (WriterT [String] []) Int 
+  <haskell> 
−  logString s = ...</pre> 
+  logString :: String > StateT MyState (WriterT [String] []) Int 
+  logString s = ... 

+  </haskell> 

we can write clearer, more flexible code like: 
we can write clearer, more flexible code like: 

−  <pre>logString :: (MonadWriter [String] m) => String > m Int 
+  <haskell> 
−  logString s = ...</pre> 
+  logString :: (MonadWriter [String] m) => String > m Int 
−  and then lift the <tt>logString</tt> computation into the combined monad when we use it. 
+  logString s = ... 
+  </haskell> 

+  and then lift the <code>logString</code> computation into the combined monad when we use it. 

−  [[Image:info.png]] You may need to use the compiler flags <tt>fglasgowexts</tt> with GHC or the equivalent flags with your Haskell compiler to use this technique. The issue is that <tt>m</tt> in the constraint above is a type constructor, not a type, and this is not supported in standard Haskell 98. <br /> 
+  [[Image:info.png]] You may need to use the compiler flags <code>fglasgowexts</code> with GHC or the equivalent flags with your Haskell compiler to use this technique. The issue is that <code>m</code> in the constraint above is a type constructor, not a type, and this is not supported in standard Haskell 98. <br /> 
−  When using lifting with complex transformer stacks, you may find yourself composing multiple lifts, like <tt>lift . lift . lift $ f x</tt>. This can become hard to follow, and if the transformer stack changes (perhaps you add <tt>ErrorT</tt> into the mix) the lifting may need to be changed all over the code. A good practice to prevent this is to declare helper functions with informative names to do the lifting: 
+  When using lifting with complex transformer stacks, you may find yourself composing multiple lifts, like <code>lift . lift . lift $ f x</code>. This can become hard to follow, and if the transformer stack changes (perhaps you add <code>ErrorT</code> into the mix) the lifting may need to be changed all over the code. A good practice to prevent this is to declare helper functions with informative names to do the lifting: 
−  <pre>liftListToState = lift . lift . lift</pre> 
+  <haskell> 
+  liftListToState = lift . lift . lift 

+  </haskell> 

Then, the code is more informative and if the transformer stack changes, the impact on the lifting code is confined to a small number of these helper functions. 
Then, the code is more informative and if the transformer stack changes, the impact on the lifting code is confined to a small number of these helper functions. 

Line 2,625:  Line 2,176:  
Code available in [[../examples/example26.hsexample26.hs]] 
Code available in [[../examples/example26.hsexample26.hs]] 

−  <pre> this is our combined monad type for this problem 
+  <haskell> 
+   this is our combined monad type for this problem 

type NDS a = StateT Int (WriterT [String] []) a 
type NDS a = StateT Int (WriterT [String] []) a 

Line 2,631:  Line 2,182:  
 return the digits of a number as a list 
 return the digits of a number as a list 

−  getDigits :: Int > [Int] 
+  getDigits :: Int > [Int] 
getDigits n = let s = (show n) 
getDigits n = let s = (show n) 

in map digitToInt s 
in map digitToInt s 

Line 2,638:  Line 2,189:  
 write a value to a log and return that value 
 write a value to a log and return that value 

−  logVal :: (MonadWriter [String] m) => Int > m Int 
+  logVal :: (MonadWriter [String] m) => Int > m Int 
−  logVal n = do tell ["logVal: " ++ (show n)] 
+  logVal n = do tell ["logVal: " ++ (show n)] 
return n 
return n 

 do a logging computation and return the length of the log it wrote 
 do a logging computation and return the length of the log it wrote 

−  getLogLength :: (MonadWriter [[a]] m) => m b > m Int 
+  getLogLength :: (MonadWriter [[a]] m) => m b > m Int 
−  getLogLength c = do (_,l) < listen $ c 
+  getLogLength c = do (_,l) < listen $ c 
return (length (concat l)) 
return (length (concat l)) 

 log a string value and return 0 
 log a string value and return 0 

−  logString :: (MonadWriter [String] m) => String > m Int 
+  logString :: (MonadWriter [String] m) => String > m Int 
−  logString s = do tell ["logString: " ++ s] 
+  logString s = do tell ["logString: " ++ s] 
return 0 
return 0 

{ Here is a computation that requires a WriterT [String] [] } 
{ Here is a computation that requires a WriterT [String] [] } 

−   "Fork" the computation and log each list item in a different branch. 
+   "Fork" the computation and log each list item in a different branch. 
−  logEach :: (Show a) => [a] > WriterT [String] [] a 
+  logEach :: (Show a) => [a] > WriterT [String] [] a 
−  logEach xs = do x < lift xs 
+  logEach xs = do x < lift xs 
−  tell ["logEach: " ++ (show x)] 
+  tell ["logEach: " ++ (show x)] 
return x 
return x 

Line 2,663:  Line 2,214:  
 increment the state by a specified value 
 increment the state by a specified value 

−  addVal :: (MonadState Int m) => Int > m () 
+  addVal :: (MonadState Int m) => Int > m () 
−  addVal n = do x < get 
+  addVal n = do x < get 
put (x+n) 
put (x+n) 

Line 2,670:  Line 2,221:  
 set the state to a given value, and log that value 
 set the state to a given value, and log that value 

−  setVal :: Int > NDS () 
+  setVal :: Int > NDS () 
−  setVal n = do x < lift $ logVal n 
+  setVal n = do x < lift $ logVal n 
put x 
put x 

−   "Fork" the computation, adding a different digit to the state in each branch. 
+   "Fork" the computation, adding a different digit to the state in each branch. 
 Because setVal is used, the new values are logged as well. 
 Because setVal is used, the new values are logged as well. 

−  addDigits :: Int > NDS () 
+  addDigits :: Int > NDS () 
−  addDigits n = do x < get 
+  addDigits n = do x < get 
−  y < lift . lift $ getDigits n 
+  y < lift . lift $ getDigits n 
setVal (x+y) 
setVal (x+y) 

{ an equivalent construction is: 
{ an equivalent construction is: 

−  addDigits :: Int > NDS () 
+  addDigits :: Int > NDS () 
−  addDigits n = do x < get 
+  addDigits n = do x < get 
−  msum (map (\i>setVal (x+i)) (getDigits n)) 
+  msum (map (\i>setVal (x+i)) (getDigits n)) 
} 
} 

Line 2,692:  Line 2,243:  
lifting logic are confined to a small number of functions. 
lifting logic are confined to a small number of functions. 

} 
} 

−  liftListToNDS :: [a] > NDS a 
+  liftListToNDS :: [a] > NDS a 
liftListToNDS = lift . lift 
liftListToNDS = lift . lift 

Line 2,698:  Line 2,249:  
 monads as necessary. 
 monads as necessary. 

main :: IO () 
main :: IO () 

−  main = do mapM_ print $ runWriterT $ (`evalStateT` 0) $ do x < lift $ getLogLength $ logString "hello" 
+  main = do mapM_ print $ runWriterT $ (`evalStateT` 0) $ do x < lift $ getLogLength $ logString "hello" 
addDigits x 
addDigits x 

−  x < lift $ logEach [1,3,5] 
+  x < lift $ logEach [1,3,5] 
lift $ logVal x 
lift $ logVal x 

liftListToNDS $ getDigits 287 
liftListToNDS $ getDigits 287 

−  </pre> 
+  
+  </haskell> 

Once you fully understand how the various lifts in the example work and how lifting promotes code reuse, you are ready for realworld monadic programming. All that is left to do is to hone your skills writing real software. Happy hacking! 
Once you fully understand how the various lifts in the example work and how lifting promotes code reuse, you are ready for realworld monadic programming. All that is left to do is to hone your skills writing real software. Happy hacking! 

−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[xformerexamples.htmlMore examples with monad transformers]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[beyond.htmlContinuing Exploration]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Continuing Exploration 
Continuing Exploration 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[stacking.htmlManaging the transformer stack]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[analogy.htmlAppendix I  A physical analogy for monads]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Continuing Exploration = 
= Continuing Exploration = 

−  
−  
−   

This brings us to the end of this tutorial. If you want to continue learning about the mathematical foundations of monads, there are numerous [http://plato.stanford.edu/entries/categorytheory/ category theory] resources on the internet. For more examples of monads and their applications in the real world, you might want to explore the design of the [http://www.cs.uu.nl/people/daan/papers/parsec.html Parsec] monadic parser combinator library and/or the [http://www.math.chalmers.se/~rjmh/QuickCheck/ QuickCheck] testing tool. You may also be interested in [http://www.haskell.org/arrows/ arrows], which are similar to monads but more general. 
This brings us to the end of this tutorial. If you want to continue learning about the mathematical foundations of monads, there are numerous [http://plato.stanford.edu/entries/categorytheory/ category theory] resources on the internet. For more examples of monads and their applications in the real world, you might want to explore the design of the [http://www.cs.uu.nl/people/daan/papers/parsec.html Parsec] monadic parser combinator library and/or the [http://www.math.chalmers.se/~rjmh/QuickCheck/ QuickCheck] testing tool. You may also be interested in [http://www.haskell.org/arrows/ arrows], which are similar to monads but more general. 

If you discover any errors — no matter how small — in this document, or if you have suggestions for how it can be improved, please write to the author at [mailto:jnewbern@yahoo.com jnewbern@yahoo.com]. 
If you discover any errors — no matter how small — in this document, or if you have suggestions for how it can be improved, please write to the author at [mailto:jnewbern@yahoo.com jnewbern@yahoo.com]. 

−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[stacking.htmlManaging the transformer stack]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[analogy.htmlAppendix I  A physical analogy for monads]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

A physical analogy for monads 
A physical analogy for monads 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[standardxformers.htmlStandard monad transformers]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[examples.htmlAppendix II  Haskell code examples]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

= A physical analogy for monads = 
= A physical analogy for monads = 

Line 2,798:  Line 2,300:  
Lets take the example of an assembly line to make chopsticks, and see how it is handled in our physical analogy and how me might represent it as a program in Haskell. We will have three worker machines. The first takes small pieces of wood as input and outputs a tray containing a pair of roughly shaped chopsticks. The second takes a pair of roughly shaped chopsticks and outputs a tray containing a pair of smooth, polished chopsticks with the name of the restaurant printed on them. The third takes a pair of polished chopsticks and outputs a tray containing a finished pair of chopsticks in a printed paper wrapper. We could represent this in Haskell as: 
Lets take the example of an assembly line to make chopsticks, and see how it is handled in our physical analogy and how me might represent it as a program in Haskell. We will have three worker machines. The first takes small pieces of wood as input and outputs a tray containing a pair of roughly shaped chopsticks. The second takes a pair of roughly shaped chopsticks and outputs a tray containing a pair of smooth, polished chopsticks with the name of the restaurant printed on them. The third takes a pair of polished chopsticks and outputs a tray containing a finished pair of chopsticks in a printed paper wrapper. We could represent this in Haskell as: 

−  <pre> the basic types we are dealing with 
+  <haskell> 
+   the basic types we are dealing with 

type Wood = ... 
type Wood = ... 

type Chopsticks = ... 
type Chopsticks = ... 

Line 2,806:  Line 2,308:  
 worker function 1: makes roughly shaped chopsticks 
 worker function 1: makes roughly shaped chopsticks 

−  makeChopsticks :: Wood > Tray Chopsticks 
+  makeChopsticks :: Wood > Tray Chopsticks 
makeChopsticks w = ... 
makeChopsticks w = ... 

 worker function 2: polishes chopsticks 
 worker function 2: polishes chopsticks 

−  polishChopsticks :: Chopsticks > Tray Chopsticks 
+  polishChopsticks :: Chopsticks > Tray Chopsticks 
polishChopsticks c = ... 
polishChopsticks c = ... 

 worker function 3: wraps chopsticks 
 worker function 3: wraps chopsticks 

−  wrapChopsticks :: Chopsticks > Tray Wrapper Chopsticks 
+  wrapChopsticks :: Chopsticks > Tray Wrapper Chopsticks 
−  wrapChopsticks c = ...</pre> 
+  wrapChopsticks c = ... 
−  It is clear that the worker machines contain all of the functionality needed to produce chopsticks. What is missing is the specification of the trays, loader, and combiner machines that collectively make up the Tray monad. Our trays should either be empty or contain a single item. Our loader machine would simply take an item and place it in a tray on the conveyor belt. The combiner machine would take each input tray and pass along empty trays while feeding the contents of nonempty trays to its worker machine. In Haskell, we would define the <tt>Tray</tt> monad as: 
+  </haskell> 
+  It is clear that the worker machines contain all of the functionality needed to produce chopsticks. What is missing is the specification of the trays, loader, and combiner machines that collectively make up the Tray monad. Our trays should either be empty or contain a single item. Our loader machine would simply take an item and place it in a tray on the conveyor belt. The combiner machine would take each input tray and pass along empty trays while feeding the contents of nonempty trays to its worker machine. In Haskell, we would define the <code>Tray</code> monad as: 

−  <pre> trays are either empty or contain a single item 
+  <haskell> 
+   trays are either empty or contain a single item 

data Tray x = Empty  Contains x 
data Tray x = Empty  Contains x 

 Tray is a monad 
 Tray is a monad 

instance Monad Tray where 
instance Monad Tray where 

−  Empty >>= _ = Empty 
+  Empty >>= _ = Empty 
−  (Contains x) >>= worker = worker x 
+  (Contains x) >>= worker = worker x 
return = Contains 
return = Contains 

−  fail _ = Empty </pre> 
+  fail _ = Empty 
−  [[Image:info.png]] You may recognize the <tt>Tray</tt> monad as a disguised version of the <tt>Maybe</tt> monad that is a standard part of Haskell 98 library. <br /> 
+  </haskell> 
+  [[Image:info.png]] You may recognize the <code>Tray</code> monad as a disguised version of the <code>Maybe</code> monad that is a standard part of Haskell 98 library. <br /> 

Line 2,845:  Line 2,347:  
In Haskell, the sequencing can be done using the standard monadic functions: 
In Haskell, the sequencing can be done using the standard monadic functions: 

−  <pre>assemblyLine :: Wood > Tray Wrapped Chopsticks 
+  <haskell> 
−  assemblyLine w = (return w) >>= makeChopsticks >>= polishChopsticks >>= wrapChopsticks</pre> 
+  assemblyLine :: Wood > Tray Wrapped Chopsticks 
+  assemblyLine w = (return w) >>= makeChopsticks >>= polishChopsticks >>= wrapChopsticks 

+  </haskell> 

or using the built in Haskell "do" notation for monads: 
or using the built in Haskell "do" notation for monads: 

−  <pre>assemblyLine :: Wood > Tray Wrapped Chopsticks 
+  <haskell> 
−  assemblyLine w = do c < makeChopsticks w 
+  assemblyLine :: Wood > Tray Wrapped Chopsticks 
−  c' < polishChopsticks c 
+  assemblyLine w = do c < makeChopsticks w 
−  c'' < wrapChopsticks c' 
+  c' < polishChopsticks c 
−  return c''</pre> 
+  c'' < wrapChopsticks c' 
+  return c'' 

+  </haskell> 

So far, you have seen how monads are like a framework for building assembly lines, but you probably haven't been overawed by their utility. To see why we might want to build our assembly line using the monadic approach, consider what would happen if we wanted to change the manufacturing process. 
So far, you have seen how monads are like a framework for building assembly lines, but you probably haven't been overawed by their utility. To see why we might want to build our assembly line using the monadic approach, consider what would happen if we wanted to change the manufacturing process. 

−  Right now, when a worker machine malfunctions, it uses the <tt>fail</tt> routine to produce an empty tray. The <tt>fail</tt> routine takes an argument describing the failure, but our <tt>Tray</tt> type ignores this and simply produces an empty tray. This empty tray travels down the assembly line and the combiner machines allow it to bypass the remaining worker machines. It eventually reaches the end of the assembly line, where it is brought to you, the quality control engineer. It is your job to figure out which machine failed, but all you have to go on is an empty tray. 
+  Right now, when a worker machine malfunctions, it uses the <code>fail</code> routine to produce an empty tray. The <code>fail</code> routine takes an argument describing the failure, but our <code>Tray</code> type ignores this and simply produces an empty tray. This empty tray travels down the assembly line and the combiner machines allow it to bypass the remaining worker machines. It eventually reaches the end of the assembly line, where it is brought to you, the quality control engineer. It is your job to figure out which machine failed, but all you have to go on is an empty tray. 
−  You realize that your job would be much easier if you took advantage of the failure messages that are currently ignored by the <tt>fail</tt> routine in your <tt>Tray</tt> monad. Because your assembly line is organized around a monadic approach, it is easy for you to add this functionality to your assembly line without changing your worker machines. 
+  You realize that your job would be much easier if you took advantage of the failure messages that are currently ignored by the <code>fail</code> routine in your <code>Tray</code> monad. Because your assembly line is organized around a monadic approach, it is easy for you to add this functionality to your assembly line without changing your worker machines. 
To make the change, you simply create a new tray type that can never be empty. It will always either contain an item or it will contain a failure report describing the exact reason there is no item in the tray. 
To make the change, you simply create a new tray type that can never be empty. It will always either contain an item or it will contain a failure report describing the exact reason there is no item in the tray. 

−  <pre> tray2s either contain a single item or contain a failure report 
+  <haskell> 
+   tray2s either contain a single item or contain a failure report 

data Tray2 x = Contains x  Failed String 
data Tray2 x = Contains x  Failed String 

 Tray2 is a monad 
 Tray2 is a monad 

instance Monad Tray2 where 
instance Monad Tray2 where 

−  (Failed reason) >>= _ = Failed reason 
+  (Failed reason) >>= _ = Failed reason 
−  (Contains x) >>= worker = worker x 
+  (Contains x) >>= worker = worker x 
return = Contains 
return = Contains 

−  fail reason = Failed reason</pre> 
+  fail reason = Failed reason 
−  [[Image:info.png]] You may recognize the <tt>Tray2</tt> monad as a disguised version of the <tt>Error</tt> monad that is a standard part of the Haskell 98 libraries.<br /> 
+  </haskell> 
+  [[Image:info.png]] You may recognize the <code>Tray2</code> monad as a disguised version of the <code>Error</code> monad that is a standard part of the Haskell 98 libraries.<br /> 

−  Replacing the <tt>Tray</tt> monad with the <tt>Tray2</tt> monad instantly upgrades your assembly line. Now when a failure occurs, the tray that is brought to the quality control engineer contains a failure report detailing the exact cause of the failure! 
+  Replacing the <code>Tray</code> monad with the <code>Tray2</code> monad instantly upgrades your assembly line. Now when a failure occurs, the tray that is brought to the quality control engineer contains a failure report detailing the exact cause of the failure! 
−  
−  
−   

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[standardxformers.htmlStandard monad transformers]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left">Next: [[examples.htmlAppendix II  Haskell code examples]]</td> 

−  </tr> 

−  </tbody> 

−  </table> 

Haskell code examples 
Haskell code examples 

−  
−  <table> 

−  <tbody> 

−  <tr class="odd"> 

−  <td align="left">Prev: [[analogy.htmlAppendix I  A physical analogy for monads]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left"></td> 

−  </tr> 

−  </tbody> 

−  </table> 

= Haskell code examples = 
= Haskell code examples = 

−  This appendix contains a list of all of the code [[../examples/examples]] supplied with the tutorial. 
+  This appendix contains a list of all of the code [[../examples/examples]] supplied with the tutorial. The source code can be [http://web.archive.org/web/20061210172052/http://www.nomaware.com/monads/html/examples.html found here]. 
== [[../examples/example1.hsExample 1]] == 
== [[../examples/example1.hsExample 1]] == 

Line 2,902:  Line 2,394:  
This example is discussed in the section: [[class.html#example2Doing it with class]]. 
This example is discussed in the section: [[class.html#example2Doing it with class]]. 

−  The example code builds on the first example, and shows how donotation can be used with an instance of the <tt>Monad</tt> class (in this case, <tt>Maybe</tt> is the monad used). 
+  The example code builds on the first example, and shows how donotation can be used with an instance of the <code>Monad</code> class (in this case, <code>Maybe</code> is the monad used). 
== [[../examples/example3.hsExample 3]] == 
== [[../examples/example3.hsExample 3]] == 

Line 2,908:  Line 2,400:  
This example is discussed in the section: [[monadfns.html#example3Monad support in Haskell]]. 
This example is discussed in the section: [[monadfns.html#example3Monad support in Haskell]]. 

−  The example code builds on the first two examples, and shows a somewhat atypical — but very powerful — use of the <tt>foldM</tt> function outside of a doblock. 
+  The example code builds on the first two examples, and shows a somewhat atypical — but very powerful — use of the <code>foldM</code> function outside of a doblock. 
== [[../examples/example4.hsExample 4]] == 
== [[../examples/example4.hsExample 4]] == 

Line 2,914:  Line 2,406:  
This example is discussed in the section: [[monadfns.html#example4Monad support in Haskell]]. 
This example is discussed in the section: [[monadfns.html#example4Monad support in Haskell]]. 

−  The example code shows a more typical use of the <tt>foldM</tt> function within a doblock. It combines dictionary values read from different files into a single dictionary using the <tt>foldM</tt> function within the IO monad. 
+  The example code shows a more typical use of the <code>foldM</code> function within a doblock. It combines dictionary values read from different files into a single dictionary using the <code>foldM</code> function within the IO monad. 
== [[../examples/example5.hsExample 5]] == 
== [[../examples/example5.hsExample 5]] == 

Line 2,920:  Line 2,412:  
This example is discussed in the section: [[monadfns.html#example5Monad support in Haskell]]. 
This example is discussed in the section: [[monadfns.html#example5Monad support in Haskell]]. 

−  The example code shows the use of the <tt>filterM</tt> function within a doblock. It prints the subset of its arguments that specify directories and ignores nondirectory arguments. 
+  The example code shows the use of the <code>filterM</code> function within a doblock. It prints the subset of its arguments that specify directories and ignores nondirectory arguments. 
== [[../examples/example6.hsExample 6]] == 
== [[../examples/example6.hsExample 6]] == 

Line 2,926:  Line 2,418:  
This example is discussed in the section: [[monadfns.html#example6Monad support in Haskell]]. 
This example is discussed in the section: [[monadfns.html#example6Monad support in Haskell]]. 

−  The example code shows the use of the <tt>liftM</tt> function within a doblock. It looks up a name in a list and uses a lifted String manipulation function to modify it within the Maybe monad. 
+  The example code shows the use of the <code>liftM</code> function within a doblock. It looks up a name in a list and uses a lifted String manipulation function to modify it within the Maybe monad. 
== [[../examples/example7.hsExample 7]] == 
== [[../examples/example7.hsExample 7]] == 

Line 2,932:  Line 2,424:  
This example is discussed in the section: [[monadfns.html#example7Monad support in Haskell]]. 
This example is discussed in the section: [[monadfns.html#example7Monad support in Haskell]]. 

−  The example code shows a higherorder application of <tt>liftM2</tt>. It folds lifted operations within the List monad to produce lists of all combinations of elements combined with the lifted operator. 
+  The example code shows a higherorder application of <code>liftM2</code>. It folds lifted operations within the List monad to produce lists of all combinations of elements combined with the lifted operator. 
== [[../examples/example8.hsExample 8]] == 
== [[../examples/example8.hsExample 8]] == 

Line 2,938:  Line 2,430:  
This example is discussed in the section: [[monadfns.html#example8Monad support in Haskell]]. 
This example is discussed in the section: [[monadfns.html#example8Monad support in Haskell]]. 

−  The example code shows a higherorder application of <tt>ap</tt>. It folds <tt>ap</tt> through a list of <tt>Maybe (a>a)</tt> functions to process sequences of commands. 
+  The example code shows a higherorder application of <code>ap</code>. It folds <code>ap</code> through a list of <code>Maybe (a>a)</code> functions to process sequences of commands. 
== [[../examples/example9.hsExample 9]] == 
== [[../examples/example9.hsExample 9]] == 

Line 2,944:  Line 2,436:  
This example is discussed in the section: [[monadfns.html#example9Monad support in Haskell]]. 
This example is discussed in the section: [[monadfns.html#example9Monad support in Haskell]]. 

−  The example code shows the use of <tt>msum</tt> in the Maybe monad to select the first variable match in a stack of binding environments. 
+  The example code shows the use of <code>msum</code> in the Maybe monad to select the first variable match in a stack of binding environments. 
== [[../examples/example10.hsExample 10]] == 
== [[../examples/example10.hsExample 10]] == 

Line 2,950:  Line 2,442:  
This example is discussed in the section: [[monadfns.html#example10Monad support in Haskell]]. 
This example is discussed in the section: [[monadfns.html#example10Monad support in Haskell]]. 

−  The example code shows the use of <tt>guard</tt> in the Maybe monad to select only the records from a list that satisfy a predicate (equivalent to <tt>filter</tt>). 
+  The example code shows the use of <code>guard</code> in the Maybe monad to select only the records from a list that satisfy a predicate (equivalent to <code>filter</code>). 
== [[../examples/example11.hsExample 11]] == 
== [[../examples/example11.hsExample 11]] == 

Line 2,956:  Line 2,448:  
This example is discussed in the section: [[maybemonad.html#exampleThe Maybe monad]]. 
This example is discussed in the section: [[maybemonad.html#exampleThe Maybe monad]]. 

−  The example code shows how to use the <tt>Maybe</tt> monad to build complex queries from simpler queries that may fail to return a result. The specific example used is looking up mail preferences for someone based on either their full name or a nickname. 
+  The example code shows how to use the <code>Maybe</code> monad to build complex queries from simpler queries that may fail to return a result. The specific example used is looking up mail preferences for someone based on either their full name or a nickname. 
== [[../examples/example12.hsExample 12]] == 
== [[../examples/example12.hsExample 12]] == 

Line 2,962:  Line 2,454:  
This example is discussed in the section: [[errormonad.html#exampleThe Error monad]]. 
This example is discussed in the section: [[errormonad.html#exampleThe Error monad]]. 

−  The example code demonstrates the use of the <tt>Either</tt> type constructor as an <tt>Error</tt> monad with a custom error type. The example parses hexadecimal digits and uses the exception handling mechanism of the <tt>Error</tt> monad to provide informative error messages in the event of a parse failure. 
+  The example code demonstrates the use of the <code>Either</code> type constructor as an <code>Error</code> monad with a custom error type. The example parses hexadecimal digits and uses the exception handling mechanism of the <code>Error</code> monad to provide informative error messages in the event of a parse failure. 
== [[../examples/example13.hsExample 13]] == 
== [[../examples/example13.hsExample 13]] == 

Line 2,974:  Line 2,466:  
This example is discussed in the section: [[iomonad.html#exampleThe IO monad]]. 
This example is discussed in the section: [[iomonad.html#exampleThe IO monad]]. 

−  The example code implements a simple version of the standard Unix command "tr". The example demonstrates use of the IO monad including implicit <tt>fail</tt> calls due to pattern matching failures and the use of <tt>catcherror</tt>. 
+  The example code implements a simple version of the standard Unix command "tr". The example demonstrates use of the IO monad including implicit <code>fail</code> calls due to pattern matching failures and the use of <code>catcherror</code>. 
== [[../examples/example15.hsExample 15]] == 
== [[../examples/example15.hsExample 15]] == 

Line 3,034:  Line 2,526:  
This example is discussed in the section: [[standardxformers.html#example3Standard monad transformers]]. 
This example is discussed in the section: [[standardxformers.html#example3Standard monad transformers]]. 

−  The example code uses the <tt>StateT</tt> transformer on the List monad to create a combined monad for doing nondeterministic stateful computations. The example uses the combined monad to solve a logic problem. 
+  The example code uses the <code>StateT</code> transformer on the List monad to create a combined monad for doing nondeterministic stateful computations. The example uses the combined monad to solve a logic problem. 
== [[../examples/example25.hsExample 25]] == 
== [[../examples/example25.hsExample 25]] == 

Line 3,040:  Line 2,532:  
This example is discussed in the section: [[stacking.html#exampleAn example with multiple monad transformers]]. 
This example is discussed in the section: [[stacking.html#exampleAn example with multiple monad transformers]]. 

−  The example code uses the <tt>StateT</tt> and <tt>WriterT</tt> transformers on the List monad to create a combined monad for doing nondeterministic stateful computations with logging. The example uses the combined monad to solve the Nqueens problem. 
+  The example code uses the <code>StateT</code> and <code>WriterT</code> transformers on the List monad to create a combined monad for doing nondeterministic stateful computations with logging. The example uses the combined monad to solve the Nqueens problem. 
== [[../examples/example26.hsExample 26]] == 
== [[../examples/example26.hsExample 26]] == 

Line 3,046:  Line 2,538:  
This example is discussed in the section: [[stacking.html#liftingHeavy lifting]]. 
This example is discussed in the section: [[stacking.html#liftingHeavy lifting]]. 

−  The example code demonstrates the use of the <tt>lift</tt> function and the necessity of managing its use in complex transformer stacks. 
+  The example code demonstrates the use of the <code>lift</code> function and the necessity of managing its use in complex transformer stacks. 
−  +  [[Category:Monad]] 

−   
+  [[Category:Standard classes]] 
−  +  [[Category:Standard libraries]] 

−  <table> 
+  [[Category:Standard packages]] 
−  <tbody> 
+  [[Category:Standard types]] 
−  <tr class="odd"> 
+  [[Category:Tutorials]] 
−  <td align="left">Prev: [[analogy.htmlApendix I  A physical analogy for monads]]</td> 

−  <td align="left">TOC: [[index.htmlContents]]</td> 

−  <td align="left"></td> 

−  </tr> 

−  </tbody> 

−  </table> 
Revision as of 13:53, 29 April 2013
All About Monads is a tutorial on monads and monad transformers and a walkthrough of common monad instances. You can download a PDF version here or here. And here is a version of the article which includes source code.
Attempts are being made at porting the tutorial to this wiki; what you're seeing below is a preview of the result of that effort. If you wish to help out you should fork this GitHub repo rather than edit this page, for now.
Contents 