https://wiki.haskell.org/api.php?action=feedcontributions&user=Kini&feedformat=atomHaskellWiki - User contributions [en]2021-02-25T20:12:26ZUser contributionsMediaWiki 1.27.4https://wiki.haskell.org/index.php?title=Base_package&diff=59836Base package2015-06-03T23:41:37Z<p>Kini: </p>
<hr />
<div>The '''base package''' contains the [[Prelude]] and its support libraries, and a large collection of useful libraries ranging from data structures to parsing combinators and debugging utilities. It is specific to the GHC implementation of Haskell.<br />
<br />
This package includes the following: <br />
<br />
*[[Arrays]]<br />
<br />
*[[Arrow]]s<br />
<br />
*[[Functor]]s<br />
<br />
*[[Maybe]]<br />
<br />
*[[Monad]]s<br />
<br />
and many others.<br />
<br />
== Versions ==<br />
<br />
The base package is shipped alongside the GHC compiler itself, but version numbers for the base package do not match the GHC version number. Here is a table indicating which base package versions ship with which GHC. Data is taken from GHC release notes, and, since base 4.7.0.0, the changelog.md file in the base package's source code. Only GHC versions in which the base package's version number was bumped are listed here. (Last updated Aug 2014.)<br />
<br />
{|<br />
|-<br />
! GHC version<br />
! base version<br />
|-<br />
| 6.10.1 (Nov 2008)<br />
| 4.0.0.0<br />
|-<br />
| 6.10.2 (Apr 2009)<br />
| 4.1.0.0<br />
|-<br />
| 6.12.1 (Dec 2009)<br />
| 4.2.0.0<br />
|-<br />
| 6.12.2 (Apr 2010)<br />
| 4.2.0.1<br />
|-<br />
| 6.12.3 (Jun 2010)<br />
| 4.2.0.2<br />
|-<br />
| 7.0.1 (Nov 2010)<br />
| 4.3.0.0<br />
|-<br />
| 7.0.2 (Mar 2011)<br />
| 4.3.1.0<br />
|-<br />
| 7.2.1 (Aug 2011)<br />
| 4.4.0.0<br />
|-<br />
| 7.2.2 (Nov 2011)<br />
| 4.4.1.0<br />
|-<br />
| 7.4.1 (Feb 2012)<br />
| 4.5.0.0<br />
|-<br />
| 7.4.2 (Jun 2012)<br />
| 4.5.1.0<br />
|-<br />
| 7.6.1 (Sep 2012)<br />
| 4.6.0.0<br />
|-<br />
| 7.6.2 (Jan 2013)<br />
| 4.6.0.1<br />
|-<br />
| 7.8.1 (Apr 2014)<br />
| 4.7.0.0<br />
|-<br />
| 7.8.3 (Jul 2014)<br />
| 4.7.0.1<br />
|-<br />
| 7.8.4 (Dec 2014)<br />
| 4.7.0.2<br />
|-<br />
| 7.10.1 (Mar 2015)<br />
| 4.8.0.0<br />
|}<br />
<br />
See also the [https://hackage.haskell.org/package/base hackage page for the base package].<br />
<br />
[[Category:Standard packages]]</div>Kinihttps://wiki.haskell.org/index.php?title=Base_package&diff=58698Base package2014-08-26T02:41:05Z<p>Kini: /* Versions */</p>
<hr />
<div>The '''base package''' contains the [[Prelude]] and its support libraries, and a large collection of useful libraries ranging from data structures to parsing combinators and debugging utilities. It is specific to the GHC implementation of Haskell.<br />
<br />
This package includes the following: <br />
<br />
*[[Arrays]]<br />
<br />
*[[Arrow]]s<br />
<br />
*[[Functor]]s<br />
<br />
*[[Maybe]]<br />
<br />
*[[Monad]]s<br />
<br />
and many others.<br />
<br />
== Versions ==<br />
<br />
The base package is shipped alongside the GHC compiler itself, but version numbers for the base package do not match the GHC version number. Here is a table indicating which base package versions ship with which GHC. Data is taken from GHC release notes, and, since base 4.7.0.0, the changelog.md file in the base package's source code. Only GHC versions in which the base package's version number was bumped are listed here. (Last updated Aug 2014.)<br />
<br />
{|<br />
|-<br />
! GHC version<br />
! base version<br />
|-<br />
| 6.10.1 (Nov 2008)<br />
| 4.0.0.0<br />
|-<br />
| 6.10.2 (Apr 2009)<br />
| 4.1.0.0<br />
|-<br />
| 6.12.1 (Dec 2009)<br />
| 4.2.0.0<br />
|-<br />
| 6.12.2 (Apr 2010)<br />
| 4.2.0.1<br />
|-<br />
| 6.12.3 (Jun 2010)<br />
| 4.2.0.2<br />
|-<br />
| 7.0.1 (Nov 2010)<br />
| 4.3.0.0<br />
|-<br />
| 7.0.2 (Mar 2011)<br />
| 4.3.1.0<br />
|-<br />
| 7.2.1 (Aug 2011)<br />
| 4.4.0.0<br />
|-<br />
| 7.2.2 (Nov 2011)<br />
| 4.4.1.0<br />
|-<br />
| 7.4.1 (Feb 2012)<br />
| 4.5.0.0<br />
|-<br />
| 7.4.2 (Jun 2012)<br />
| 4.5.1.0<br />
|-<br />
| 7.6.1 (Sep 2012)<br />
| 4.6.0.0<br />
|-<br />
| 7.6.2 (Jan 2013)<br />
| 4.6.0.1<br />
|-<br />
| 7.8.1 (Apr 2014)<br />
| 4.7.0.0<br />
|-<br />
| 7.8.3 (Jul 2014)<br />
| 4.7.0.1<br />
|-<br />
| 7.10.1 (TBA)<br />
| 4.7.1.0<br />
|}<br />
<br />
See also the [https://hackage.haskell.org/package/base hackage page for the base package].<br />
<br />
[[Category:Standard packages]]</div>Kinihttps://wiki.haskell.org/index.php?title=Base_package&diff=58697Base package2014-08-26T02:40:50Z<p>Kini: </p>
<hr />
<div>The '''base package''' contains the [[Prelude]] and its support libraries, and a large collection of useful libraries ranging from data structures to parsing combinators and debugging utilities. It is specific to the GHC implementation of Haskell.<br />
<br />
This package includes the following: <br />
<br />
*[[Arrays]]<br />
<br />
*[[Arrow]]s<br />
<br />
*[[Functor]]s<br />
<br />
*[[Maybe]]<br />
<br />
*[[Monad]]s<br />
<br />
and many others.<br />
<br />
== Versions ==<br />
<br />
The base package is shipped alongside the GHC compiler itself, but version numbers for the base package do not match the GHC version number. Here is a table indicating which base package versions ship with which GHC. Data is taken from GHC release notes, and, since base 4.7.0.0, the changelog.md file in the base package's source code. Only GHC versions in which the base package's version number was bumped are listed here.<br />
<br />
{|<br />
|-<br />
! GHC version<br />
! base version<br />
|-<br />
| 6.10.1 (Nov 2008)<br />
| 4.0.0.0<br />
|-<br />
| 6.10.2 (Apr 2009)<br />
| 4.1.0.0<br />
|-<br />
| 6.12.1 (Dec 2009)<br />
| 4.2.0.0<br />
|-<br />
| 6.12.2 (Apr 2010)<br />
| 4.2.0.1<br />
|-<br />
| 6.12.3 (Jun 2010)<br />
| 4.2.0.2<br />
|-<br />
| 7.0.1 (Nov 2010)<br />
| 4.3.0.0<br />
|-<br />
| 7.0.2 (Mar 2011)<br />
| 4.3.1.0<br />
|-<br />
| 7.2.1 (Aug 2011)<br />
| 4.4.0.0<br />
|-<br />
| 7.2.2 (Nov 2011)<br />
| 4.4.1.0<br />
|-<br />
| 7.4.1 (Feb 2012)<br />
| 4.5.0.0<br />
|-<br />
| 7.4.2 (Jun 2012)<br />
| 4.5.1.0<br />
|-<br />
| 7.6.1 (Sep 2012)<br />
| 4.6.0.0<br />
|-<br />
| 7.6.2 (Jan 2013)<br />
| 4.6.0.1<br />
|-<br />
| 7.8.1 (Apr 2014)<br />
| 4.7.0.0<br />
|-<br />
| 7.8.3 (Jul 2014)<br />
| 4.7.0.1<br />
|-<br />
| 7.10.1 (TBA)<br />
| 4.7.1.0<br />
|}<br />
<br />
See also the [https://hackage.haskell.org/package/base hackage page for the base package].<br />
<br />
[[Category:Standard packages]]</div>Kinihttps://wiki.haskell.org/index.php?title=All_About_Monads&diff=58694All About Monads2014-08-24T14:55:18Z<p>Kini: </p>
<hr />
<div>''All About Monads'' is a tutorial on monads and monad transformers and a walk-through of common monad instances. You can download a PDF version [http://ompldr.org/vY29zdw/All_About_Monads.pdf here] or [http://www.cs.rit.edu/~swm/cs561/All_About_Monads.pdf 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].<br />
<br />
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/all-about-monads this GitHub repo] rather than edit this page, for now.<br />
<br />
= Introduction =<br />
<br />
== What is a monad? ==<br />
<br />
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.<br />
<br />
''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:<br />
<br />
<haskell><br />
data Maybe a = Nothing | Just a<br />
</haskell><br />
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.<br />
<br />
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.html|Part II]].<br />
<br />
== Why should I make the effort to understand monads? ==<br />
<br />
The sheer number of different [http://haskell.cs.yale.edu/bookshelf/#monads monad tutorials] on the internet is a good indication of the difficulty many people have understanding the concept. This is due to the abstract nature of monads and to the fact that they are used in several different capacities, which can confuse the picture of exactly what a monad is and what it is good for.<br />
<br />
In Haskell, monads play a central role in the I/O system. It is not essential to understand monads to do I/O in Haskell, but understanding the I/O monad will improve your code and extend your capabilities.<br />
<br />
For the programmer, monads are useful tools for structuring functional programs. They have three properties that make them especially useful:<br />
<br />
# Modularity - They allow computations to be composed from simpler computations and separate the combination strategy from the actual computations being performed.<br />
# Flexibility - They allow functional programs to be much more adaptable than equivalent programs written without monads. This is because the monad distills the computational strategy into a single place instead of requiring it be distributed throughout the entire program.<br />
# Isolation - They can be used to create imperative-style computational structures which remain safely isolated from the main body of the functional program. This is useful for incorporating side-effects (such as I/O) and state (which violates referential transparency) into a pure functional language like Haskell.<br />
<br />
Each of these features will be revisited later in the tutorial in the context of specific monads.<br />
<br />
= Meet the Monads =<br />
<br />
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.<br />
<br />
== Type constructors ==<br />
<br />
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>:<br />
<br />
<haskell><br />
data Maybe a = Nothing | Just a<br />
</haskell><br />
<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:<br />
<br />
<haskell><br />
country = Just "China"<br />
</haskell><br />
In the same way, you can construct a type by applying the <code>Maybe</code> type constructor to a type:<br />
<br />
<haskell><br />
lookupAge :: DB -> String -> Maybe Int<br />
</haskell><br />
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 &quot;<code>m a</code>&quot; to represent a container of some type holding a value of some type!<br />
<br />
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.<br />
<br />
[[Image:info.png]] If you get messages about &quot;kind errors&quot; from the compiler when working with monads, it means that you are not using the type constructors correctly. <br /><br />
<br />
<br />
== Maybe a monad ==<br />
<br />
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 &quot;<code>m</code>&quot; when discussing monads in general. The function that builds values of that type is traditionally called &quot;<code>return</code>&quot; and the third function is known as &quot;bind&quot; but is written &quot;<code>>>=</code>&quot;. The signatures of the functions are:<br />
<br />
<haskell><br />
-- the type of monad m<br />
data m a = ... <br />
<br />
-- return is a type constructor that creates monad instances <br />
return :: a -> m a<br />
<br />
-- bind is a function that combines a monad instance m a with a computation<br />
-- that produces another monad instance m b from a's to produce a new<br />
-- monad instance m b<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
</haskell><br />
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 &quot;bind&quot; 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.<br />
<br />
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.html|physical analogy of a monad]] before continuing.<br />
<br />
== An example ==<br />
<br />
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!<br />
<br />
We would represent the possibility of not having a mother or father using the <code>Maybe</code> type constructor in our Haskell code:<br />
<br />
<haskell><br />
type Sheep = ...<br />
<br />
father :: Sheep -> Maybe Sheep<br />
father = ...<br />
<br />
mother :: Sheep -> Maybe Sheep<br />
mother = ...<br />
</haskell><br />
Then, defining functions to find grandparents is a little more complicated, because we have to handle the possibility of not having a parent:<br />
<br />
<haskell><br />
maternalGrandfather :: Sheep -> Maybe Sheep<br />
maternalGrandfather s = case (mother s) of<br />
Nothing -> Nothing<br />
Just m -> father m<br />
</haskell><br />
and so on for the other grandparent combinations.<br />
<br />
It gets even worse if we want to find great grandparents:<br />
<br />
<haskell><br />
mothersPaternalGrandfather :: Sheep -> Maybe Sheep<br />
mothersPaternalGrandfather s = case (mother s) of<br />
Nothing -> Nothing<br />
Just m -> case (father m) of<br />
Nothing -> Nothing<br />
Just gf -> father gf<br />
</haskell><br />
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:<br />
<br />
Code available in [[../examples/example1.hs|example1.hs]]<br />
<br />
<haskell><br />
-- comb is a combinator for sequencing operations that return Maybe<br />
comb :: Maybe a -> (a -> Maybe b) -> Maybe b<br />
comb Nothing _ = Nothing<br />
comb (Just x) f = f x<br />
<br />
-- now we can use `comb` to build complicated sequences<br />
mothersPaternalGrandfather :: Sheep -> Maybe Sheep<br />
mothersPaternalGrandfather s = (Just s) `comb` mother `comb` father `comb` father <br />
</haskell><br />
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.<br />
<br />
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.<br />
<br />
== List is also a monad ==<br />
<br />
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.<br />
<br />
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>).<br />
<br />
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.<br />
<br />
Examples of this use of the List monad, and contrasting examples using the Maybe monad will be presented shortly. But first, we must see how useful monads are defined in Haskell.<br />
<br />
== Summary ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
= Doing it with class =<br />
<br />
== Haskell type classes ==<br />
<br />
The discussion in this chapter involves the Haskell type class system. If you are not familiar with type classes in Haskell, you should [http://www.haskell.org/tutorial/classes.html review them] before continuing.<br />
<br />
== The Monad class ==<br />
<br />
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 non-standard function names. It's easy to do and it has many benefits, so just do it!<br />
<br />
The standard <code>Monad</code> class definition in Haskell looks something like this:<br />
<br />
<haskell><br />
class Monad m where<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
return :: a -> m a<br />
</haskell><br />
== Example continued ==<br />
<br />
Continuing the [[meet.html#example1|previous 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.<br />
<br />
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:<br />
<br />
<haskell><br />
instance Monad Maybe where<br />
Nothing >>= f = Nothing<br />
(Just x) >>= f = f x<br />
return = Just<br />
</haskell><br />
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:<br />
<br />
<haskell><br />
-- we can use monadic operations to build complicated sequences<br />
maternalGrandfather :: Sheep -> Maybe Sheep<br />
maternalGrandfather s = (return s) >>= mother >>= father<br />
<br />
fathersMaternalGrandmother :: Sheep -> Maybe Sheep<br />
fathersMaternalGrandmother s = (return s) >>= father >>= mother >>= mother <br />
</haskell><br />
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.<br />
<br />
[[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<br />
<br />
<haskell><br />
doSomething :: (Monad m) => a -> m b<br />
</haskell><br />
is much more flexible than one of the type<br />
<br />
<haskell><br />
doSomething :: a -> Maybe b<br />
</haskell><br />
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.<br />
<br />
== Do notation ==<br />
<br />
Using the standard monadic function names is good, but another advantage of membership in the <code>Monad</code> class is the Haskell support for &quot;do&quot; 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 do-block in Haskell.<br />
<br />
In short, the do notation allows you to write monadic computations using a pseudo-imperative style with named variables. The result of a monadic computation can be &quot;assigned&quot; 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.<br />
<br />
Here is a sample of do notation using the <code>Maybe</code> monad:<br />
<br />
Code available in [[../examples/example2.hs|example2.hs]]<br />
<br />
<haskell><br />
-- we can also use do-notation to build complicated sequences<br />
mothersPaternalGrandfather :: Sheep -> Maybe Sheep<br />
mothersPaternalGrandfather s = do m <- mother s<br />
gf <- father m<br />
father gf<br />
</haskell><br />
Compare this to <code>fathersMaternalGrandmother</code> written above without using do notation.<br />
<br />
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:<br />
<br />
<haskell><br />
mothersPaternalGrandfather s = do { m <- mother s; gf <- father m; father gf }<br />
</haskell><br />
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 imperative-style computations within a larger functional program. This theme will be expanded upon when we deal with side-effects and the I/O monad later.<br />
<br />
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.<br />
<br />
The actual translation from do notation to standard monadic operators is roughly that every expression matched to a pattern, <code>x <- expr1</code>, becomes<br />
<br />
<haskell><br />
expr1 >>= \x -><br />
</haskell><br />
and every expression without a variable assignment, <code>expr2</code> becomes<br />
<br />
<haskell><br />
expr2 >>= \_ -><br />
</haskell><br />
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 &quot;in&quot; keyword). The definition of <code>mothersPaternalGrandfather</code> above would be translated to:<br />
<br />
<haskell><br />
mothersPaternalGrandfather s = mother s >>= (\m -><br />
father m >>= (\gf -><br />
father gf))<br />
</haskell><br />
<br />
(The parentheses are for clarity and aren't actually required.)<br />
<br />
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.<br />
<br />
== Summary ==<br />
<br />
Haskell provides built-in 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 &quot;bind&quot;) functions for the monad.<br />
<br />
A monad that is an instance of the <code>Monad</code> class can be used with do-notation, which is syntactic sugar that provides a simple, imperative-style notation for describing computations with monads.<br />
<br />
= The monad laws =<br />
<br />
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 &quot;the monad axioms&quot;. 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.<br />
<br />
== The three fundamental laws ==<br />
<br />
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:<br />
<br />
# <code>(return x) >>= f == f x</code><br />
# <code>m >>= return == m</code><br />
# <code>(m >>= f) >>= g == m >>= (\x -> f x >>= g)</code><br />
<br />
The first law requires that <code>return</code> is a left-identity with respect to <code>>>=</code>. The second law requires that <code>return</code> is a right-identity 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 do-notation using the monad will be consistent.<br />
<br />
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.<br />
<br />
== Failure IS an option ==<br />
<br />
The definition of the <code>Monad</code> class given [[class.html#monad|earlier]] 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>.<br />
<br />
The default implementation of the <code>fail</code> function is:<br />
<br />
<haskell><br />
fail s = error s<br />
</haskell><br />
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:<br />
<br />
<haskell><br />
fail _ = Nothing<br />
</haskell><br />
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.<br />
<br />
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:<br />
<br />
<haskell><br />
fn :: Int -> Maybe [Int]<br />
fn idx = do let l = [Just [1,2,3], Nothing, Just [], Just [7..20]]<br />
(x:xs) <- l!!idx -- a pattern match failure will call "fail"<br />
return xs<br />
</haskell><br />
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>.<br />
<br />
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>:<br />
<br />
<haskell><br />
(>>) :: m a -> m b -> m b<br />
m >> k = m >>= (\_ -> k)<br />
</haskell><br />
== No way out ==<br />
<br />
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.<br />
<br />
By not requiring such a function, the Haskell <code>Monad</code> class allows the creation of one-way monads. One-way 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.<br />
<br />
The <code>IO</code> monad is a familiar example of a one-way 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 non-monadic values.<br />
<br />
''The wonderful feature of a one-way monad is that it can support side-effects in its monadic operations but prevent them from destroying the functional properties of the non-monadic portions of the program.''<br />
<br />
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 one-way 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 one-way 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 side-effects and non-referentially-transparent functions cannot escape from it.<br />
<br />
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 &quot;run&quot; to provide the answer.<br />
<br />
== Zero and Plus ==<br />
<br />
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:<br />
<br />
# <code>mzero >>= f == mzero</code><br />
# <code>m >>= (\x -> mzero) == mzero</code><br />
# <code>mzero `mplus` m == m</code><br />
# <code>m `mplus` mzero == m</code><br />
<br />
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.<br />
<br />
Monads which have a zero and a plus can be declared as instances of the <code>MonadPlus</code> class in Haskell:<br />
<br />
<haskell><br />
class (Monad m) => MonadPlus m where<br />
mzero :: m a<br />
mplus :: m a -> m a -> m a<br />
</haskell><br />
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>:<br />
<br />
<haskell><br />
instance MonadPlus Maybe where<br />
mzero = Nothing<br />
Nothing `mplus` x = x<br />
x `mplus` _ = x<br />
</haskell><br />
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>.<br />
<br />
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.<br />
<br />
The <code>mplus</code> operator is used to combine monadic values from separate computations into a single monadic value. Within the context of our sheep-cloning 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.<br />
<br />
== Summary ==<br />
<br />
Instances of the <code>Monad</code> class should conform to the so-called 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 do-notation.<br />
<br />
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 do-notation.<br />
<br />
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.<br />
<br />
= Exercises =<br />
<br />
# [[#exercise1|Do notation]]<br />
# [[#exercise2|Combining monadic values]]<br />
# [[#exercise3|Using the List monad]]<br />
# [[#exercise4|Using the Monad class constraint]]<br />
<br />
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 sheep-cloning [[../examples/example2.hs|example]], with which the reader should already be familiar.<br />
<br />
== Exercise 1: Do notation ==<br />
<br />
Rewrite the <code>maternalGrandfather</code>, <code>fathersMaternalGrandmother</code>, and <code>mothersPaternalGrandfather</code> functions in [[../examples/example2.hs|Example 2]] using the monadic operators <code>return</code> and <code>>>=</code>, without using any do-notation syntactic sugar.<br />
<br />
<br />
<br />
Click [[solution1.html|here]] to see the solution.<br />
<br />
== Exercise 2: Combining monadic values ==<br />
<br />
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.<br />
<br />
Click [[solution2.html|here]] to see the solution.<br />
<br />
== Exercise 3: Using the List monad ==<br />
<br />
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.<br />
<br />
Click [[solution3.html|here]] to see the solution.<br />
<br />
== Exercise 4: Using the Monad class constraint ==<br />
<br />
Monads promote modularity and code reuse by encapsulating often-used 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.<br />
<br />
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].<br />
<br />
Click [[solution4.html|here]] to see the solution.<br />
<br />
= Monad support in Haskell =<br />
<br />
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 less-commonly used monad functions. The individual monad types are each in their own libraries and are the subject of [[introII.html|Part II]] of this tutorial.<br />
<br />
== In the standard prelude ==<br />
<br />
The Haskell 98 [http://www.haskell.org/onlinelibrary/standard-prelude.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.<br />
<br />
=== The <code>Monad</code> class ===<br />
<br />
We have seen the <code>Monad</code> class before:<br />
<br />
<haskell><br />
class Monad m where<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
(>>) :: m a -> m b -> m b<br />
return :: a -> m a<br />
fail :: String -> m a<br />
<br />
-- Minimal complete definition:<br />
-- (>>=), return<br />
m >> k = m >>= \_ -> k<br />
fail s = error s<br />
</haskell><br />
=== The sequencing functions ===<br />
<br />
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:<br />
<br />
<haskell><br />
sequence :: Monad m => [m a] -> m [a] <br />
sequence = foldr mcons (return [])<br />
where mcons p q = p >>= \x -> q >>= \y -> return (x:y)<br />
</haskell><br />
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 side-effects of the monadic computations are important.<br />
<br />
<haskell><br />
sequence_ :: Monad m => [m a] -> m () <br />
sequence_ = foldr (>>) (return ())<br />
</haskell><br />
=== The mapping functions ===<br />
<br />
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:<br />
<br />
<haskell><br />
mapM :: Monad m => (a -> m b) -> [a] -> m [b] <br />
mapM f as = sequence (map f as)<br />
</haskell><br />
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 side-effects of the monadic computation are important.<br />
<br />
<haskell><br />
mapM_ :: Monad m => (a -> m b) -> [a] -> m () <br />
mapM_ f as = sequence_ (map f as)<br />
</haskell><br />
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:<br />
<br />
<haskell><br />
putString :: [Char] -> IO ()<br />
putString s = mapM_ putChar s<br />
</haskell><br />
<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 non-monadic version but the function outputs will be within the monad:<br />
<br />
<haskell><br />
-- compare the non-monadic and monadic signatures<br />
map :: (a -> b) -> [a] -> [b]<br />
mapM :: Monad m => (a -> m b) -> [a] -> m [b] <br />
</haskell><br />
=== The reverse binder function (<code>=<<</code>) ===<br />
<br />
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 &quot;<code>>>=</code>&quot;, the reverse binding function is called &quot;<code>=<<</code>&quot;. It is useful in circumstances where the binding operator is used as a higher-order term and it is more convenient to have the arguments in the reversed order. Its definition is simply:<br />
<br />
<haskell><br />
(=<<) :: Monad m => (a -> m b) -> m a -> m b<br />
f =<< x = x >>= f<br />
</haskell><br />
== In the Monad module ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== The <code>MonadPlus</code> class ===<br />
<br />
The <code>Monad</code> module defines the <code>MonadPlus</code> class for monads with a zero element and a plus operator:<br />
<br />
<haskell><br />
class Monad m => MonadPlus m where<br />
mzero :: m a<br />
mplus :: m a -> m a -> m a<br />
</haskell><br />
=== Monadic versions of list functions ===<br />
<br />
Several functions are provided which generalize standard list-processing functions to monads. The <code>mapM</code> functions are exported in the standard prelude and were described above.<br />
<br />
<code>foldM</code> is a monadic version of <code>foldl</code> in which monadic computations built from a list are bound left-to-right. The definition is:<br />
<br />
<haskell><br />
foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a<br />
foldM f a [] = return a<br />
foldM f a (x:xs) = f a x >>= \y -> foldM f y xs<br />
</haskell><br />
but it is easier to understand the operation of <code>foldM</code> if you consider its effect in terms of a do block:<br />
<br />
<haskell><br />
-- this is not valid Haskell code, it is just for illustration<br />
foldM f a1 [x1,x2,...,xn] = do a2 <- f a1 x1<br />
a3 <- f a2 x2<br />
...<br />
f an xn<br />
</haskell><br />
Right-to-left binding is achieved by reversing the input list before calling <code>foldM</code>.<br />
<br />
We can use <code>foldM</code> to create a more poweful query function in our sheep cloning example:<br />
<br />
Code available in [[../examples/example3.hs|example3.hs]]<br />
<br />
<haskell><br />
-- traceFamily is a generic function to find an ancestor<br />
traceFamily :: Sheep -> [ (Sheep -> Maybe Sheep) ] -> Maybe Sheep<br />
traceFamily s l = foldM getParent s l<br />
where getParent s f = f s<br />
<br />
-- we can define complex queries using traceFamily in an easy, clear way<br />
mothersPaternalGrandfather s = traceFamily s [mother, father, father]<br />
paternalGrandmother s = traceFamily s [father, mother]<br />
</haskell><br />
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 &quot;<code>traceFamily s [father, mother]</code>&quot; than it is to use the <code>paternalGrandmother</code> function!<br />
<br />
A more typical use of <code>foldM</code> is within a do block:<br />
<br />
Code available in [[../examples/example4.hs|example4.hs]]<br />
<br />
<haskell><br />
-- a Dict is just a finite map from strings to strings<br />
type Dict = FiniteMap String String<br />
<br />
-- this an auxilliary function used with foldl<br />
addEntry :: Dict -> Entry -> Dict<br />
addEntry d e = addToFM d (key e) (value e)<br />
<br />
-- this is an auxiliiary function used with foldM inside the IO monad<br />
addDataFromFile :: Dict -> Handle -> IO Dict<br />
addDataFromFile dict hdl = do contents <- hGetContents hdl<br />
entries <- return (map read (lines contents))<br />
return (foldl (addEntry) dict entries)<br />
<br />
-- this program builds a dictionary from the entries in all files named on the<br />
-- command line and then prints it out as an association list<br />
main :: IO ()<br />
main = do files <- getArgs<br />
handles <- mapM openForReading files<br />
dict <- foldM addDataFromFile emptyFM handles<br />
print (fmToList dict)<br />
</haskell><br />
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.<br />
<br />
<haskell><br />
filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]<br />
filterM p [] = return []<br />
filterM p (x:xs) = do b <- p x<br />
ys <- filterM p xs<br />
return (if b then (x:ys) else ys)<br />
</haskell><br />
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:<br />
<br />
Code available in [[../examples/example5.hs|example5.hs]]<br />
<br />
<haskell><br />
import Monad<br />
import Directory<br />
import System<br />
<br />
-- NOTE: doesDirectoryExist has type FilePath -> IO Bool<br />
<br />
-- this program prints only the directories named on the command line<br />
main :: IO ()<br />
main = do names <- getArgs<br />
dirs <- filterM doesDirectoryExist names<br />
mapM_ putStrLn dirs<br />
</haskell><br />
<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 side-effects of the monadic computation matter.<br />
<br />
<haskell><br />
zipWithM ::(Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]<br />
zipWithM f xs ys = sequence (zipWith f xs ys)<br />
<br />
zipWithM_ ::(Monad m) => (a -> b -> m c) -> [a] -> [b] -> m ()<br />
zipWithM_ f xs ys = sequence_ (zipWith f xs ys)<br />
</haskell><br />
=== Conditional monadic computations ===<br />
<br />
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 &quot;()&quot; 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>.<br />
<br />
<haskell><br />
when :: (Monad m) => Bool -> m () -> m ()<br />
when p s = if p then s else return ()<br />
<br />
unless :: (Monad m) => Bool -> m () -> m ()<br />
unless p s = when (not p) s<br />
</haskell><br />
=== <code>ap</code> and the lifting functions ===<br />
<br />
''Lifting'' is a monadic operation that converts a non-monadic function into an equivalent function that operates on monadic values. We say that a function is &quot;lifted into the monad&quot; 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.<br />
<br />
The simplest lifting operator is <code>liftM</code>, which lifts a function of a single argument into a monad.<br />
<br />
<haskell><br />
liftM :: (Monad m) => (a -> b) -> (m a -> m b)<br />
liftM f = \a -> do { a' <- a; return (f a') }<br />
</haskell><br />
Lifting operators are also provided for functions with more arguments. <code>liftM2</code> lifts functions of two arguments:<br />
<br />
<haskell><br />
liftM2 :: (Monad m) => (a -> b -> c) -> (m a -> m b -> m c)<br />
liftM2 f = \a b -> do { a' <- a; b' <- b; return (f a' b') }<br />
</haskell><br />
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.<br />
<br />
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:<br />
<br />
<haskell><br />
getName :: String -> Maybe String<br />
getName name = do let db = [("John", "Smith, John"), ("Mike", "Caine, Michael")]<br />
tempName <- lookup name db<br />
return (swapNames tempName)<br />
</haskell><br />
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>:<br />
<br />
Code available in [[../examples/example6.hs|example6.hs]]<br />
<br />
<haskell><br />
getName :: String -> Maybe String<br />
getName name = do let db = [("John", "Smith, John"), ("Mike", "Caine, Michael")]<br />
liftM swapNames (lookup name db)<br />
</haskell><br />
The difference is even greater when lifting functions with more arguments.<br />
<br />
The lifting functions also enable very concise constructions using higher-order functions. To understand this example code, you might need to review the definition of the monad functions for the [[listmonad.html#definition|List monad]] (particularly <code>>>=</code>). Imagine how you might implement this function without lifting the operator:<br />
<br />
Code available in [[../examples/example7.hs|example7.hs]]<br />
<br />
<haskell><br />
-- allCombinations returns a list containing the result of<br />
-- folding the binary operator through all combinations<br />
-- of elements of the given lists<br />
-- For example, allCombinations (+) [[0,1],[1,2,3]] would be<br />
-- [0+1,0+2,0+3,1+1,1+2,1+3], or [1,2,3,2,3,4]<br />
-- and allCombinations (*) [[0,1],[1,2],[3,5]] would be<br />
-- [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]<br />
allCombinations :: (a -> a -> a) -> [[a]] -> [a]<br />
allCombinations fn [] = []<br />
allCombinations fn (l:ls) = foldl (liftM2 fn) l ls<br />
</haskell><br />
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:<br />
<br />
<haskell><br />
ap :: (Monad m) => m (a -> b) -> m a -> m b<br />
ap = liftM2 ($)<br />
</haskell><br />
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 higher-order functions and monads.<br />
<br />
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 higher-order computations:<br />
<br />
Code available in [[../examples/example8.hs|example8.hs]]<br />
<br />
<haskell><br />
-- lookup the commands and fold ap into the command list to<br />
-- compute a result.<br />
main :: IO ()<br />
main = do let fns = [("double",(2*)), ("halve",(`div`2)),<br />
("square",(\x->x*x)), ("negate", negate),<br />
("incr",(+1)), ("decr",(+(-1)))<br />
]<br />
args <- getArgs<br />
let val = read (args!!0)<br />
cmds = map ((flip lookup) fns) (words (args!!1))<br />
print $ foldl (flip ap) (Just val) cmds<br />
</haskell><br />
=== Functions for use with <code>MonadPlus</code> ===<br />
<br />
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:<br />
<br />
<haskell><br />
msum :: MonadPlus m => [m a] -> m a<br />
msum xs = foldr mplus mzero xs<br />
</haskell><br />
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.<br />
<br />
<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:<br />
<br />
Code available in [[../examples/example9.hs|example9.hs]]<br />
<br />
<haskell><br />
type Variable = String<br />
type Value = String<br />
type EnvironmentStack = [[(Variable,Value)]]<br />
<br />
-- lookupVar retrieves a variable's value from the environment stack<br />
-- It uses msum in the Maybe monad to return the first non-Nothing value.<br />
lookupVar :: Variable -> EnvironmentStack -> Maybe Value<br />
lookupVar var stack = msum $ map (lookup var) stack<br />
</haskell><br />
instead of:<br />
<br />
<haskell><br />
lookupVar :: Variable -> EnvironmentStack -> Maybe Value<br />
lookupVar var [] = Nothing<br />
lookupVar var (e:es) = let val = lookup var e<br />
in maybe (lookupVar var es) Just val<br />
</haskell><br />
The second function for use with monads with a zero and a plus is the <code>guard</code> function:<br />
<br />
<haskell><br />
guard :: MonadPlus m => Bool -> m ()<br />
guard p = if p then return () else mzero<br />
</haskell><br />
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>.<br />
<br />
Here is an example demonstrating the use of the <code>guard</code> function in the <code>Maybe</code> monad.<br />
<br />
Code available in [[../examples/example10.hs|example10.hs]]<br />
<br />
<haskell><br />
data Record = Rec {name::String, age::Int} deriving Show<br />
type DB = [Record]<br />
<br />
-- getYoungerThan returns all records for people younger than a specified age.<br />
-- It uses the guard function to eliminate records for ages at or over the limit.<br />
-- This is just for demonstration purposes. In real life, it would be<br />
-- clearer to simply use filter. When the filter criteria are more complex,<br />
-- guard becomes more useful.<br />
getYoungerThan :: Int -> DB -> [Record]<br />
getYoungerThan limit db = mapMaybe (\r -> do { guard (age r < limit); return r }) db<br />
</haskell><br />
== Summary ==<br />
<br />
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 commonly-used (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.<br />
<br />
Part II - Introduction<br />
<br />
= Introduction =<br />
<br />
The monads covered in Part II include a mixture of standard Haskell types that are monads as well as monad classes from Andy Gill's Monad Template Library. The Monad Template Library is included in the Glasgow Haskell Compiler's hierarchical libraries under [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.html Control.Monad]<br />
<br />
Some of the documentation for these monads comes from the excellent [http://www.haskell.org/hawiki Haskell Wiki]. In addition to the monads covered here, monads appear many other places in Haskell, such as the [http://www.cs.uu.nl/people/daan/papers/parsec.html Parsec] monadic combinator parsing library. These monads are beyond the scope of this reference, but they are thoroughly documented on their own. You can get a taste of the Parsec library by looking in the [[../examples/example16.hs|source code]] for [[readermonad.html#example|example 16]].<br />
<br />
<table><br />
<thead><br />
<tr class="header"><br />
<th align="left">Monad</th><br />
<th align="left">Type of computation</th><br />
<th align="left">Combination strategy for <code>>>=</code></th><br />
</tr><br />
</thead><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">[[identitymonad.html|Identity]]</td><br />
<td align="left">''N/A — Used with monad transformers''</td><br />
<td align="left">The bound function is applied to the input value.</td><br />
</tr><br />
<tr class="even"><br />
<td align="left">[[maybemonad.html|Maybe]]</td><br />
<td align="left">Computations which may not return a result</td><br />
<td align="left"><code>Nothing</code> input gives <code>Nothing</code> output<br /><br />
<code>Just x</code> input uses <code>x</code> as input to the bound function.</td><br />
</tr><br />
<tr class="odd"><br />
<td align="left">[[errormonad.html|Error]]</td><br />
<td align="left">Computations which can fail or throw exceptions</td><br />
<td align="left">Failure records information describing the failure. Binding passes failure information on without executing the bound function, or uses successful values as input to the bound function.</td><br />
</tr><br />
<tr class="even"><br />
<td align="left">[[listmonad.html|[] (List)]]</td><br />
<td align="left">Non-deterministic computations which can return multiple possible results</td><br />
<td align="left">Maps the bound function onto the input list and concatenates the resulting lists to get a list of all possible results from all possible inputs.</td><br />
</tr><br />
<tr class="odd"><br />
<td align="left">[[iomonad.html|IO]]</td><br />
<td align="left">Computations which perform I/O</td><br />
<td align="left">Sequential execution of I/O actions in the order of binding.</td><br />
</tr><br />
<tr class="even"><br />
<td align="left">[[statemonad.html|State]]</td><br />
<td align="left">Computations which maintain state</td><br />
<td align="left">The bound function is applied to the input value to produce a state transition function which is applied to the input state.</td><br />
</tr><br />
<tr class="odd"><br />
<td align="left">[[readermonad.html|Reader]]</td><br />
<td align="left">Computations which read from a shared environment</td><br />
<td align="left">The bound function is applied to the value of the input using the same environment.</td><br />
</tr><br />
<tr class="even"><br />
<td align="left">[[writermonad.html|Writer]]</td><br />
<td align="left">Computations which write data in addition to computing values</td><br />
<td align="left">Written data is maintained separately from values. The bound function is applied to the input value and anything it writes is appended to the write data stream.</td><br />
</tr><br />
<tr class="odd"><br />
<td align="left">[[contmonad.html|Cont]]</td><br />
<td align="left">Computations which can be interrupted and restarted</td><br />
<td align="left">The bound function is inserted into the continuation chain.</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Identity monad<br />
<br />
= The Identity monad =<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Simple function application<br />
<br />
Binding strategy:<br />
<br />
The bound function is applied to the input value. <code>Identity x >>= f == Identity (f x)</code><br />
<br />
Useful for:<br />
<br />
Monads can be derived from monad transformers applied to the Identity monad.<br />
<br />
Zero and plus:<br />
<br />
None.<br />
<br />
Example type:<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Identity.html Identity a]<br />
<br />
== Motivation ==<br />
<br />
The Identity monad is a monad that does not embody any computational strategy. It simply applies the bound function to its input without any modification. Computationally, there is no reason to use the Identity monad instead of the much simpler act of simply applying functions to their arguments. The purpose of the Identity monad is its fundamental role in the theory of monad transformers (covered in Part III). Any monad transformer applied to the Identity monad yields a non-transformer version of that monad.<br />
<br />
== Definition ==<br />
<br />
<haskell><br />
newtype Identity a = Identity { runIdentity :: a } <br />
<br />
instance Monad Identity where<br />
return a = Identity a -- i.e. return = id <br />
(Identity x) >>= f = f x -- i.e. x >>= f = f x <br />
</haskell><br />
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.html|State]] monad.<br />
<br />
== Example ==<br />
<br />
A typical use of the Identity monad is to derive a monad from a monad transformer.<br />
<br />
<haskell><br />
-- derive the State monad using the StateT monad transformer<br />
type State s a = StateT s Identity a<br />
</haskell><br />
The Maybe monad<br />
<br />
= The Maybe monad =<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which may return <code>Nothing</code><br />
<br />
Binding strategy:<br />
<br />
<code>Nothing</code> values bypass the bound function, other values are used as inputs to the bound function.<br />
<br />
Useful for:<br />
<br />
Building computations from sequences of functions that may return <code>Nothing</code>. Complex database queries or dictionary lookups are good examples.<br />
<br />
Zero and plus:<br />
<br />
<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>.<br />
<br />
Example type:<br />
<br />
[http://www.haskell.org/onlinelibrary/maybe.html Maybe a]<br />
<br />
== Motivation ==<br />
<br />
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.<br />
<br />
[[Image:info.png]] If you ever find yourself writing code like this:<br /><br />
<br />
<br />
<haskell><br />
case ... of<br />
Nothing -> Nothing<br />
Just x -> case ... of<br />
Nothing -> Nothing<br />
Just y -> ...<br />
</haskell><br />
you should consider using the monadic properties of <code>Maybe</code> to improve the code.<br />
<br />
== Definition ==<br />
<br />
<haskell><br />
data Maybe a = Nothing | Just a<br />
<br />
instance Monad Maybe where<br />
return = Just<br />
fail = Nothing<br />
Nothing >>= f = Nothing<br />
(Just x) >>= f = f x<br />
<br />
instance MonadPlus Maybe where<br />
mzero = Nothing<br />
Nothing `mplus` x = x<br />
x `mplus` _ = x<br />
</haskell><br />
== Example ==<br />
<br />
A common example is in combining dictionary lookups. Given a dictionary that maps full names to email addresses, another that maps nicknames to email addresses, and a third that maps email addresses to email preferences, you could create a function that finds a person's email preferences based on either a full name or a nickname.<br />
<br />
Code available in [[../examples/example11.hs|example11.hs]]<br />
<br />
<haskell><br />
data MailPref = HTML | Plain<br />
data MailSystem = ...<br />
<br />
getMailPrefs :: MailSystem -> String -> Maybe MailPref<br />
getMailPrefs sys name =<br />
do let nameDB = fullNameDB sys<br />
nickDB = nickNameDB sys<br />
prefDB = prefsDB sys<br />
addr <- (lookup name nameDB) `mplus` (lookup name nickDB)<br />
lookup addr prefDB<br />
</haskell><br />
The Error monad<br />
<br />
= The Error monad =<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which may fail or throw exceptions<br />
<br />
Binding strategy:<br />
<br />
Failure records information about the cause/location of the failure. Failure values bypass the bound function, other values are used as inputs to the bound function.<br />
<br />
Useful for:<br />
<br />
Building computations from sequences of functions that may fail or using exception handling to structure error handling.<br />
<br />
Zero and plus:<br />
<br />
Zero is represented by an empty error and the plus operation executes its second argument if the first fails.<br />
<br />
Example type:<br />
<br />
[http://www.haskell.org/onlinelibrary/standard-prelude.html#$tEither Either String a]<br />
<br />
== Motivation ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
== Definition ==<br />
<br />
The definition of the <code>MonadError</code> class below uses multi-parameter 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.<br />
<br />
<haskell><br />
class Error a where<br />
noMsg :: a<br />
strMsg :: String -> a<br />
<br />
class (Monad m) => MonadError e m | m -> e where<br />
throwError :: e -> m a<br />
catchError :: m a -> (e -> m a) -> m a<br />
</haskell><br />
<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:<br />
<br />
<haskell><br />
do { action1; action2; action3 } `catchError` handler <br />
</haskell><br />
where the <code>action</code> functions can call <code>throwError</code>. Note that <code>handler</code> and the do-block must have the same return type.<br />
<br />
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 non-error (right) values.<br />
<br />
<br />
<br />
<haskell><br />
instance MonadError (Either e) where <br />
throwError = Left <br />
(Left e) `catchError` handler = handler e <br />
a `catchError` _ = a <br />
</haskell><br />
== Example ==<br />
<br />
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.<br />
<br />
Code available in [[../examples/example12.hs|example12.hs]]<br />
<br />
<haskell><br />
-- This is the type of our parse error representation.<br />
data ParseError = Err {location::Int, reason::String}<br />
<br />
-- We make it an instance of the Error class<br />
instance Error ParseError where<br />
noMsg = Err 0 "Parse Error"<br />
strMsg s = Err 0 s<br />
<br />
-- For our monad type constructor, we use Either ParseError<br />
-- which represents failure using Left ParseError or a<br />
-- successful result of type a using Right a.<br />
type ParseMonad = Either ParseError<br />
<br />
-- parseHexDigit attempts to convert a single hex digit into<br />
-- an Integer in the ParseMonad monad and throws an error on an<br />
-- invalid character<br />
parseHexDigit :: Char -> Int -> ParseMonad Integer<br />
parseHexDigit c idx = if isHexDigit c then<br />
return (toInteger (digitToInt c))<br />
else<br />
throwError (Err idx ("Invalid character '" ++ [c] ++ "'"))<br />
<br />
-- parseHex parses a string containing a hexadecimal number into<br />
-- an Integer in the ParseMonad monad. A parse error from parseHexDigit<br />
-- will cause an exceptional return from parseHex.<br />
parseHex :: String -> ParseMonad Integer<br />
parseHex s = parseHex' s 0 1<br />
where parseHex' [] val _ = return val<br />
parseHex' (c:cs) val idx = do d <- parseHexDigit c idx<br />
parseHex' cs ((val * 16) + d) (idx + 1)<br />
<br />
-- toString converts an Integer into a String in the ParseMonad monad<br />
toString :: Integer -> ParseMonad String<br />
toString n = return $ show n<br />
<br />
-- convert takes a String containing a hexadecimal representation of<br />
-- a number to a String containing a decimal representation of that<br />
-- number. A parse error on the input String will generate a<br />
-- descriptive error message as the output String.<br />
convert :: String -> String<br />
convert s = let (Right str) = do {n <- parseHex s; toString n} `catchError` printError<br />
in str<br />
where printError e = return $ "At index " ++ (show (location e)) ++ ":" ++ (reason e)<br />
</haskell><br />
The List monad<br />
<br />
= The List monad =<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which may return 0, 1, or more possible results.<br />
<br />
Binding strategy:<br />
<br />
The bound function is applied to all possible values in the input list and the resulting lists are concatenated to produce a list of all possible results.<br />
<br />
Useful for:<br />
<br />
Building computations from sequences of non-deterministic operations. Parsing ambiguous grammars is a common example.<br />
<br />
Zero and plus:<br />
<br />
<code>[]</code> is the zero and <code>++</code> is the plus operation.<br />
<br />
Example type:<br />
<br />
<code>[a]</code><br />
<br />
== Motivation ==<br />
<br />
The List monad embodies the strategy of combining a chain of non-deterministic computations by applying the operations to all possible values at each step. It is useful when computations must deal with ambiguity. In that case it allows all possibilities to be explored until the ambiguity is resolved.<br />
<br />
== Definition ==<br />
<br />
<haskell><br />
instance Monad [] where<br />
m >>= f = concatMap f m<br />
return x = [x]<br />
fail s = []<br />
<br />
instance MonadPlus [] where<br />
mzero = []<br />
mplus = (++)<br />
</haskell><br />
== Example ==<br />
<br />
The canonical example of using the List monad is for parsing ambiguous grammars. The example below shows just a small example of parsing data into hex values, decimal values and words containing only alpha-numeric characters. Note that hexadecimal digits overlap both decimal digits and alphanumeric characters, leading to an ambiguous grammar. &quot;dead&quot; is both a valid hex value and a word, for example, and &quot;10&quot; is both a decimal value of 10 and a hex value of 16.<br />
<br />
Code available in [[../examples/example13.hs|example13.hs]]<br />
<br />
<haskell><br />
-- we can parse three different types of terms<br />
data Parsed = Digit Integer | Hex Integer | Word String deriving Show<br />
<br />
-- attempts to add a character to the parsed representation of a hex digit<br />
parseHexDigit :: Parsed -> Char -> [Parsed]<br />
parseHexDigit (Hex n) c = if isHexDigit c then<br />
return (Hex ((n*16) + (toInteger (digitToInt c))))<br />
else<br />
mzero<br />
parseHexDigit _ _ = mzero<br />
<br />
-- attempts to add a character to the parsed representation of a decimal digit<br />
parseDigit :: Parsed -> Char -> [Parsed]<br />
parseDigit (Digit n) c = if isDigit c then<br />
return (Digit ((n*10) + (toInteger (digitToInt c))))<br />
else<br />
mzero<br />
parseDigit _ _ = mzero<br />
<br />
-- attempts to add a character to the parsed representation of a word<br />
parseWord :: Parsed -> Char -> [Parsed]<br />
parseWord (Word s) c = if isAlpha c then<br />
return (Word (s ++ [c]))<br />
else<br />
mzero<br />
parseWord _ _ = mzero<br />
<br />
-- tries to parse the digit as a hex value, a decimal value and a word<br />
-- the result is a list of possible parses<br />
parse :: Parsed -> Char -> [Parsed]<br />
parse p c = (parseHexDigit p c) `mplus` (parseDigit p c) `mplus` (parseWord p c)<br />
<br />
-- parse an entire String and return a list of the possible parsed values<br />
parseArg :: String -> [Parsed]<br />
parseArg s = do init <- (return (Hex 0)) `mplus` (return (Digit 0)) `mplus` (return (Word ""))<br />
foldM parse init s<br />
</haskell><br />
The IO monad<br />
<br />
= The IO monad =<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which perform I/O<br />
<br />
Binding strategy:<br />
<br />
I/O actions are executed in the order in which they are bound. Failures throw I/O errors which can be caught and handled.<br />
<br />
Useful for:<br />
<br />
Performing I/O within a Haskell program.<br />
<br />
Zero and plus:<br />
<br />
None.<br />
<br />
Example type:<br />
<br />
[http://www.haskell.org/onlinelibrary/io.html IO a]<br />
<br />
== Motivation ==<br />
<br />
Input/Output is incompatible with a pure functional language because it is not referentially transparent and side-effect free. The IO monad solves this problem by confining computations that perform I/O within the IO monad.<br />
<br />
== Definition ==<br />
<br />
The definition of the IO monad is platform-specific. No data constructors are exported and no functions are provided to remove data from the IO monad. This makes the IO monad a one-way monad and is essential to ensuring safety of functional programs by isolating side-effects and non-referentially transparent actions within the imperative-style computations of the IO monad.<br />
<br />
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.<br />
<br />
In Haskell, the top-level <code>main</code> function must have type <code>IO ()</code>, so that programs are typically structured at the top level as an imperative-style sequence of I/O actions and calls to functional-style 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.<br />
<br />
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.<br />
<br />
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>.<br />
<br />
<haskell><br />
instance Monad IO where<br />
return a = ... -- function from a -> IO a<br />
m >>= k = ... -- executes the I/O action m and binds the value to k's input <br />
fail s = ioError (userError s)<br />
<br />
data IOError = ...<br />
<br />
ioError :: IOError -> IO a<br />
ioError = ...<br />
<br />
userError :: String -> IOError<br />
userError = ...<br />
<br />
catch :: IO a -> (IOError -> IO a) -> IO a <br />
catch = ...<br />
<br />
try :: IO a -> IO (Either IOError a)<br />
try f = catch (do r <- f<br />
return (Right r))<br />
(return . Left)<br />
</haskell><br />
The <code>IO</code> monad is incorporated into the Monad Template Library framework as an instance of the <code>MonadError</code> class.<br />
<br />
<haskell><br />
instance Error IOError where<br />
...<br />
<br />
instance MonadError IO where<br />
throwError = ioError<br />
catchError = catch<br />
</haskell><br />
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.<br />
<br />
== Example ==<br />
<br />
This example shows a partial implementation of the &quot;tr&quot; command that copies the standard input stream to the standard output stream with character translations controlled by command-line arguments. It demonstrates the use of the exception handling mechanisms of the <code>MonadError</code> class with the <code>IO</code> monad.<br />
<br />
Code available in [[../examples/example14.hs|example14.hs]]<br />
<br />
<haskell><br />
import Monad<br />
import System<br />
import IO<br />
import Control.Monad.Error<br />
<br />
-- translate char in set1 to corresponding char in set2<br />
translate :: String -> String -> Char -> Char<br />
translate [] _ c = c<br />
translate (x:xs) [] c = if x == c then ' ' else translate xs [] c<br />
translate (x:xs) [y] c = if x == c then y else translate xs [y] c<br />
translate (x:xs) (y:ys) c = if x == c then y else translate xs ys c<br />
<br />
-- translate an entire string<br />
translateString :: String -> String -> String -> String<br />
translateString set1 set2 str = map (translate set1 set2) str<br />
<br />
usage :: IOError -> IO ()<br />
usage e = do putStrLn "Usage: ex14 set1 set2"<br />
putStrLn "Translates characters in set1 on stdin to the corresponding"<br />
putStrLn "characters from set2 and writes the translation to stdout."<br />
<br />
-- translates stdin to stdout based on commandline arguments<br />
main :: IO ()<br />
main = (do [set1,set2] <- getArgs<br />
contents <- hGetContents stdin<br />
putStr $ translateString set1 set2 contents)<br />
`catchError` usage<br />
</haskell><br />
The State monad<br />
<br />
= The State monad =<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which maintain state.<br />
<br />
Binding strategy:<br />
<br />
Binding threads a state parameter through the sequence of bound functions so that the same state value is never used twice, giving the illusion of in-place update.<br />
<br />
Useful for:<br />
<br />
Building computations from sequences of operations that require a shared state.<br />
<br />
Zero and plus:<br />
<br />
None.<br />
<br />
Example type:<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.State.html State st a]<br />
<br />
== Motivation ==<br />
<br />
A pure functional language cannot update values in place because it violates referential transparency. A common idiom to simulate such stateful computations is to &quot;thread&quot; a state parameter through a sequence of functions:<br />
<br />
<haskell><br />
data MyType = MT Int Bool Char Int deriving Show<br />
<br />
makeRandomValue :: StdGen -> (MyType, StdGen)<br />
makeRandomValue g = let (n,g1) = randomR (1,100) g<br />
(b,g2) = random g1<br />
(c,g3) = randomR ('a','z') g2 <br />
(m,g4) = randomR (-n,n) g3<br />
in (MT n b c m, g4)<br />
</haskell><br />
This approach works, but such code can be error-prone, 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.<br />
<br />
== Definition ==<br />
<br />
The definition shown here uses multi-parameter 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.<br />
<br />
<haskell><br />
newtype State s a = State { runState :: (s -> (a,s)) } <br />
<br />
instance Monad (State s) where <br />
return a = State $ \s -> (a,s)<br />
(State x) >>= f = State $ \s -> let (v,s') = x s in runState (f v) s' <br />
</haskell><br />
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>.<br />
<br />
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 right-hand argument to the value and new state from its left-hand argument.<br />
<br />
<haskell><br />
class MonadState m s | m -> s where <br />
get :: m s<br />
put :: s -> m ()<br />
<br />
instance MonadState (State s) s where <br />
get = State $ \s -> (s,s) <br />
put s = State $ \_ -> ((),s) <br />
</haskell><br />
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.<br />
<br />
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.<br />
<br />
== Example ==<br />
<br />
A simple application of the State monad is to thread the random generator state through multiple calls to the generation function.<br />
<br />
Code available in [[../examples/example15.hs|example15.hs]]<br />
<br />
<haskell><br />
data MyType = MT Int Bool Char Int deriving Show<br />
<br />
{- Using the State monad, we can define a function that returns<br />
a random value and updates the random generator state at<br />
the same time.<br />
-}<br />
getAny :: (Random a) => State StdGen a<br />
getAny = do g <- get<br />
(x,g') <- return $ random g<br />
put g'<br />
return x<br />
<br />
-- similar to getAny, but it bounds the random value returned<br />
getOne :: (Random a) => (a,a) -> State StdGen a<br />
getOne bounds = do g <- get<br />
(x,g') <- return $ randomR bounds g<br />
put g'<br />
return x<br />
<br />
{- Using the State monad with StdGen as the state, we can build<br />
random complex types without manually threading the<br />
random generator states through the code.<br />
-} <br />
makeRandomValueST :: StdGen -> (MyType, StdGen)<br />
makeRandomValueST = runState (do n <- getOne (1,100)<br />
b <- getAny<br />
c <- getOne ('a','z')<br />
m <- getOne (-n,n)<br />
return (MT n b c m))<br />
</haskell><br />
The Reader monad<br />
<br />
= The Reader monad =<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which read values from a shared environment.<br />
<br />
Binding strategy:<br />
<br />
Monad values are functions from the environment to a value. The bound function is applied to the bound value, and both have access to the shared environment.<br />
<br />
Useful for:<br />
<br />
Maintaining variable bindings, or other shared environment.<br />
<br />
Zero and plus:<br />
<br />
None.<br />
<br />
Example type:<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Reader.html Reader [(String,Value)] a]<br />
<br />
== Motivation ==<br />
<br />
Some programming problems require computations within a shared environment (such as a set of variable bindings). These computations typically read values from the environment and sometimes execute sub-computations in a modified environment (with new or shadowing bindings, for example), but they do not require the full generality of the State monad.<br />
<br />
The Reader monad is specifically designed for these types of computations and is often a clearer and easier mechanism than using the State monad.<br />
<br />
== Definition ==<br />
<br />
The definition shown here uses multi-parameter 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.<br />
<br />
<haskell><br />
newtype Reader e a = Reader { runReader :: (e -> a) }<br />
<br />
instance Monad (Reader e) where <br />
return a = Reader $ \e -> a <br />
(Reader r) >>= f = Reader $ \e -> runReader (f (r e)) e <br />
</haskell><br />
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.<br />
<br />
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 left-hand side and then applies the bound function to that value in the same environment.<br />
<br />
<haskell><br />
class MonadReader e m | m -> e where <br />
ask :: m e<br />
local :: (e -> e) -> m a -> m a <br />
<br />
instance MonadReader (Reader e) where <br />
ask = Reader id <br />
local f c = Reader $ \e -> runReader c (f e) <br />
<br />
asks :: (MonadReader e m) => (e -> a) -> m a <br />
asks sel = ask >>= return . sel<br />
</haskell><br />
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.<br />
<br />
== Example ==<br />
<br />
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.<br />
<br />
Code available in [[../examples/example16.hs|example16.hs]]<br />
<br />
<haskell><br />
-- This the abstract syntax representation of a template<br />
-- Text Variable Quote Include Compound<br />
data Template = T String | V Template | Q Template | I Template [Definition] | C [Template]<br />
data Definition = D Template Template<br />
<br />
-- Our environment consists of an association list of named templates and<br />
-- an association list of named variable values. <br />
data Environment = Env {templates::[(String,Template)],<br />
variables::[(String,String)]}<br />
<br />
-- lookup a variable from the environment<br />
lookupVar :: String -> Environment -> Maybe String<br />
lookupVar name env = lookup name (variables env)<br />
<br />
-- lookup a template from the environment<br />
lookupTemplate :: String -> Environment -> Maybe Template<br />
lookupTemplate name env = lookup name (templates env)<br />
<br />
-- add a list of resolved definitions to the environment<br />
addDefs :: [(String,String)] -> Environment -> Environment<br />
addDefs defs env = env {variables = defs ++ (variables env)}<br />
<br />
-- resolve a Definition and produce a (name,value) pair<br />
resolveDef :: Definition -> Reader Environment (String,String)<br />
resolveDef (D t d) = do name <- resolve t<br />
value <- resolve d<br />
return (name,value)<br />
<br />
-- resolve a template into a string<br />
resolve :: Template -> Reader Environment (String)<br />
resolve (T s) = return s<br />
resolve (V t) = do varName <- resolve t<br />
varValue <- asks (lookupVar varName)<br />
return $ maybe "" id varValue<br />
resolve (Q t) = do tmplName <- resolve t<br />
body <- asks (lookupTemplate tmplName)<br />
return $ maybe "" show body <br />
resolve (I t ds) = do tmplName <- resolve t<br />
body <- asks (lookupTemplate tmplName)<br />
case body of<br />
Just t' -> do defs <- mapM resolveDef ds<br />
local (addDefs defs) (resolve t')<br />
Nothing -> return ""<br />
resolve (C ts) = (liftM concat) (mapM resolve ts)<br />
</haskell><br />
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>.<br />
<br />
The Writer monad<br />
<br />
= The Writer monad =<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which produce a stream of data in addition to the computed values.<br />
<br />
Binding strategy:<br />
<br />
A Writer monad value is a (computation value, log value) pair. Binding replaces the computation value with the result of applying the bound function to the previous value and appends any log data from the computation to the existing log data.<br />
<br />
Useful for:<br />
<br />
Logging, or other computations that produce output &quot;on the side&quot;.<br />
<br />
Zero and plus:<br />
<br />
None.<br />
<br />
Example type:<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Writer.html Writer [String] a]<br />
<br />
== Motivation ==<br />
<br />
It is often desirable for a computation to generate output &quot;on the side&quot;. Logging and tracing are the most common examples in which data is generated during a computation that we want to retain but is not the primary result of the computation.<br />
<br />
Explicitly managing the logging or tracing data can clutter up the code and invite subtle bugs such as missed log entries. The Writer monad provides a cleaner way to manage the output without cluttering the main computation.<br />
<br />
== Definition ==<br />
<br />
The definition shown here uses multi-parameter 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.<br />
<br />
[[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.<br />
<br />
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!<br />
<br />
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.<br />
<br />
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>.<br />
<br />
The most commonly used standard monoid in Haskell is the list, but functions of type <code>(a -> a)</code> also form a monoid.<br />
<br />
[[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.<br />
<br />
<haskell><br />
newtype Writer w a = Writer { runWriter :: (a,w) } <br />
<br />
instance (Monoid w) => Monad (Writer w) where <br />
return a = Writer (a,mempty) <br />
(Writer (a,w)) >>= f = let (a',w') = runWriter $ f a in Writer (a',w `mappend` w')<br />
</haskell><br />
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.<br />
<br />
<haskell><br />
class (Monoid w, Monad m) => MonadWriter w m | m -> w where <br />
pass :: m (a,w -> w) -> m a <br />
listen :: m a -> m (a,w) <br />
tell :: w -> m () <br />
<br />
instance (Monoid w) => MonadWriter (Writer w) where <br />
pass (Writer ((a,f),w)) = Writer (a,f w) <br />
listen (Writer (a,w)) = Writer ((a,w),w) <br />
tell s = Writer ((),s) <br />
<br />
listens :: (MonadWriter w m) => (w -> b) -> m a -> m (a,b)<br />
listens f m = do (a,w) <- listen m; return (a,f w)<br />
<br />
censor :: (MonadWriter w m) => (w -> w) -> m a -> m a <br />
censor f m = pass $ do a <- m; return (a,f)<br />
</haskell><br />
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 &quot;listen&quot; to the log output generated by a Writer.<br />
<br />
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.<br />
<br />
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.<br />
<br />
== Example ==<br />
<br />
In this example, we imagine a very simple firewall that filters packets based on a rulebase of rules matching the source and destination hosts and the payload of the packet. The firewall's primary job is packet filtering, but we would also like it to produce a log of its activity.<br />
<br />
Code available in [[../examples/example17.hs|example17.hs]]<br />
<br />
<haskell><br />
-- this is the format of our log entries<br />
data Entry = Log {count::Int, msg::String} deriving Eq<br />
<br />
-- add a message to the log<br />
logMsg :: String -> Writer [Entry] ()<br />
logMsg s = tell [Log 1 s]<br />
<br />
-- this handles one packet<br />
filterOne :: [Rule] -> Packet -> Writer [Entry] (Maybe Packet)<br />
filterOne rules packet = do <br />
rule <- return (match rules packet)<br />
case rule of<br />
Nothing -> do<br />
logMsg $ "DROPPING UNMATCHED PACKET: " ++ (show packet)<br />
return Nothing<br />
(Just r) -> do<br />
when (logIt r) $ logMsg ("MATCH: " ++ (show r) ++ " <=> " ++ (show packet))<br />
case r of (Rule Accept _ _) -> return $ Just packet<br />
(Rule Reject _ _) -> return Nothing<br />
</haskell><br />
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 &quot;delayed logging&quot; trick to only add a log entry only after we get a new entry that doesn't match the ones before it.<br />
<br />
Code available in [[../examples/example17.hs|example17.hs]]<br />
<br />
<haskell><br />
-- merge identical entries at the end of the log<br />
-- This function uses [Entry] as both the log type and the result type.<br />
-- When two identical messages are merged, the result is just the message<br />
-- with an incremented count. When two different messages are merged,<br />
-- the first message is logged and the second is returned as the result.<br />
mergeEntries :: [Entry] -> [Entry] -> Writer [Entry] [Entry]<br />
mergeEntries [] x = return x<br />
mergeEntries x [] = return x<br />
mergeEntries [e1] [e2] = let (Log n msg) = e1<br />
(Log n' msg') = e2<br />
in if msg == msg' then<br />
return [(Log (n+n') msg)]<br />
else<br />
do tell [e1]<br />
return [e2]<br />
<br />
-- This is a complex-looking function but it is actually pretty simple.<br />
-- It maps a function over a list of values to get a list of Writers,<br />
-- then runs each writer and combines the results. The result of the function<br />
-- is a writer whose value is a list of all the values from the writers and whose<br />
-- log output is the result of folding the merge operator into the individual<br />
-- log entries (using 'initial' as the initial log value).<br />
groupSame :: (Monoid a) => a -> (a -> a -> Writer a a) -> [b] -> (b -> Writer a c) -> Writer a [c]<br />
groupSame initial merge [] _ = do tell initial<br />
return []<br />
groupSame initial merge (x:xs) fn = do (result,output) <- return (runWriter (fn x))<br />
new <- merge initial output<br />
rest <- groupSame new merge xs fn<br />
return (result:rest)<br />
<br />
-- this filters a list of packets, producing a filtered packet list and a log of<br />
-- the activity in which consecutive messages are merged<br />
filterAll :: [Rule] -> [Packet] -> Writer [Entry] [Packet]<br />
filterAll rules packets = do tell [Log 1 "STARTING PACKET FILTER"]<br />
out <- groupSame [] mergeEntries packets (filterOne rules)<br />
tell [Log 1 "STOPPING PACKET FILTER"]<br />
return (catMaybes out)<br />
</haskell><br />
The Continuation monad<br />
<br />
= The Continuation monad =<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which can be interrupted and resumed.<br />
<br />
Binding strategy:<br />
<br />
Binding a function to a monadic value creates a new continuation which uses the function as the continuation of the monadic computation.<br />
<br />
Useful for:<br />
<br />
Complex control structures, error handling and creating co-routines.<br />
<br />
Zero and plus:<br />
<br />
None.<br />
<br />
Example type:<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Cont.html Cont r a]<br />
<br />
== Motivation ==<br />
<br />
[[Image:warn.png]] Abuse of the Continuation monad can produce code that is impossible to understand and maintain.<br />
<br />
Before using the Continuation monad, be sure that you have a firm understanding of continuation-passing 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.<br />
<br />
Continuations represent the ''future'' of a computation, as a function from an intermediate result to the final result. In continuation-passing 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.<br />
<br />
== Definition ==<br />
<br />
<haskell><br />
newtype Cont r a = Cont { runCont :: ((a -> r) -> r) } -- r is the final result type of the whole computation <br />
<br />
instance Monad (Cont r) where <br />
return a = Cont $ \k -> k a -- i.e. return a = \k -> k a <br />
(Cont c) >>= f = Cont $ \k -> c (\a -> runCont (f a) k) -- i.e. c >>= f = \k -> c (\a -> f a k) <br />
</haskell><br />
The Continuation monad represents computations in continuation-passing 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>.<br />
<br />
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.<br />
<br />
<haskell><br />
class (Monad m) => MonadCont m where <br />
callCC :: ((a -> m b) -> m a) -> m a <br />
<br />
instance MonadCont (Cont r) where <br />
callCC f = Cont $ \k -> runCont (f (\a -> Cont $ \_ -> k a)) k<br />
</haskell><br />
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.<br />
<br />
<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 lambda-expression 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.<br />
<br />
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.<br />
<br />
== Example ==<br />
<br />
This example gives a taste of how escape continuations work. The example function uses escape continuations to perform a complicated transformation on an integer.<br />
<br />
Code available in [[../examples/example18.hs|example18.hs]]<br />
<br />
<haskell><br />
{- We use the continuation monad to perform "escapes" from code blocks.<br />
This function implements a complicated control structure to process<br />
numbers:<br />
<br />
Input (n) Output List Shown<br />
========= ====== ==========<br />
0-9 n none<br />
10-199 number of digits in (n/2) digits of (n/2)<br />
200-19999 n digits of (n/2)<br />
20000-1999999 (n/2) backwards none<br />
>= 2000000 sum of digits of (n/2) digits of (n/2)<br />
-} <br />
fun :: Int -> String<br />
fun n = (`runCont` id) $ do<br />
str <- callCC $ \exit1 -> do -- define "exit1"<br />
when (n < 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' <- callCC $ \exit2 -> do -- define "exit2"<br />
when ((length ns) < 3) (exit2 (length ns))<br />
when ((length ns) < 5) (exit2 n)<br />
when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns') --escape 2 levels<br />
return $ sum ns<br />
return $ "(ns = " ++ (show ns) ++ ") " ++ (show n')<br />
return $ "Answer: " ++ str<br />
</haskell><br />
Part III - Introduction<br />
<br />
= Introduction =<br />
<br />
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, non-determistic 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 sub-computation is performed in a one-way monad.<br />
<br />
Often, the computations can't be performed in isolation. In this case, what is needed is a monad that combines the features of the two monads into a single computation. It is inefficient and poor practice to write a new monad instance with the required characteristics each time a new combination is desired. Instead, we would prefer to develop a way to combine the standard monads to produce the needed hybrids. The technique that lets us do exactly that is called monad transformers.<br />
<br />
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 re-examined.<br />
<br />
Combining monads the hard way<br />
<br />
= Combining monads the hard way =<br />
<br />
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#example|example 18]] (the Continuation monad) to illustrate these issues, so you may want to review it before continuing.<br />
<br />
== Nested Monads ==<br />
<br />
Some computations have a simple enough structure that the monadic computations can be nested, avoiding the need for a combined monad altogether. In Haskell, all computations occur in the IO monad at the top level, so the monad examples we have seen so far all actually use the technique of nested monadic computations. To do this, the computations perform all of their input at the beginning — usually by reading arguments from the command line — then pass the values on to the monadic computations to produce results, and finally perform their output at the end. This structure avoids the issues of combining monads but makes the examples seem contrived at times.<br />
<br />
The code introduced in example 18 followed the nesting pattern: reading a number from the command line in the IO monad, passing that number to a computation in the Continuation monad to produce a string, and then writing the string back in the IO monad. The computations in the IO monad aren't restricted to reading from the command line and writing strings; they can be arbitrarily complex. Likewise, the inner computation can be arbitrarily complex as well. As long as the inner computation does not depend on the functionality of the outer monad, it can be safely nested within the outer monad, as illustrated in this variation on example 18 which reads the value from stdin instead of using a command line argument:<br />
<br />
Code available in [[../examples/example19.hs|example19.hs]]<br />
<br />
<haskell><br />
fun :: IO String<br />
fun = do n <- (readLn::IO Int) -- this is an IO monad block<br />
return $ (`runCont` id) $ do -- this is a Cont monad block<br />
str <- callCC $ \exit1 -> do<br />
when (n < 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' <- callCC $ \exit2 -> do<br />
when ((length ns) < 3) (exit2 (length ns))<br />
when ((length ns) < 5) (exit2 n)<br />
when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns')<br />
return $ sum ns<br />
return $ "(ns = " ++ (show ns) ++ ") " ++ (show n')<br />
return $ "Answer: " ++ str<br />
</haskell><br />
== Combined Monads ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
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 one-way monad — so we may need to nest little do-blocks 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.<br />
<br />
Code available in [[../examples/example20.hs|example20.hs]]<br />
<br />
<haskell><br />
toIO :: a -> IO a<br />
toIO x = return x<br />
<br />
fun :: IO String<br />
fun = do n <- (readLn::IO Int) -- this is an IO monad block<br />
convert n<br />
<br />
convert :: Int -> IO String<br />
convert n = (`runCont` id) $ do -- this is a Cont monad block<br />
str <- callCC $ \exit1 -> do -- str has type IO String<br />
when (n < 10) (exit1 $ toIO (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' <- callCC $ \exit2 -> do -- n' has type IO Int<br />
when ((length ns) < 3) (exit2 (toIO (length ns)))<br />
when ((length ns) < 5) (exit2 $ do putStrLn "Enter a number:"<br />
x <- (readLn::IO Int)<br />
return x)<br />
when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns)<br />
exit1 $ toIO (dropWhile (=='0') ns')<br />
return (toIO (sum ns))<br />
return $ do num <- n' -- this is an IO monad block<br />
return $ "(ns = " ++ (show ns) ++ ") " ++ (show num)<br />
return $ do s <- str -- this is an IO monad block<br />
return $ "Answer: " ++ s<br />
</haskell><br />
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 side-by-side shows the degree to which the manual monad combination strategy pollutes the code.<br />
<br />
Nested monads from example 19<br />
<br />
Manually combined monads from example 20<br />
<br />
<haskell><br />
fun = do n <- (readLn::IO Int)<br />
return $ (`runCont` id) $ do<br />
str <- callCC $ \exit1 -> do<br />
when (n < 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' <- callCC $ \exit2 -> do<br />
when ((length ns) < 3) (exit2 (length ns))<br />
when ((length ns) < 5) (exit2 n)<br />
when ((length ns) < 7) $ do<br />
let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns')<br />
return $ sum ns<br />
return $ "(ns = " ++ (show ns) ++ ") " ++ (show n')<br />
return $ "Answer: " ++ str<br />
</haskell><br />
<haskell><br />
convert n = (`runCont` id) $ do<br />
str <- callCC $ \exit1 -> do<br />
when (n < 10) (exit1 $ toIO (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' <- callCC $ \exit2 -> do<br />
when ((length ns) < 3) (exit2 (toIO (length ns)))<br />
when ((length ns) < 5) (exit2 $ do<br />
putStrLn "Enter a number:"<br />
x <- (readLn::IO Int)<br />
return x)<br />
when ((length ns) < 7) $ do<br />
let ns' = map intToDigit (reverse ns)<br />
exit1 $ toIO (dropWhile (=='0') ns')<br />
return (toIO (sum ns))<br />
return $ do num <- n'<br />
return $ "(ns = " ++ (show ns) ++ ") " ++ (show num)<br />
return $ do s <- str<br />
return $ "Answer: " ++ s<br />
</haskell><br />
Monad transformers<br />
<br />
= Monad transformers =<br />
<br />
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.<br />
<br />
== Transformer type constructors ==<br />
<br />
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>.<br />
<br />
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>.<br />
<br />
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 non-transformer 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>.<br />
<br />
[[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.<br />
<br />
== Lifting ==<br />
<br />
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 do-blocks 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.<br />
<br />
Recall the <code>liftM</code> family of functions which are used to lift non-monadic 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.<br />
<br />
Code available in [[../examples/example21.hs|example21.hs]]<br />
<br />
<haskell><br />
fun :: IO String<br />
fun = (`runContT` return) $ do<br />
n <- liftIO (readLn::IO Int)<br />
str <- callCC $ \exit1 -> do -- define "exit1"<br />
when (n < 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' <- callCC $ \exit2 -> do -- define "exit2"<br />
when ((length ns) < 3) (exit2 (length ns))<br />
when ((length ns) < 5) $ do liftIO $ putStrLn "Enter a number:"<br />
x <- liftIO (readLn::IO Int)<br />
exit2 x<br />
when ((length ns) < 7) $ do let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns') --escape 2 levels<br />
return $ sum ns<br />
return $ "(ns = " ++ (show ns) ++ ") " ++ (show n')<br />
return $ "Answer: " ++ str<br />
</haskell><br />
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.<br />
<br />
Nested monads from example 19<br />
<br />
Monads combined with a transformer from example 21<br />
<br />
<haskell><br />
fun = do n <- (readLn::IO Int)<br />
return $ (`runCont` id) $ do<br />
str <- callCC $ \exit1 -> do<br />
when (n < 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' <- callCC $ \exit2 -> do<br />
when ((length ns) < 3) (exit2 (length ns))<br />
when ((length ns) < 5) (exit2 n)<br />
when ((length ns) < 7) $ do<br />
let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns')<br />
return $ sum ns<br />
return $ "(ns = " ++ (show ns) ++ ") " ++ (show n')<br />
return $ "Answer: " ++ str<br />
</haskell><br />
<haskell><br />
fun = (`runContT` return) $ do<br />
n <- liftIO (readLn::IO Int)<br />
str <- callCC $ \exit1 -> do<br />
when (n < 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' <- callCC $ \exit2 -> do<br />
when ((length ns) < 3) (exit2 (length ns))<br />
when ((length ns) < 5) $ do<br />
liftIO $ putStrLn "Enter a number:"<br />
x <- liftIO (readLn::IO Int)<br />
exit2 x<br />
when ((length ns) < 7) $ do<br />
let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns')<br />
return $ sum ns<br />
return $ "(ns = " ++ (show ns) ++ ") " ++ (show n')<br />
return $ "Answer: " ++ str<br />
</haskell><br />
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#comparison|changes]] required to achieve the same result using a manually combined monad.<br />
<br />
Standard monad transformers<br />
<br />
= Standard monad transformers =<br />
<br />
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.<br />
<br />
== The MonadTrans and MonadIO classes ==<br />
<br />
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.<br />
<br />
<haskell><br />
class MonadTrans t where<br />
lift :: (Monad m) => m a -> t m a<br />
</haskell><br />
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.<br />
<br />
<haskell><br />
class (Monad m) => MonadIO m where<br />
liftIO :: IO a -> m a<br />
</haskell><br />
== Transformer versions of standard monads ==<br />
<br />
The standard monads of the monad template library all have transformer versions which are defined consistently with their non-transformer 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 non-transformer type.<br />
<br />
<table><br />
<tr class="header"><br />
<th align="left">Standard Monad</th><br />
<th align="left">Transformer Version</th><br />
<th align="left">Original Type</th><br />
<th align="left">Combined Type</th><br />
</tr><br />
<tr class="odd"><br />
<td align="left">[[errormonad.html|Error]]</td><br />
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Error.html#ErrorT ErrorT]</td><br />
<td align="left"><code>Either e a</code></td><br />
<td align="left"><code>m (Either e a)</code></td><br />
</tr><br />
<tr class="even"><br />
<td align="left">[[statemonad.html|State]]</td><br />
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.State.html#StateT StateT]</td><br />
<td align="left"><code>s -> (a,s)</code></td><br />
<td align="left"><code>s -> m (a,s)</code></td><br />
</tr><br />
<tr class="odd"><br />
<td align="left">[[readermonad.html|Reader]]</td><br />
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Reader.html#ReaderT ReaderT]</td><br />
<td align="left"><code>r -> a</code></td><br />
<td align="left"><code>r -> m a</code></td><br />
</tr><br />
<tr class="even"><br />
<td align="left">[[writermonad.html|Writer]]</td><br />
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Writer.html#WriterT WriterT]</td><br />
<td align="left"><code>(a,w)</code></td><br />
<td align="left"><code>m (a,w)</code></td><br />
</tr><br />
<tr class="odd"><br />
<td align="left">[[contmonad.html|Cont]]</td><br />
<td align="left">[http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Cont.html#ContT ContT]</td><br />
<td align="left"><code>(a -> r) -> r</code></td><br />
<td align="left"><code>(a -> m r) -> m r</code></td><br />
</tr><br />
</table><br />
<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 /><br />
<br />
<br />
Anatomy of a monad transformer<br />
<br />
= Anatomy of a monad transformer =<br />
<br />
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.html|State monad]] before continuing.<br />
<br />
== Combined monad definition ==<br />
<br />
Just as the State monad was built upon the definition<br />
<br />
<haskell><br />
newtype State s a = State { runState :: (s -> (a,s)) }<br />
</haskell><br />
the StateT transformer is built upon the definition<br />
<br />
<haskell><br />
newtype StateT s m a = StateT { runStateT :: (s -> m (a,s)) }<br />
</haskell><br />
<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>.<br />
<br />
To define <code>StateT s m</code> as a <code>Monad</code> instance:<br />
<br />
<haskell><br />
newtype StateT s m a = StateT { runStateT :: (s -> m (a,s)) }<br />
<br />
instance (Monad m) => Monad (StateT s m) where<br />
return a = StateT $ \s -> return (a,s)<br />
(StateT x) >>= f = StateT $ \s -> do (v,s') <- x s -- get new value, state<br />
(StateT x') <- return $ f v -- apply bound function to get new state transformation fn<br />
x' s' -- apply the state transformation fn to the new state<br />
</haskell><br />
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 do-block to perform a computation in the inner monad.<br />
<br />
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>:<br />
<br />
<haskell><br />
instance (Monad m) => MonadState s (StateT s m) where<br />
get = StateT $ \s -> return (s,s)<br />
put s = StateT $ \_ -> return ((),s)<br />
</haskell><br />
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>:<br />
<br />
<haskell><br />
instance (MonadPlus m) => MonadPlus (StateT s m) where<br />
mzero = StateT $ \s -> mzero<br />
(StateT x1) `mplus` (StateT x2) = StateT $ \s -> (x1 s) `mplus` (x2 s)<br />
</haskell><br />
== Defining the lifting function ==<br />
<br />
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:<br />
<br />
<haskell><br />
instance MonadTrans (StateT s) where<br />
lift c = StateT $ \s -> c >>= (\x -> return (x,s))<br />
</haskell><br />
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 &quot;fork&quot; 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.<br />
<br />
== Functors ==<br />
<br />
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.<br />
<br />
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://www-internal.cse.ogi.edu/~mpj/pubs/springschool95.ps paper] that inspired the Haskell monad template library.<br />
<br />
More examples with monad transformers<br />
<br />
= More examples with monad transformers =<br />
<br />
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.<br />
<br />
== WriterT with IO ==<br />
<br />
Try adapting the [[writermonad.html#example|firewall simulator]] of example 17 to include a timestamp on each log entry (don't worry about merging entries). The necessary changes should look something like this:<br />
<br />
Code available in [[../examples/example22.hs|example22.hs]]<br />
<br />
<haskell><br />
-- this is the format of our log entries<br />
data Entry = Log {timestamp::ClockTime, msg::String} deriving Eq<br />
<br />
instance Show Entry where<br />
show (Log t s) = (show t) ++ " | " ++ s<br />
<br />
-- this is the combined monad type<br />
type LogWriter a = WriterT [Entry] IO a<br />
<br />
-- add a message to the log<br />
logMsg :: String -> LogWriter ()<br />
logMsg s = do t <- liftIO getClockTime<br />
tell [Log t s]<br />
<br />
-- this handles one packet<br />
filterOne :: [Rule] -> Packet -> LogWriter (Maybe Packet)<br />
filterOne rules packet = do rule <- return (match rules packet)<br />
case rule of<br />
Nothing -> do logMsg ("DROPPING UNMATCHED PACKET: " ++ (show packet))<br />
return Nothing<br />
(Just r) -> do when (logIt r) (logMsg ("MATCH: " ++ (show r) ++ " <=> " ++ (show packet)))<br />
case r of<br />
(Rule Accept _ _) -> return (Just packet)<br />
(Rule Reject _ _) -> return Nothing<br />
<br />
-- this filters a list of packets, producing a filtered packet list<br />
-- and a log of the activity<br />
filterAll :: [Rule] -> [Packet] -> LogWriter [Packet]<br />
filterAll rules packets = do logMsg "STARTING PACKET FILTER"<br />
out <- mapM (filterOne rules) packets<br />
logMsg "STOPPING PACKET FILTER"<br />
return (catMaybes out)<br />
<br />
-- read the rule data from the file named in the first argument, and the packet data from<br />
-- the file named in the second argument, and then print the accepted packets followed by<br />
-- a log generated during the computation.<br />
main :: IO ()<br />
main = do args <- getArgs<br />
ruleData <- readFile (args!!0)<br />
packetData <- readFile (args!!1)<br />
let rules = (read ruleData)::[Rule]<br />
packets = (read packetData)::[Packet]<br />
(out,log) <- runWriterT (filterAll rules packets)<br />
putStrLn "ACCEPTED PACKETS"<br />
putStr (unlines (map show out))<br />
putStrLn "\n\nFIREWALL LOG"<br />
putStr (unlines (map show log))<br />
</haskell><br />
== ReaderT with IO ==<br />
<br />
If you found that one too easy, move on to a slightly more complex example: convert the [[readermonad.html#example|template system]] in example 16 from using a single template file with named templates to treating individual files as templates. One possible solution is shown in [[../examples/example23.hs|example 23]], but try to do it without looking first.<br />
<br />
== StateT with List ==<br />
<br />
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.<br />
<br />
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 non-deterministic nature of the List monad allows us to easily test all combinations of variable assignments.<br />
<br />
We start by laying the groundwork we will need to represent the logic problem, a simple predicate language:<br />
<br />
Code available in [[../examples/example24.hs|example24.hs]]<br />
<br />
<haskell><br />
-- First, we develop a language to express logic problems<br />
type Var = String<br />
type Value = String<br />
data Predicate = Is Var Value -- var has specific value<br />
| Equal Var Var -- vars have same (unspecified) value<br />
| And Predicate Predicate -- both are true<br />
| Or Predicate Predicate -- at least one is true<br />
| Not Predicate -- it is not true<br />
deriving (Eq, Show)<br />
<br />
type Variables = [(Var,Value)]<br />
<br />
-- test for a variable NOT equaling a value<br />
isNot :: Var -> Value -> Predicate<br />
isNot var value = Not (Is var value)<br />
<br />
-- if a is true, then b must also be true<br />
implies :: Predicate -> Predicate -> Predicate<br />
implies a b = Not (a `And` (Not b))<br />
<br />
-- exclusive or<br />
orElse :: Predicate -> Predicate -> Predicate<br />
orElse a b = (a `And` (Not b)) `Or` ((Not a) `And` b)<br />
<br />
-- Check a predicate with the given variable bindings.<br />
-- An unbound variable causes a Nothing return value.<br />
check :: Predicate -> Variables -> Maybe Bool<br />
check (Is var value) vars = do val <- lookup var vars<br />
return (val == value)<br />
check (Equal v1 v2) vars = do val1 <- lookup v1 vars<br />
val2 <- lookup v2 vars<br />
return (val1 == val2)<br />
check (And p1 p2) vars = liftM2 (&&) (check p1 vars) (check p2 vars)<br />
check (Or p1 p2) vars = liftM2 (||) (check p1 vars) (check p2 vars)<br />
check (Not p) vars = liftM (not) (check p vars)<br />
</haskell><br />
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.<br />
<br />
Code available in [[../examples/example24.hs|example24.hs]]<br />
<br />
<haskell><br />
-- this is the type of our logic problem<br />
data ProblemState = PS {vars::Variables, constraints::[Predicate]}<br />
<br />
-- this is our monad type for non-determinstic computations with state<br />
type NDS a = StateT ProblemState [] a<br />
<br />
-- lookup a variable<br />
getVar :: Var -> NDS (Maybe Value)<br />
getVar v = do vs <- gets vars<br />
return $ lookup v vs<br />
<br />
-- set a variable<br />
setVar :: Var -> Value -> NDS ()<br />
setVar v x = do st <- get<br />
vs' <- return $ filter ((v/=).fst) (vars st)<br />
put $ st {vars=(v,x):vs'}<br />
<br />
-- Check if the variable assignments satisfy all of the predicates.<br />
-- The partial argument determines the value used when a predicate returns<br />
-- Nothing because some variable it uses is not set. Setting this to True<br />
-- allows us to accept partial solutions, then we can use a value of<br />
-- False at the end to signify that all solutions should be complete.<br />
isConsistent :: Bool -> NDS Bool<br />
isConsistent partial = do cs <- gets constraints<br />
vs <- gets vars<br />
let results = map (\p->check p vs) cs<br />
return $ and (map (maybe partial id) results)<br />
<br />
-- Return only the variable bindings that are complete consistent solutions.<br />
getFinalVars :: NDS Variables<br />
getFinalVars = do c <- isConsistent False<br />
guard c<br />
gets vars<br />
<br />
-- Get the first solution to the problem, by evaluating the solver computation with<br />
-- an initial problem state and then returning the first solution in the result list,<br />
-- or Nothing if there was no solution.<br />
getSolution :: NDS a -> ProblemState -> Maybe a<br />
getSolution c i = listToMaybe (evalStateT c i)<br />
<br />
-- Get a list of all possible solutions to the problem by evaluating the solver<br />
-- computation with an initial problem state.<br />
getAllSolutions :: NDS a -> ProblemState -> [a]<br />
getAllSolutions c i = evalStateT c i<br />
</haskell><br />
We are ready to apply the predicate language and stateful nondeterministic monad to solving a logic problem. For this example, we will use the well-known Kalotan puzzle which appeared in ''Mathematical Brain-Teasers'', Dover Publications (1976), by J. A. H. Hunter.<br />
<br />
<blockquote>The Kalotans are a tribe with a peculiar quirk: their males always tell the truth. Their females never make two consecutive true statements, or two consecutive untrue statements. An anthropologist (let's call him Worf) has begun to study them. Worf does not yet know the Kalotan language. One day, he meets a Kalotan (heterosexual) couple and their child Kibi. Worf asks Kibi: ``Are you a boy?'' The kid answers in Kalotan, which of course Worf doesn't understand. Worf turns to the parents (who know English) for explanation. One of them says: &quot;Kibi said: `I am a boy.'&quot; The other adds: &quot;Kibi is a girl. Kibi lied.&quot; Solve for the sex of Kibi and the sex of each parent.</blockquote><br />
We will need some additional predicates specific to this puzzle, and to define the universe of allowed variables values:<br />
<br />
Code available in [[../examples/example24.hs|example24.hs]]<br />
<br />
<haskell><br />
-- if a male says something, it must be true<br />
said :: Var -> Predicate -> Predicate<br />
said v p = (v `Is` "male") `implies` p<br />
<br />
-- if a male says two things, they must be true<br />
-- if a female says two things, one must be true and one must be false<br />
saidBoth :: Var -> Predicate -> Predicate -> Predicate<br />
saidBoth v p1 p2 = And ((v `Is` "male") `implies` (p1 `And` p2))<br />
((v `Is` "female") `implies` (p1 `orElse` p2))<br />
<br />
-- lying is saying something is true when it isn't or saying something isn't true when it is<br />
lied :: Var -> Predicate -> Predicate<br />
lied v p = ((v `said` p) `And` (Not p)) `orElse` ((v `said` (Not p)) `And` p)<br />
<br />
-- Test consistency over all allowed settings of the variable.<br />
tryAllValues :: Var -> NDS ()<br />
tryAllValues var = do (setVar var "male") `mplus` (setVar var "female")<br />
c <- isConsistent True<br />
guard c<br />
</haskell><br />
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:<br />
<br />
Code available in [[../examples/example24.hs|example24.hs]]<br />
<br />
<haskell><br />
-- Define the problem, try all of the variable assignments and print a solution.<br />
main :: IO ()<br />
main = do let variables = []<br />
constraints = [ Not (Equal "parent1" "parent2"),<br />
"parent1" `said` ("child" `said` ("child" `Is` "male")),<br />
saidBoth "parent2" ("child" `Is` "female")<br />
("child" `lied` ("child" `Is` "male")) ]<br />
problem = PS variables constraints<br />
print $ (`getSolution` problem) $ do tryAllValues "parent1"<br />
tryAllValues "parent2"<br />
tryAllValues "child"<br />
getFinalVars<br />
</haskell><br />
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.<br />
<br />
Managing the transformer stack<br />
<br />
= Managing the transformer stack =<br />
<br />
As the number of monads combined together increases, it becomes increasingly important to manage the stack of monad transformers well.<br />
<br />
== Selecting the correct order ==<br />
<br />
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?<br />
<br />
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>.<br />
<br />
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.<br />
<br />
== An example with multiple transformers ==<br />
<br />
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 N-queens problem: to place N queens on a chess board so that no queen can attack another.<br />
<br />
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.<br />
<br />
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.<br />
<br />
Code available in [[../examples/example25.hs|example25.hs]]<br />
<br />
<haskell><br />
-- this is the type of our problem description<br />
data NQueensProblem = NQP {board::Board,<br />
ranks::[Rank], files::[File],<br />
asc::[Diagonal], desc::[Diagonal]}<br />
<br />
-- initial state = empty board, all ranks, files, and diagonals free<br />
initialState = let fileA = map (\r->Pos A r) [1..8]<br />
rank8 = map (\f->Pos f 8) [A .. H]<br />
rank1 = map (\f->Pos f 1) [A .. H]<br />
asc = map Ascending (nub (fileA ++ rank1))<br />
desc = map Descending (nub (fileA ++ rank8))<br />
in NQP (Board []) [1..8] [A .. H] asc desc<br />
<br />
-- this is our combined monad type for this problem<br />
type NDS a = WriterT [String] (StateT NQueensProblem []) a<br />
<br />
-- Get the first solution to the problem, by evaluating the solver computation with<br />
-- an initial problem state and then returning the first solution in the result list,<br />
-- or Nothing if there was no solution.<br />
getSolution :: NDS a -> NQueensProblem -> Maybe (a,[String])<br />
getSolution c i = listToMaybe (evalStateT (runWriterT c) i)<br />
<br />
-- add a Queen to the board in a specific position<br />
addQueen :: Position -> NDS ()<br />
addQueen p = do (Board b) <- gets board<br />
rs <- gets ranks<br />
fs <- gets files<br />
as <- gets asc<br />
ds <- gets desc<br />
let b' = (Piece Black Queen, p):b<br />
rs' = delete (rank p) rs<br />
fs' = delete (file p) fs<br />
(a,d) = getDiags p<br />
as' = delete a as<br />
ds' = delete d ds<br />
tell ["Added Queen at " ++ (show p)]<br />
put (NQP (Board b') rs' fs' as' ds')<br />
<br />
-- test if a position is in the set of allowed diagonals<br />
inDiags :: Position -> NDS Bool<br />
inDiags p = do let (a,d) = getDiags p<br />
as <- gets asc<br />
ds <- gets desc<br />
return $ (elem a as) && (elem d ds)<br />
<br />
-- add a Queen to the board in all allowed positions<br />
addQueens :: NDS ()<br />
addQueens = do rs <- gets ranks<br />
fs <- gets files<br />
allowed <- filterM inDiags [Pos f r | f <- fs, r <- rs]<br />
tell [show (length allowed) ++ " possible choices"]<br />
msum (map addQueen allowed)<br />
<br />
-- Start with an empty chess board and add the requested number of queens,<br />
-- then get the board and print the solution along with the log<br />
main :: IO ()<br />
main = do args <- getArgs<br />
let n = read (args!!0)<br />
cmds = replicate n addQueens<br />
sol = (`getSolution` initialState) $ do sequence_ cmds<br />
gets board<br />
case sol of<br />
Just (b,l) -> do putStr $ show b -- show the solution<br />
putStr $ unlines l -- show the log<br />
Nothing -> putStrLn "No solution"<br />
</haskell><br />
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.<br />
<br />
== Heavy lifting ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
Instead of writing brittle code like:<br />
<br />
<haskell><br />
logString :: String -> StateT MyState (WriterT [String] []) Int<br />
logString s = ...<br />
</haskell><br />
we can write clearer, more flexible code like:<br />
<br />
<haskell><br />
logString :: (MonadWriter [String] m) => String -> m Int<br />
logString s = ...<br />
</haskell><br />
and then lift the <code>logString</code> computation into the combined monad when we use it.<br />
<br />
[[Image:info.png]] You may need to use the compiler flags <code>-fglasgow-exts</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 /><br />
<br />
<br />
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:<br />
<br />
<haskell><br />
liftListToState = lift . lift . lift<br />
</haskell><br />
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.<br />
<br />
The hardest part about lifting is understanding the semantics of lifting computations, since this depends on the details of the inner monad and the transformers in the stack. As a final task, try to understand the different roles that lifting plays in the following example code. Can you predict what the output of the program will be?<br />
<br />
Code available in [[../examples/example26.hs|example26.hs]]<br />
<br />
<haskell><br />
-- this is our combined monad type for this problem<br />
type NDS a = StateT Int (WriterT [String] []) a<br />
<br />
{- Here is a computation on lists -}<br />
<br />
-- return the digits of a number as a list<br />
getDigits :: Int -> [Int]<br />
getDigits n = let s = (show n)<br />
in map digitToInt s<br />
<br />
{- Here are some computations in MonadWriter -}<br />
<br />
-- write a value to a log and return that value<br />
logVal :: (MonadWriter [String] m) => Int -> m Int<br />
logVal n = do tell ["logVal: " ++ (show n)]<br />
return n<br />
<br />
-- do a logging computation and return the length of the log it wrote<br />
getLogLength :: (MonadWriter [[a]] m) => m b -> m Int<br />
getLogLength c = do (_,l) <- listen $ c<br />
return (length (concat l))<br />
<br />
-- log a string value and return 0<br />
logString :: (MonadWriter [String] m) => String -> m Int<br />
logString s = do tell ["logString: " ++ s]<br />
return 0<br />
<br />
{- Here is a computation that requires a WriterT [String] [] -}<br />
<br />
-- "Fork" the computation and log each list item in a different branch.<br />
logEach :: (Show a) => [a] -> WriterT [String] [] a<br />
logEach xs = do x <- lift xs<br />
tell ["logEach: " ++ (show x)]<br />
return x<br />
<br />
{- Here is a computation in MonadState -}<br />
<br />
-- increment the state by a specified value<br />
addVal :: (MonadState Int m) => Int -> m ()<br />
addVal n = do x <- get<br />
put (x+n)<br />
<br />
{- Here are some computations in the combined monad -}<br />
<br />
-- set the state to a given value, and log that value<br />
setVal :: Int -> NDS ()<br />
setVal n = do x <- lift $ logVal n<br />
put x<br />
<br />
-- "Fork" the computation, adding a different digit to the state in each branch.<br />
-- Because setVal is used, the new values are logged as well.<br />
addDigits :: Int -> NDS ()<br />
addDigits n = do x <- get<br />
y <- lift . lift $ getDigits n<br />
setVal (x+y)<br />
<br />
{- an equivalent construction is:<br />
addDigits :: Int -> NDS ()<br />
addDigits n = do x <- get<br />
msum (map (\i->setVal (x+i)) (getDigits n))<br />
-}<br />
<br />
{- This is an example of a helper function that can be used to put all of the lifting logic<br />
in one location and provide more informative names. This has the advantage that if the<br />
transformer stack changes in the future (say, to add ErrorT) the changes to the existing<br />
lifting logic are confined to a small number of functions.<br />
-}<br />
liftListToNDS :: [a] -> NDS a<br />
liftListToNDS = lift . lift<br />
<br />
-- perform a series of computations in the combined monad, lifting computations from other<br />
-- monads as necessary.<br />
main :: IO ()<br />
main = do mapM_ print $ runWriterT $ (`evalStateT` 0) $ do x <- lift $ getLogLength $ logString "hello"<br />
addDigits x<br />
x <- lift $ logEach [1,3,5]<br />
lift $ logVal x<br />
liftListToNDS $ getDigits 287<br />
<br />
</haskell><br />
Once you fully understand how the various lifts in the example work and how lifting promotes code reuse, you are ready for real-world monadic programming. All that is left to do is to hone your skills writing real software. Happy hacking!<br />
<br />
Continuing Exploration<br />
<br />
= Continuing Exploration =<br />
<br />
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/category-theory/ 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.<br />
<br />
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].<br />
<br />
A physical analogy for monads<br />
<br />
= A physical analogy for monads =<br />
<br />
Because monads are such abstract entities, it is sometimes useful to think about a physical system that is analogous to a monad instead of thinking about monads directly. In this way, we can use our physical intuition and experiences to gain insights that we can relate back to the abstract world of computational monads.<br />
<br />
The particular physical analogy developed here is that of a mechanized assembly line. It is not a perfect fit for monads — especially with some of the higher-order aspects of monadic computation — but I believe it could be helpful to gain the initial understanding of how a monad works.<br />
<br />
Begin by thinking about a Haskell program as a conveyor belt. Input goes on end of the conveyor belt and is carried to a succession of work areas. At each work area, some operation is performed on the item on the conveyor belt and the result is carried by the conveyor belt to the next work area. Finally, the conveyor belt carries the final product to the end of the assembly line to be output.<br />
<br />
In this assembly line model, our physical monad is a system of machines that controls how successive work areas on the assembly line combine their functionality to create the overall product.<br />
<br />
Our monad consists of three parts:<br />
<br />
# Trays that hold work products as they move along the conveyor belt.<br />
# Loader machines that can put any object into a tray.<br />
# Combiner machines that can take a tray with an object and produce a tray with a new object. These combiner machines are attached to worker machines that actualy produce the new objects.<br />
<br />
We use the monad by setting up our assembly line as a loader machine which puts materials into trays at the beginning of the assembly line. The conveyor belt then carries these trays to each work area, where a combiner machine takes the tray and may decide based on its contents whether to run them through a worker machine, as shown in Figure A-1.<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">[[Image:figureA-1.png]]</td><br />
</tr><br />
<tr class="even"><br />
<td align="left">Figure A-1. An assembly line using a monad architecture.</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The important thing to notice about the monadic assembly line is that it separates out the work of combining the output of the worker machines from the actual work done by the worker machines. Once they are separated, we can vary them independently. So the same combiner machines could be used on an assembly line to make airplanes and an assembly line to make chopsticks. Likewise, the same worker machines could be used with different combiners to alter the way the final product is produced.<br />
<br />
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:<br />
<br />
<haskell><br />
-- the basic types we are dealing with<br />
type Wood = ...<br />
type Chopsticks = ...<br />
data Wrapper x = Wrapper x<br />
<br />
-- NOTE: the Tray type comes from the Tray monad<br />
<br />
-- worker function 1: makes roughly shaped chopsticks<br />
makeChopsticks :: Wood -> Tray Chopsticks<br />
makeChopsticks w = ...<br />
<br />
-- worker function 2: polishes chopsticks<br />
polishChopsticks :: Chopsticks -> Tray Chopsticks<br />
polishChopsticks c = ...<br />
<br />
-- worker function 3: wraps chopsticks<br />
wrapChopsticks :: Chopsticks -> Tray Wrapper Chopsticks<br />
wrapChopsticks c = ...<br />
</haskell><br />
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 non-empty trays to its worker machine. In Haskell, we would define the <code>Tray</code> monad as:<br />
<br />
<haskell><br />
-- trays are either empty or contain a single item <br />
data Tray x = Empty | Contains x<br />
<br />
-- Tray is a monad<br />
instance Monad Tray where<br />
Empty >>= _ = Empty<br />
(Contains x) >>= worker = worker x<br />
return = Contains<br />
fail _ = Empty <br />
</haskell><br />
[[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 /><br />
<br />
<br />
All that remains is to sequence the worker machines together using the loader and combiner machines to make a complete assembly line, as shown in Figure A-2.<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">[[Image:figureA-2.png]]</td><br />
</tr><br />
<tr class="even"><br />
<td align="left">Figure A-2. A complete assembly line for making chopsticks using a monadic approach.</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
In Haskell, the sequencing can be done using the standard monadic functions:<br />
<br />
<haskell><br />
assemblyLine :: Wood -> Tray Wrapped Chopsticks<br />
assemblyLine w = (return w) >>= makeChopsticks >>= polishChopsticks >>= wrapChopsticks<br />
</haskell><br />
or using the built in Haskell &quot;do&quot; notation for monads:<br />
<br />
<haskell><br />
assemblyLine :: Wood -> Tray Wrapped Chopsticks<br />
assemblyLine w = do c <- makeChopsticks w<br />
c' <- polishChopsticks c<br />
c'' <- wrapChopsticks c'<br />
return c''<br />
</haskell><br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
<haskell><br />
-- tray2s either contain a single item or contain a failure report <br />
data Tray2 x = Contains x | Failed String<br />
<br />
-- Tray2 is a monad<br />
instance Monad Tray2 where<br />
(Failed reason) >>= _ = Failed reason<br />
(Contains x) >>= worker = worker x<br />
return = Contains<br />
fail reason = Failed reason<br />
</haskell><br />
[[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 /><br />
<br />
<br />
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!<br />
<br />
Haskell code examples<br />
<br />
= Haskell code examples =<br />
<br />
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].<br />
<br />
== [[../examples/example1.hs|Example 1]] ==<br />
<br />
This example is discussed in the section: [[meet.html#example1|Meet the monads]].<br />
<br />
The example code introduces the monad concept without using Haskell typeclasses. It shows how a monadic combinator can be used to simplify the construction of computations from sequences of computations which may not return a result.<br />
<br />
== [[../examples/example2.hs|Example 2]] ==<br />
<br />
This example is discussed in the section: [[class.html#example2|Doing it with class]].<br />
<br />
The example code builds on the first example, and shows how do-notation can be used with an instance of the <code>Monad</code> class (in this case, <code>Maybe</code> is the monad used).<br />
<br />
== [[../examples/example3.hs|Example 3]] ==<br />
<br />
This example is discussed in the section: [[monadfns.html#example3|Monad support in Haskell]].<br />
<br />
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 do-block.<br />
<br />
== [[../examples/example4.hs|Example 4]] ==<br />
<br />
This example is discussed in the section: [[monadfns.html#example4|Monad support in Haskell]].<br />
<br />
The example code shows a more typical use of the <code>foldM</code> function within a do-block. It combines dictionary values read from different files into a single dictionary using the <code>foldM</code> function within the IO monad.<br />
<br />
== [[../examples/example5.hs|Example 5]] ==<br />
<br />
This example is discussed in the section: [[monadfns.html#example5|Monad support in Haskell]].<br />
<br />
The example code shows the use of the <code>filterM</code> function within a do-block. It prints the subset of its arguments that specify directories and ignores non-directory arguments.<br />
<br />
== [[../examples/example6.hs|Example 6]] ==<br />
<br />
This example is discussed in the section: [[monadfns.html#example6|Monad support in Haskell]].<br />
<br />
The example code shows the use of the <code>liftM</code> function within a do-block. It looks up a name in a list and uses a lifted String manipulation function to modify it within the Maybe monad.<br />
<br />
== [[../examples/example7.hs|Example 7]] ==<br />
<br />
This example is discussed in the section: [[monadfns.html#example7|Monad support in Haskell]].<br />
<br />
The example code shows a higher-order 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.<br />
<br />
== [[../examples/example8.hs|Example 8]] ==<br />
<br />
This example is discussed in the section: [[monadfns.html#example8|Monad support in Haskell]].<br />
<br />
The example code shows a higher-order 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.<br />
<br />
== [[../examples/example9.hs|Example 9]] ==<br />
<br />
This example is discussed in the section: [[monadfns.html#example9|Monad support in Haskell]].<br />
<br />
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.<br />
<br />
== [[../examples/example10.hs|Example 10]] ==<br />
<br />
This example is discussed in the section: [[monadfns.html#example10|Monad support in Haskell]].<br />
<br />
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>).<br />
<br />
== [[../examples/example11.hs|Example 11]] ==<br />
<br />
This example is discussed in the section: [[maybemonad.html#example|The Maybe monad]].<br />
<br />
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.<br />
<br />
== [[../examples/example12.hs|Example 12]] ==<br />
<br />
This example is discussed in the section: [[errormonad.html#example|The Error monad]].<br />
<br />
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.<br />
<br />
== [[../examples/example13.hs|Example 13]] ==<br />
<br />
This example is discussed in the section: [[listmonad.html#example|The List monad]].<br />
<br />
The example code uses the built-in list type constructor as a monad for non-deterministic computation. The example demonstrates parsing an ambiguous grammar consisting of integers, hex values, and words.<br />
<br />
== [[../examples/example14.hs|Example 14]] ==<br />
<br />
This example is discussed in the section: [[iomonad.html#example|The IO monad]].<br />
<br />
The example code implements a simple version of the standard Unix command &quot;tr&quot;. 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>.<br />
<br />
== [[../examples/example15.hs|Example 15]] ==<br />
<br />
This example is discussed in the section: [[statemonad.html#example|The State monad]].<br />
<br />
The example code shows how the State monad can be used instead of explicitly passing state. The example uses the State monad to manage the random number generator state while building a compound data value requiring multiple calls to the random number generator.<br />
<br />
== [[../examples/example16.hs|Example 16]] ==<br />
<br />
This example is discussed in the section: [[readermonad.html#example|The Reader monad]].<br />
<br />
The example code shows how the Reader monad can be used to simplify computations involving a shared environment. The example uses the Reader monad to implement a simple template substitution system. The example code demonstrates the use of the Parsec monadic parser combinator library.<br />
<br />
== [[../examples/example17.hs|Example 17]] ==<br />
<br />
This example is discussed in the section: [[writermonad.html#example|The Writer monad]].<br />
<br />
The example code shows how the Writer monad can be used to implement logging. The example implements a very simple firewall simulator and uses the Writer monad to log the firewall activity.<br />
<br />
== [[../examples/example18.hs|Example 18]] ==<br />
<br />
This example is discussed in the section: [[contmonad.html#example|The Continuation monad]].<br />
<br />
The example code shows how the Continuation monad's escape continuations work. The example computes a complex transformation of a number.<br />
<br />
== [[../examples/example19.hs|Example 19]] ==<br />
<br />
This example is discussed in the section: [[hardway.html#example1|Combining monads the hard way]].<br />
<br />
The example code shows how the Continuation monad can be nested within the IO monad given a suitable computational structure. The example is a slight modification of example 18.<br />
<br />
== [[../examples/example20.hs|Example 20]] ==<br />
<br />
This example is discussed in the section: [[hardway.html#example2|Combining monads the hard way]].<br />
<br />
The example code shows how the Continuation monad and IO monad can be used simultaneously, but without using monad transformers. The example builds on examples 18 and 19.<br />
<br />
== [[../examples/example21.hs|Example 21]] ==<br />
<br />
This example is discussed in the section: [[transformers.html#example|Monad transformers]].<br />
<br />
The example code shows how the transformer version of the Continuation monad can be used to create a combined monad for using continuations and doing I/O. The example builds on examples 18, 19 and 20.<br />
<br />
== [[../examples/example22.hs|Example 22]] ==<br />
<br />
This example is discussed in the section: [[standardxformers.html#example1|Standard monad transformers]].<br />
<br />
The example code shows how the transformer version of the Writer monad can be used to create a combined monad for logging and doing I/O. The example adds timestamps to the log entries of the firewall simulator from example 17.<br />
<br />
== [[../examples/example23.hs|Example 23]] ==<br />
<br />
This example is discussed in the section: [[standardxformers.html#example2|Standard monad transformers]].<br />
<br />
The example code shows how the transformer version of the Reader monad can be used to create a monad that combines a shared environment with I/O. The example converts the template system of example 16 to use files as templates.<br />
<br />
== [[../examples/example24.hs|Example 24]] ==<br />
<br />
This example is discussed in the section: [[standardxformers.html#example3|Standard monad transformers]].<br />
<br />
The example code uses the <code>StateT</code> transformer on the List monad to create a combined monad for doing non-deterministic stateful computations. The example uses the combined monad to solve a logic problem.<br />
<br />
== [[../examples/example25.hs|Example 25]] ==<br />
<br />
This example is discussed in the section: [[stacking.html#example|An example with multiple monad transformers]].<br />
<br />
The example code uses the <code>StateT</code> and <code>WriterT</code> transformers on the List monad to create a combined monad for doing non-deterministic stateful computations with logging. The example uses the combined monad to solve the N-queens problem.<br />
<br />
== [[../examples/example26.hs|Example 26]] ==<br />
<br />
This example is discussed in the section: [[stacking.html#lifting|Heavy lifting]].<br />
<br />
The example code demonstrates the use of the <code>lift</code> function and the necessity of managing its use in complex transformer stacks.<br />
<br />
[[Category:Monad]]<br />
[[Category:Standard classes]]<br />
[[Category:Standard libraries]]<br />
[[Category:Standard packages]]<br />
[[Category:Standard types]]<br />
[[Category:Tutorials]]</div>Kinihttps://wiki.haskell.org/index.php?title=Let_vs._Where&diff=58319Let vs. Where2014-06-11T23:34:25Z<p>Kini: </p>
<hr />
<div>Haskell programmers often wonder whether to use <hask>let</hask> or <hask>where</hask>.<br />
This seems to be only a matter of taste in the sense of "[[Declaration vs. expression style]]", however there is more to it.<br />
<br />
It is important to know that <hask>let ... in ...</hask> is an expression, that is, it can be written wherever expressions are allowed. In contrast, <hask>where</hask> is bound to a surrounding syntactic construct, like the [[pattern matching]] line of a function definition.<br />
<br />
== Advantages of let ==<br />
<br />
Suppose you have the function<br />
<haskell><br />
f :: s -> (a,s)<br />
f x = y<br />
where y = ... x ...<br />
</haskell><br />
and later you decide to put this into the <hask>Control.Monad.State</hask> monad.<br />
However, transforming to<br />
<haskell><br />
f :: State s a<br />
f = State $ \x -> y<br />
where y = ... x ...<br />
</haskell><br />
will not work, because <hask>where</hask> refers to the pattern matching <hask> f = </hask>,<br />
where no <hask>x</hask> is in scope.<br />
<br />
In contrast, if you had started with <hask>let</hask>, then you wouldn't have trouble.<br />
<haskell><br />
f :: s -> (a,s)<br />
f x =<br />
let y = ... x ...<br />
in y<br />
</haskell><br />
This is easily transformed to:<br />
<haskell><br />
f :: State s a<br />
f = State $ \x -><br />
let y = ... x ...<br />
in y<br />
</haskell><br />
<br />
== Advantages of where ==<br />
<br />
Because "where" blocks are bound to a syntactic construct, they can be used to share bindings between parts of a function that are not syntactically expressions. For example:<br />
<br />
<haskell><br />
f x<br />
| cond1 x = a<br />
| cond2 x = g a<br />
| otherwise = f (h x a)<br />
where<br />
a = w x<br />
</haskell><br />
<br />
In expression style, you might use an explicit <hask>case</hask>:<br />
<br />
<haskell><br />
f x<br />
= let a = w x<br />
in case () of<br />
_ | cond1 x -> a<br />
| cond2 x -> g a<br />
| otherwise -> f (h x a)<br />
</haskell><br />
<br />
or a [[Case|functional equivalent]]:<br />
<br />
<haskell><br />
f x =<br />
let a = w x<br />
in select (f (h x a))<br />
[(cond1 x, a),<br />
(cond2 x, g a)]<br />
</haskell><br />
<br />
or a series of if-then-else expressions:<br />
<br />
<haskell><br />
f x<br />
= let a = w x<br />
in if cond1 x<br />
then a<br />
else if cond2 x<br />
then g a<br />
else f (h x a)<br />
</haskell><br />
<br />
These alternatives are arguably less readable and hide the structure of the function more than simply using <hask>where</hask>.<br />
<br />
== Lambda Lifting ==<br />
<br />
One other approach to consider is that let or where can often be implemented using [[lambda lifting]] and [[let floating]], incurring at least the cost of introducing a new name. The above example:<br />
<br />
<haskell><br />
f x<br />
| cond1 x = a<br />
| cond2 x = g a<br />
| otherwise = f (h x a)<br />
where<br />
a = w x<br />
</haskell><br />
<br />
could be implemented as:<br />
<br />
<haskell><br />
f x = f' (w x) x<br />
<br />
f' a x<br />
| cond1 x = a<br />
| cond2 x = g a<br />
| otherwise = f (h x a)<br />
</haskell><br />
<br />
The auxiliary definition can either be a top-level binding, or included in f using <hask>let</hask> or <hask>where</hask>.<br />
<br />
== Problems with where ==<br />
<br />
If you run both<br />
<br />
<haskell><br />
fib = (map fib' [0 ..] !!)<br />
where<br />
fib' 0 = 0<br />
fib' 1 = 1<br />
fib' n = fib (n - 1) + fib (n - 2)<br />
</haskell><br />
<br />
and<br />
<br />
<haskell><br />
fib x = map fib' [0 ..] !! x<br />
where<br />
fib' 0 = 0<br />
fib' 1 = 1<br />
fib' n = fib (n - 1) + fib (n - 2)<br />
</haskell><br />
<br />
you will notice that the second one runs considerably slower than the first. You may wonder why simply adding an explicit argument to <hask>fib</hask> (known as [[eta expansion]]) degrades performance so dramatically.<br />
<br />
You might see the reason better if you rewrote this code using <hask>let</hask>.<br />
<br />
Compare<br />
<br />
<haskell><br />
fib =<br />
let fib' 0 = 0<br />
fib' 1 = 1<br />
fib' n = fib (n - 1) + fib (n - 2)<br />
in (map fib' [0 ..] !!)<br />
</haskell><br />
<br />
and<br />
<br />
<haskell><br />
fib x =<br />
let fib' 0 = 0<br />
fib' 1 = 1<br />
fib' n = fib (n - 1) + fib (n - 2)<br />
in map fib' [0 ..] !! x<br />
</haskell><br />
<br />
In the second case, <hask>fib'</hask> is redefined for every argument <hask>x</hask>. The compiler cannot know whether you intended this -- while it increases time complexity it may reduce space complexity. Thus it will not float the definition out from under the binding of x.<br><br><br />
<br />
In contrast, in the first function, <hask>fib'</hask> can be moved to the top level by the compiler. The <hask>where</hask> clause hid this structure<br />
and made the application to <hask>x</hask> look like a plain eta expansion, which it is not.<br />
<br />
* Haskell-Cafe on [http://www.haskell.org/pipermail/haskell-cafe/2010-October/084538.html Eta-expansion destroys memoization?]<br />
<br />
<br />
[[Category:Style]]<br />
[[Category:Syntax]]</div>Kinihttps://wiki.haskell.org/index.php?title=Xmonad/Frequently_asked_questions&diff=56813Xmonad/Frequently asked questions2013-09-11T19:44:26Z<p>Kini: more specific link</p>
<hr />
<div>{{xmonad}}<br />
<br />
''xmonad: frequently asked questions''<br />
<br />
''For configuration tricks, and using xmonad.hs, see [[Xmonad/General_xmonad.hs_config_tips]]''.<br />
<br />
''For more documentation, see'':<br />
<br />
* [http://xmonad.org/intro.html Building xmonad]<br />
* [http://xmonad.org/contrib.html Configuring and extending xmonad]<br />
* [http://xmonad.org/xmonad-docs/xmonad-contrib/ Extension documentation]<br />
<br />
==When I start xmonad, nothing happens.==<br />
<br />
Don't panic, this is expected behavior. XMonad is a minimal window manager, meaning it doesn't set a background, start a status bar, display a splash screen or play a soothing sound effect when it starts up. Once xmonad has started, the only thing it does is listen for your first command. Try pressing mod-shift-enter (that is Alt, Shift, and Enter pressed at the same time) to bring up an xterm. Once the xterm appears, use it to read xmonad's man page or point a web browser at http://xmonad.org/tour.html. If no xterm appears, see if any other advice on this page applies.<br />
<br />
==Installation==<br />
<br />
===What build dependencies does xmonad have?===<br />
<br />
The [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/xmonad hackage page for xmonad] lists all dependencies, including:<br />
<br />
* Standard Haskell libraries (you might already have these installed):<br />
** [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Cabal Cabal]<br />
** [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/mtl mtl]<br />
** [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/unix unix]<br />
<br />
* Haskell X11 bindings:<br />
** [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/X11 X11]<br />
<br />
* C libraries:<br />
** libX<br />
** libXext<br />
** libXinerama<br />
<br />
You likely have these already if you've built any programs for X.<br />
<br />
xmonad is also availble pre-packaged for many distributions:<br />
<br />
* [http://www.openbsd.org/cgi-bin/cvsweb/ports/x11/xmonad/ OpenBSD]<br />
* [http://pkgsrc.se/wip/xmonad NetBSD]<br />
* [http://www.freshports.org/x11-wm/xmonad/ FreeBSD]<br />
* [http://packages.gentoo.org/package/xmonad Gentoo]<br />
* [http://packages.debian.org/sid/xmonad Debian]<br />
* [http://packages.ubuntu.com/hardy/xmonad Ubuntu]<br />
* [http://aur.archlinux.org/packages.php?do_Details=1&ID=10593 Arch]<br />
* [http://loupgaroublond.blogspot.com/2007/12/how-to-install-your-very-own-xmonad.html Fedora]<br />
* [http://recipes.gobolinux.org/r/?list=XMonad Gobo]<br />
* [http://nix.cs.uu.nl/nixos/ NixOS]<br />
* [http://codex.sourcemage.org/stable/windowmanagers/xmonad/ Source Mage]<br />
* [http://code.haskell.org/~arossato/xmonad-slack/ Slackware]<br />
<br />
Using your distro package is almost always preferred.<br />
<br />
===Can I install without root permission?===<br />
<br />
Yes, the Haskell libraries that xmonad depends on can all by<br />
installed in the user package database. Simply append --user <br />
to the install phase:<br />
<br />
$ runhaskell Setup.hs install --user<br />
<br />
The library will be registered in your ~/.ghc/ database.<br />
<br />
===How can I use xmonad with a display manager? (xdm, kdm, gdm)===<br />
<br />
The simplest way is to create or modify your ~/.xsession file to run<br />
xmonad. If you don't already have a .xsession, the minimal example<br />
looks like:<br />
<br />
xmonad<br />
<br />
This requires that the ghc and the xmonad executable (or a symlink to them) are in a<br />
directory in the display manager $PATH environment. Alternatively, you can use the full path to xmonad and set ghc's path systemwide. If you do this, you'll also have to change the mod-q binding to use /path/to/xmonad and restart X to have xmonad use the new mod-q (first time only) since the mod-q binding calls xmonad to recompile itself. (See mod-q doesn't work section below.)<br />
<br />
People using 'startx' can use these example [http://code.haskell.org/XMonadContrib/scripts/xinitrc xinitrc] and [http://code.haskell.org/XMonadContrib/scripts/run-xmonad.sh run-xmonad] scripts.<br />
<br />
If you are using xdm, you're done. Login and enjoy xmonad.<br />
<br />
If you're using kdm or gdm (KDE and GNOME's display mangers, respectively),<br />
you're almost done. When logging in, select the entry that says "xsession"<br />
or "default session" from the menu in order to use your ~/.xsession to<br />
start xmonad.<br />
<br />
Alternatively, if you want a menu entry specifically for xmonad, create a<br />
file named "xmonad.desktop" in your /usr/share/xsessions (location varies<br />
by distribution) directory. For example:<br />
<br />
[Desktop Entry]<br />
Encoding=UTF-8<br />
Name=xmonad<br />
Comment=This session starts xmonad<br />
Exec=/usr/local/bin/xmonad<br />
Type=Application<br />
<br />
Replace the "Exec=..." line with the actual path to your xmonad executable,<br />
and you should be able to login by selecting "xmonad" as a session from the<br />
menu in gdm/kdm.<br />
<br />
For instructions on using gdm to launch a full GNOME session with xmonad as<br />
the window manager<br />
[http://haskell.org/haskellwiki/Xmonad/Using_xmonad_in_Gnome#Starting_GNOME_with_xmonad read this].<br />
<br />
===Compiling xmonad on PowerPC and compiler is not interactive===<br />
<br />
If you have ghc installed and are trying to compile xmonad and your compiler <br />
complains about not being interactive, never fear. To compile Setup.hs simply type:<br />
<br />
ghc --make Setup.hs -o Setup<br />
<br />
Now you can:<br />
<br />
./Setup configure<br />
./Setup build<br />
sudo ./Setup install<br />
<br />
If during the build process ghc complains about the "impossible<br />
happening", and mentions that you should change something to "-fvia-C",<br />
just edit the *.cabal file replacing the line that sets the arguments<br />
for ghc, changing "-fasm" to "-fvia-C".<br />
<br />
=== How do I uninstall xmonad? ===<br />
<br />
If you have installed xmonad using your package manager, then just use it.<br />
The following applies if you have built xmonad from source code (either darcs or stable release). Let's assume you've installed xmonad to <br />
<br />
the <code>$PREFIX</code> (that is, gave <code>--prefix=$PREFIX</code> argument to <code>Setup.lhs configure</code>). If unsure, try your <br />
<br />
<code>$HOME</code> and <code>/usr/local</code> as <code>$PREFIX</code>.<br />
<br />
rm -f $PREFIX/bin/xmonad<br />
rm -rf $HOME/.xmonad<br />
rm -rf $PREFIX/lib/xmonad-$VERSION<br />
# If you have installed XMonadContrib:<br />
rm -rf $PREFIX/lib/xmonad-contrib-$VERSION<br />
<br />
If you have installed xmonad 0.5 or newer, also run<br />
ghc-pkg unregister xmonad<br />
# If you have installed XMonadContrib:<br />
ghc-pkg unregister xmonad-contrib<br />
<br />
Do not forget to purge that evil source code!<br />
<br />
=== not found errors or changes to xmonad.hs won't take effect ===<br />
<br />
Ensure that ghc, and the xmonad executable are both in the environment PATH from which you start X. Alternatively symlink them to locations already in the PATH. <code>ghc-pkg list</code> should show ghc, xmonad, X11, etc. without brackets, e.g. {xmonad} is bad. <code>ghc-pkg check</code> will tell you if you have inconsistent dependencies or other registration problems.<br />
<br />
The mod-q action calls the xmonad binary to recompile itself, so if your display manager is starting it with /path/to/xmonad you'll also have to edit your xmonad.hs mod-q binding to use the full path and restart X (or in newer versions use 'xmonad --restart') to restart xmonad with the new mod-q full path binding.<br />
<br />
'''If you recently changed ghc versions''' see [[#Upgraded GHC and now xmonad xmonad-contrib etc are not found]]<br />
<br />
===Configuring xmonad requires GHC, which is 200MB!===<br />
<br />
Yes. You can use [http://braincrater.wordpress.com/2008/09/17/xmonad-light-08-released/ xmonad-light], which allows some of the basic configurations, but if you really want to get the best xmonad experience, you need GHC.<br />
<br />
==Configuration==<br />
<br />
===How do I configure xmonad?===<br />
<br />
By creating and editing the ~/.xmonad/xmonad.hs file, a Haskell source file.<br />
<br />
You can use any Haskell you want in this module. The xmonad-contrib package contains many [http://xmonad.org/xmonad-docs/xmonad-contrib/ extension modules] to make customizing xmonad easier. To have your changes take effect, save the xmonad.hs and either restart (mod-q) or exit X and log back in.<br />
<br />
[[Xmonad/Config_archive|Example configurations]] are available on the wiki.<br />
<br />
For extensive information on configuring, see the links at the top of this page, and [http://haskell.org/haskellwiki/Xmonad/General_xmonad.hs_config_tips the configuration tips] page.<br />
<br />
===Rebinding the mod key (Alt conflicts with other apps; I want the ___ key!)===<br />
<br />
xmonad uses 'alt', actually mod1, as the default modifier. You may<br />
bind to other mod keys by editing your xmonad.hs modMask value, or by<br />
using xmodmap to rebind a key to mod1. The apple command key can be<br />
rebound to mod1 in this way. Use xmodmap to find what key your mod1<br />
is bound to, as well.<br />
<br />
You can rebind the Caps Lock key, to mod, if you wish. See this<br />
[http://lists.suckless.org/dwm/0706/2715.html mailing list item].<br />
<br />
If your new key binding doesn't appear to work, double check it doesn't<br />
clash with an existing binding.<br />
<br />
An example, binding to the mod4 (often 'Win') key:<br />
<br />
<haskell><br />
import XMonad<br />
<br />
main = xmonad defaultConfig<br />
{ modMask = mod4Mask<br />
, terminal = "urxvt"<br />
}<br />
</haskell><br />
<br />
===Multi head and workspaces (desktops)===<br />
See also [[#Multi_head_or_xinerama_troubles|xinerama troubles]] if your multi-head setup doesn't behave as described below.<br />
<br />
XMonad's defaults with multiple monitors may seem confusing and chaotic until explained and illustrated. First we'll look at how things work by default, then at common workspace keybinding customizations.<br />
<br />
To ''focus'' visible workspaces rather than ''swapping'' their screens modify your keybindings as shown in [[#Replacing greedyView with view|the next section below]]. See the section about [[#Other multi head customizations|other customizations]] to give each monitor its own set of workspaces.<br />
<br />
The xmonad man page nicely summarizes how multi-head works by default:<br />
:When running with multiple monitors (Xinerama, TwinView, xrandr), each screen has exactly one workspace visible. Pressing '''<code>mod-{w,e,r}</code>''' switches the focus between screens, while pressing '''<code>shift-mod-{w,e,r}</code>''' moves the current window to that screen. When xmonad starts, workspace 1 is on screen 1, workspace 2 is on screen 2, etc. When switching workspaces to one that is already visible, the current and visible workspaces are swapped.<br />
<br />
'''visible workspaces swap''' (default keybindings): When you have multiple workspaces visible and mod-n to a different ''visible'' workspace, your current one swaps with the other one. We'll see how to change that below, if you don't like the swapping -- simply change 'greedyView' to 'view' in your workspace key bindings. To illustrate with two monitors, using the convention "[1*] [3 ]" to mean workspaces 1 and 3 are visible with left monitor the currently active one:<br />
<br />
<pre><br />
-- 'greedyView' (default) workspace switching (easier to swap visible workspaces)<br />
<br />
-- Typical keystrokes are mod-{w,e,r} to a screen, then mod-N a workspace<br />
<br />
[1*] [3 ] -- mod-3 --> [3*] [1 ] -- mod-e, mod-4 --> [3 ] [4*]<br />
<br />
[3 ] [4*] -- mod-w, mod-4 --> [4*] [3 ]<br />
</pre><br />
<br />
'''my focus moves instead''' (custom workspace switching bindings): By replacing the 'greedyView' function with 'view' in the workspace switching bindings you can have your focus shift to the monitor displaying the given workspace, instead of having that workspace 'brought to you.' (See the next section for examples of how to do this.) For example:<br />
<br />
<pre><br />
-- 'view' workspace switching <br />
<br />
-- (easier to focus another visible workspace, harder to swap)<br />
<br />
[1*] [3 ] -- mod-3 --> [1 ] [3*] -- mod-4 --> [1 ] [4*]<br />
<br />
[1 ] [4*] -- mod-w --> [1*] [4 ] -- mod-4 --> [1 ] [4*]<br />
</pre><br />
<br />
<hask>view</hask> users may also want to add key bindings such as shiftNextScreen and swapNextScreen from the xmonad-contrib extension [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Actions-CycleWS.html XMonad.Actions.CycleWS].<br />
<br />
====Replacing greedyView with view====<br />
Here is an example of changing your workspace switching bindings to use <hask>view</hask> rather than <hask>greedyView</hask> '''using XMonad.Util.EZConfig's additionalKeysP:''' <br />
<br />
(See [http://hackage.haskell.org/packages/archive/xmonad-contrib/latest/doc/html/XMonad-Util-EZConfig.html contrib docs for EZConfig] for more details)<br />
<br />
<haskell><br />
import XMonad<br />
-- skipped<br />
import qualified XMonad.StackSet as W<br />
import XMonad.Util.EZConfig<br />
<br />
main = do<br />
xmonad $ defaultConfig {<br />
workspaces = myWorkspaces<br />
-- skipped<br />
} `additionalKeysP` myKeys<br />
<br />
myWorkspaces = ["1","2","3","4","5","6","7","8","9"]<br />
<br />
myKeys = [<br />
<br />
-- other additional keys<br />
<br />
] ++ -- (++) is needed here because the following list comprehension<br />
-- is a list, not a single key binding. Simply adding it to the<br />
-- list of key bindings would result in something like [ b1, b2,<br />
-- [ b3, b4, b5 ] ] resulting in a type error. (Lists must<br />
-- contain items all of the same type.)<br />
<br />
[ (otherModMasks ++ "M-" ++ [key], action tag)<br />
| (tag, key) <- zip myWorkspaces "123456789"<br />
, (otherModMasks, action) <- [ ("", windows . W.view) -- was W.greedyView<br />
, ("S-", windows . W.shift)]<br />
]<br />
</haskell><br />
<br />
'''For use with additionalKeys or default binding style:'''<br />
<br />
<haskell><br />
-- as above<br />
myKeys =<br />
[<br />
-- other additional keys<br />
]<br />
++<br />
[((m .|. mod1Mask, k), windows $ f i) -- Replace 'mod1Mask' with your mod key of choice.<br />
| (i, k) <- zip myWorkspaces [xK_1 .. xK_9]<br />
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]<br />
</haskell><br />
<br />
====Other multi head customizations====<br />
By default, XMonad doesn't link all your monitor screens into one workspace like Gnome and friends, neither does it use a model like dwm's where each monitor has its own set of workspaces. To set up dwm style workspaces for each screen, see (0.9 or greater) [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-IndependentScreens.html Layout.IndependentScreens]<br />
<br />
==== Screens are in wrong order ====<br />
With xmonad-contrib newer than 0.8.*, (darcs version), see also<br />
[http://haskell.org/haskellwiki/Xmonad/Notable_changes_since_0.8 XMonad.Actions.PhysicalScreens]<br />
<br />
Sometimes drivers don't do what you want, and your screens left to right are something<br />
weird like 1 0 2, so your mod-{w,e,r} bindings are messed up. Your driver may provide a utility to set screen order, but if not, or if you just don't want to mess with<br />
it, here's how to rebind the screen switching bindings:<br />
<br />
Note that if you choose not to use myKeys for the key lists appended together with <hask>++</hask> you will need to add parentheses to get something in the form <hask>`additionalKeys` ( [......] ++ [.......] )</hask>.<br />
<br />
'''Using XMonad.Util.EZConfig's additionalKeysP:'''<br />
<haskell><br />
import XMonad<br />
-- skipped<br />
import qualified XMonad.StackSet as W<br />
import XMonad.Util.EZConfig<br />
<br />
main = do<br />
xmonad $ defaultConfig {<br />
-- skipped<br />
} `additionalKeysP` myKeys<br />
<br />
modm = mod4Mask<br />
<br />
myKeys =<br />
[<br />
-- other additional keys<br />
]<br />
++<br />
[ (mask ++ "M-" ++ [key], screenWorkspace scr >>= flip whenJust (windows . action))<br />
| (key, scr) <- zip "wer" [1,0,2] -- was [0..] *** change to match your screen order ***<br />
, (action, mask) <- [ (W.view, "") , (W.shift, "S-")]<br />
]<br />
</haskell><br />
<br />
'''Using default key binding method or XMonad.Util.EZConfig's additionalKeys:'''<br />
<haskell><br />
-- as above<br />
myKeys =<br />
[<br />
-- other additional keys<br />
]<br />
++<br />
[((m .|. mod1Mask, key), screenWorkspace sc >>= flip whenJust (windows . f)) -- Replace 'mod1Mask' with your mod key of choice.<br />
| (key, sc) <- zip [xK_w, xK_e, xK_r] [1,0,2] -- was [0..] *** change to match your screen order ***<br />
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]<br />
</haskell><br />
<br />
===I don't want the focus to follow the mouse===<br />
<br />
Easy. There is a setting focusFollowsMouse in the xmonad.hs file; set it to False and restart with mod+q.<br />
<br />
=== How do I configure pointer-follows-focus? ===<br />
If you are using > xmonad-0.7, you can use the already defined XMonad.Actions.UpdatePointer:<br />
<haskell><br />
myLogHook = dynamicLogWithPP .... >> updatePointer<br />
</haskell><br />
<br />
For xmonad-0.7, in your config, import [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Actions-Warp.html XMonad.Actions.Warp] from Xmonad contrib and <br />
<br />
add this function:<br />
<haskell><br />
pointerFollowsFocus :: Rational -> Rational -> X ()<br />
pointerFollowsFocus h v = do<br />
dpy <- asks display<br />
root <- asks theRoot<br />
withFocused $ \w -> do<br />
wa <- io $ getWindowAttributes dpy w<br />
(sameRoot,_,w',_,_,_,_,_) <- io $ queryPointer dpy root<br />
if (sameRoot && w == w') then<br />
return ()<br />
else<br />
io $ warpPointer dpy none w 0 0 0 0<br />
(fraction h (wa_width wa)) (fraction v (wa_height wa))<br />
where fraction x y = floor (x * fromIntegral y)</haskell><br />
<br />
Then set the logHook in your config to &ldquo;pointerFollowsFocus <i>x</i> <i>y</i>&rdquo;. If you already have a logHook, append &ldquo; <br />
<br />
>> pointerFollowsFocus <i>x</i> <i>y</i>&rdquo; to it. For example:<br />
<haskell>myLogHook = dynamicLogWithPP defaultPP { ppCurrent = xmobarColor "#60ff45" ""<br />
, ppVisible = xmobarColor "#fffff0" "" } >> pointerFollowsFocus 1 1</haskell><br />
<br />
===Does xmonad support a statusbar?===<br />
<br />
Yes. The Hooks.DynamicLog and Hooks.ManageDocks modules are your friends for this purpose. <br />
<br />
Arbitrary external programs may be used as a statusbar. See for example<br />
[http://gotmor.googlepages.com/dzen dzen] or<br />
[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/xmobar xmobar], an<br />
extensible status bar.<br />
<br />
xmonad lets you use any application as a 'statusbar', as long as it is<br />
visible in a given 'gap' on the screen, and has the override-redirect<br />
property set to true. Many status bar/dock programs already set this<br />
property, for example, dzen. To set other applications, you can<br />
sometimes use normal X resources. For example, to use xclock, launch it<br />
with <br />
<br />
xclock -digital -xrm '*overrideRedirect: True' -geometry 1024x30+0+0<br />
<br />
'''If, like xclock, your app doesn't set wm strut properties''', so that ManageDocks and avoidStruts automatically leaves a gap, '''you can do it manually. Import the Layout.Gaps module and, set a gap of, e.g. (30,0,0,0), in xmonad.hs.''' A similar trick can be done for xsystray.<br />
<br />
Also see the [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-Monitor.html Layout.Monitor] module.<br />
<br />
You can see screenshots of statusbars on [[Xmonad/Screenshots|the screenshots page]].<br />
<br />
You can also use [http://haskell.org/haskellwiki/Xmonad/Using_xmonad_in_Gnome Gnome] or KDE trays and menus with xmonad. The [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-EwmhDesktops.html Hooks.EwmhDesktops], [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Config-Desktop.html Config.Desktop], [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Config-Gnome.html Config.Gnome], [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Config-Kde.html Config.Kde], etc. modules make desktop environment status bars more useful with xmonad.<br />
<br />
To display xmonad logHook output in gnome-panel, see [http://uhsure.com/xmonad-log-applet.html xmonad log applet].<br />
<br />
==== dzen status bars ==== <br />
<br />
xmonad's XMonadContrib library comes with a<br />
really easy function for getting a status bar working with dzen. To use<br />
it, simply have a ~/.xmonad/xmonad.hs containing:<br />
<haskell><br />
import XMonad<br />
import XMonad.Hooks.DynamicLog<br />
<br />
-- 0.9 main:<br />
main = xmonad =<< dzen defaultConfig<br />
-- 0.8.1 main:<br />
main = dzen xmonad<br />
</haskell><br />
which will launch xmonad with dzen2 if found, set up with nice colours<br />
and workspace information. See [[Xmonad/Config_archive/Don%27s_xmonad.hs|Don's config example]] for more information or [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-DynamicLog.html#v%3Adzen DynamicLog dzen's] documentation.<br />
<br />
There is an excellent command-line option and in-text command reference for the SVN version of dzen2 [http://dzen.geekmode.org/dwiki/doku.php?id=dzen:command-and-option-list here]<br />
<br />
====gkrellm or other monitors that aren't bars====<br />
<br />
Gkrellm does not behave like a dock by default. However, there is an option in <code>.gkrellm2/user_config</code> which says <code>dock = 0</code>. If you set it to 1 xmonad will recognize gkrellm as a dock. <br />
<br />
Unfortunately gkrellm usually won't hide under other windows regardless of any combination of <code>above</code> and <code>below</code> options in said config file. Opening and closing the gkrellm config usually resolves this (right click the top of gkrellm and select Configure.. from the menu).<br />
<br />
In xmonad-darcs (will release as xmonad-0.9) the Layout.Monitor module may be helpful.<br />
<br />
====Make space for a panel dock or tray====<br />
<br />
[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-ManageDocks.html ManageDocks] makes it possible for Xmonad to work with panels in the way they expect, automatically leaving the appropriate amount of room for them at the edges of the screen. ''ManageDocks'' has been enabled in the example configuration above. By itself, configuration looks like this:<br />
<br />
<haskell><br />
import XMonad<br />
import XMonad.Hooks.ManageDocks<br />
main = xmonad defaultConfig<br />
{ manageHook = manageDocks <+> manageHook defaultConfig<br />
, layoutHook = avoidStruts $ layoutHook defaultConfig<br />
}<br />
</haskell><br />
<br />
=== Make new windows appear 'below' rather than 'above' the current window ===<br />
See also the [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-InsertPosition.html Hooks.InsertPosition] module for placement hooks other than W.SwapDown to use in stack order manageHooks.<br />
<br />
==== Force a few tiled windows down ====<br />
If you only need to position a few windows below rather than above, and can specify window properties that will avoid matching floating dialogs, etc. then adding a few swapDown manageHooks (or similar from Hooks.InsertPosition referenced above) should do the trick.<br />
<br />
<haskell><br />
import XMonad<br />
import qualified XMonad.StackSet as W<br />
main = xmonad defaultConfig<br />
{ manageHook = composeAll<br />
[ resource =? "downer" --> doF W.swapDown<br />
, title =? "obnoxious window" --> doF W.swapDown<br />
, className =? "MPlayer" --> doFloat<br />
]<br />
}<br />
</haskell><br />
<br />
==== Limit windows forced down by using composeOne ====<br />
To position as many windows as possible below the focus while avoiding problems with z-order while using multiple floating windows, use [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-ManageHelpers.html Hooks.ManageHelpers] composeOne and (-?>) in place of composeAll and (-->) to specify hooks that only fire if earlier ones have not matched. You can use this to add swapDown last in your composeOne list, so that it's applied only to windows that haven't earlier been floated or identified as transient or dialog windows.<br />
<br />
<haskell><br />
import XMonad<br />
import qualified XMonad.StackSet as W<br />
import XMonad.Hooks.ManageDocks (checkDock)<br />
import XMonad.Hooks.ManageHelpers<br />
<br />
main = xmonad defaultConfig<br />
-- no dialogs, gimp or mplayer windows will get swapped down<br />
-- since they matched earlier in the composeOne list<br />
{ manageHook = composeOne<br />
[ checkDock -?> doIgnore -- equivalent to manageDocks<br />
, isDialog -?> doFloat<br />
, className =? "Gimp" -?> doFloat<br />
, className =? "MPlayer" -?> doFloat<br />
, return True -?> doF W.swapDown<br />
]<br />
}<br />
</haskell><br />
<br />
For a more complex composeOne example, see [http://mauke.ath.cx/stuff/xmonad/xmonad.hs mauke's manageHooks].<br />
<br />
==== Force all new windows down ====<br />
(<hask>doF W.swapDown</hask> is the same as using <hask>insertPosition Lower ____</hask>.) To avoid problems with floating window dialogs it's highly recommended to also add an <hask>isDialog</hask> hook as shown below. Adding <hask>doF W.swapDown</hask> to your manageHook will result in new windows being inserted below the focus; for floating windows this means behind the current window. A minimal config would look like this:<br />
<br />
<haskell><br />
import XMonad<br />
import qualified XMonad.StackSet as W<br />
import XMonad.Hooks.ManageHelpers<br />
<br />
main = xmonad defaultConfig<br />
{ manageHook = isDialog --> doF W.shiftMaster <+> doF W.swapDown<br />
-- <br />
-- To prevent unwanted swaps on other workspaces when using<br />
-- this hook with other doShift hooks, make sure to put<br />
-- doF W.swapDown furthest to the right, or last in a <br />
-- composeAll hook list<br />
}<br />
</haskell><br />
<br />
'''Warning:''' <code>doF W.swapDown</code> without restrictions will result in new floating windows popping up ''behind'' focused floating windows, and undesirable focus changes when starting and quickly destroying a window. It is better to only match specific windows to swapDown or use composeOne as shown above.<br />
<br />
==== Avoid the master window, but otherwise manage new windows normally ====<br />
Note that this is not a good solution for people who use floating windows, since many operations on floats put the floating window into the master position. Some transient windows will be swappedDown to appear below the floating parent unless the user keeps a tiled window in master and floating windows lower in the stack at all times. As with swapDown it's best to use it only on specific windows or at the end of a composeOne list if you use floating windows very often.<br />
<br />
<haskell><br />
-- <snip> <br />
import qualified XMonad.StackSet as W<br />
import XMonad.Hooks.ManageHelpers<br />
-- <snip><br />
<br />
myManageHook = fmap not isDialog --> doF avoidMaster<br />
<br />
-- or if you have other stuff in the managehook, more like<br />
-- myManageHook = (otherStuff) <+> (fmap not isDialog --> doF avoidMaster)<br />
<br />
avoidMaster :: W.StackSet i l a s sd -> W.StackSet i l a s sd<br />
avoidMaster = W.modify' $ \c -> case c of<br />
W.Stack t [] (r:rs) -> W.Stack t [r] rs<br />
otherwise -> c<br />
</haskell><br />
<br />
=== Prevent new windows from stealing focus ===<br />
Use a <hask>doF W.focusDown</hask> manageHook on selected windows, or even<br />
on all windows, similar to the swapDown examples above.<br />
<br />
For an avoidMaster that keeps the focus with the master instead of focusing<br />
the newly created window replace <hask>W.Stack t [] (r:rs) -> W.Stack t [r] rs</hask><br />
with <hask>W.Stack t [] (r:rs) -> W.Stack r [] (t:rs)</hask> in the above avoidMaster code.<br />
<br />
===Firefox annoyances===<br />
<br />
====Stop Firefox from taking focus while using EwmhDesktops====<br />
If one uses EWM Hints support, firefox is enabled to choose when you view its workspace, i.e. if you open links from emails or irc or whatever. If you find it annoying... In about:config (vimperator :preferences!) set <code>browser.tabs.loadDivertedInBackground</code> to True to be able to load urls while working elsewhere, then browse them all later when ''you'' choose to shift to the firefox workspace. Also ubuntu users may need to disable the <code>ubufox</code> extension.<br />
<br />
====Firefox's annoying popup downloader====<br />
<br />
Some applications, notably Firefox 1 and 2, create tranisent windows not<br />
set with the transient property. (e.g. firefox's download manager). When<br />
these windows appear, they can take focus and be annoying. For the case<br />
of firefox, the 'Download Statusbar' extension is useful for disabling<br />
this annoying UI feature.<br />
<br />
=== Watch fullscreen flash video ===<br />
Since approximately November 2010, the stock configuration no longer causes flash windows to immediately disappear. However, tiling flash's windows is often not what you want. Try some or all of the following hooks.<br />
<br />
For browser plugins and most apps, including mplayer floated by manage hook (as in the default manageHook) the following setup allows normal toggling of fullscreen. A few mplayer versions are configured to use a different fullscreen method, but they can be made to work with the isFullscreen hook by adding a line <code>fstype=none</code> to ~/.mplayer/config, or using the <code>-fstype=none</code> flag from the command line. See also the end of the faq regarding using handleEventHook instead.<br />
<br />
Add one of the following manageHooks, and modify layoutHook with smartBorders:<br />
<haskell><br />
-- other imports<br />
import qualified XMonad.StackSet as W<br />
import XMonad.Hooks.ManageHelpers<br />
import XMonad.Layout.NoBorders<br />
<br />
main = xmonad defaultConfig {<br />
-- skipped<br />
, layoutHook = smartBorders (yourExistingLayoutHook) -- Don't put borders on fullFloatWindows<br />
, manageHook = myManageHooks<br />
}<br />
<br />
myManageHooks = composeAll<br />
-- Allows focusing other monitors without killing the fullscreen<br />
-- [ isFullscreen --> (doF W.focusDown <+> doFullFloat)<br />
<br />
-- Single monitor setups, or if the previous hook doesn't work<br />
[ isFullscreen --> doFullFloat<br />
-- skipped<br />
]<br />
</haskell><br />
If you have multi-head and the focusDown hook doesn't work for you, in darcs xmonad/xmonad-contrib (greater than 0.9.1) XMonad.Hooks.EwmhDesktops has a fullscreenEventHook that is also worth a try. Add it to any existing handleEventHook with <+>, or simply use it as your handleEventHook if you don't already have one. This also is useful for people who prefer tiling mplayer when not fullscreened, or use totem, vlc, or other players that require something like fullscreenEventHook to work at all.<br />
<br />
=== Floating a window or sending it to a specific workspace by default ===<br />
<br />
See [[Xmonad/General_xmonad.hs_config_tips | General xmonad.hs config tips]] regarding manageHook, and the section [[#I need to find the class title or some other X property of my program | here]] about 'xprop' for this.<br />
<br />
===Startup programs===<br />
<br />
You may launch programs at startup in the usual X manner: by adding<br />
them to your .xsession or .Xinitrc. For example, the following<br />
.xsession file launches xpmroot to<br />
set the background image, xmodmap to rebind caps lock to ctrl. It<br />
then launches a status bar program with dzen, before finally<br />
launching xmonad:<br />
<br />
# .xsession<br />
xpmroot ~/.bg/407511721_eb8559457c_o.xpm &amp;<br />
xrdb -merge .Xresources<br />
<br />
xmodmap -e "remove Lock = Caps_Lock"<br />
xmodmap -e "keysym Caps_Lock = Control_L"<br />
xmodmap -e "add Control = Control_L"<br />
<br />
status | dzen2 -ta r -fg '#a8a3f7' \<br />
-bg '#3f3c6d' \<br />
-fn '-*-terminus-medium-r-normal--16-*' \<br />
-e "button1=exec:xterm" &amp; <br />
urxvt &amp;<br />
<br />
$HOME/bin/xmonad<br />
<br />
You may also launch applications from your xmonad.hs, using startupHook, however this runs each time xmonad is restarted with mod-q. Also in > xmonad-0.8 see spawnPid, mkSpawner, spawnOn.<br />
<br />
Use manageHook to arrange your programs on different workspaces by matching various window properties such as className, appName (resource), title, or role.<br />
<br />
===Using floating windows===<br />
Use the regular swap or focus up and down to navigate them, and regular mod-enter to raise a window to the front. For a mod-enter binding, the darcs shiftMaster works better than swapMaster if you use multiple floats over tiled windows. See also this<br />
[[#Force_all_new_windows_down|swapDown manage hook warning]] above. If you use that manageHook on all windows you will create new floats behind existing ones. If you use lots of floats for some reason for better float usability see SimpleFloat layout, FloatKeys, Hooks.Place, and Config.Bluetile in xmonad-contrib.<br />
<br />
===Setting the X cursor===<br />
<br />
By default xmonad doesn't set a particular X cursor, which usually<br />
means the default X cursor will be used by the system. To set your<br />
own custom cursor, use the xsetroot program, as follows, from your<br />
startup file, i.e. .xinitrc, .xsession, display manager startup or<br />
.Desktop files:<br />
<br />
# For example, a nice left-pointing arrow head cursor<br />
<br />
xsetroot -cursor_name left_ptr<br />
<br />
If you have development headers for X11, other cursors can be found in /usr/include/X11/cursorfont.h<br />
<br />
Note that some display managers, such as "slim", don't unset the changes<br />
they make to the cursor when the window manager starts. This can be worked<br />
around by setting the cursor, as above.<br />
<br />
=== Removing the borders around mplayer ===<br />
<br />
You can also use the fullscreen layout, with the [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-NoBorders.html NoBorders] smartBorders layout modifier, which automatically takes care of most cases.<br />
<br />
To add 'smartBorders' to the default tiling modes:<br />
<haskell><br />
import XMonad<br />
import XMonad.Layout.NoBorders<br />
<br />
main = xmonad $ <br />
defaultConfig<br />
{ layoutHook = smartBorders $ layoutHook defaultConfig<br />
-- other fields like terminal, modMask, etc.<br />
}<br />
</haskell><br />
<br />
<br />
<br />
You can also remove borders with a key binding using [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Actions-NoBorders.html Actions.NoBorders] extension. There's drawback: you need manually remove border any time you launch mplayer.<br />
<br />
Although this action should be able to be automated, unfortunately you cannot<br />
currently use manageHook for this purpose. That's because borders are drawn<br />
''after'' runManageHook is executed (see Operations.hs for details).<br />
<br />
Alternatively you can manually move the mplayer window 1 pixel to the left and<br />
one pixel up by importing XMonad.Actions.FloatKeys and adding a keybinding<br />
similar to ((modm, xK_b), withFocused (keysMoveWindow (-1,-1)). (I have not<br />
tested yet if this can be used in combination with the manageHook.)<br />
<br />
===I need to find the class title or some other X property of my program===<br />
<br />
When using XMonad.Layout.IM, ManageHooks, XMonad.Actions.WindowGo, or several other modules you need to specify detailed information about a window's properties.<br />
<br />
See below for a script to nicely format output from the <tt>xprop</tt> program discussed in detail in this FAQ.<br />
<br />
Otherwise, you can generally find what you need by splitting your screen between the window and a terminal; in the terminal, run <tt>xprop WM_CLASS</tt> or the like, and then click on the window. xprop will print out quite a bit of useful information about the window. <br />
* '''resource''' (also known as '''appName''') is the first element in WM_CLASS(STRING)<br />
* '''className''' is the second element in WM_CLASS(STRING)<br />
* '''title''' is WM_NAME(STRING)<br />
<br />
For example, in <code> WM_CLASS(STRING) = "emacs", "Emacs" </code> -- "emacs" is resource (appName), "Emacs" is className.<br />
<br />
(Applications may change the title after window creation, before xprop sees it. If possible, use resource or class in such cases.) stringProperty "WM_WINDOW_ROLE" can also be useful.<br />
<br />
Sample output might look like:<br />
<br />
<pre>_MOTIF_DRAG_RECEIVER_INFO(_MOTIF_DRAG_RECEIVER_INFO) = 0x6c, 0x0, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0<br />
XdndAware(ATOM) = BITMAP<br />
WM_STATE(WM_STATE):<br />
window state: Normal<br />
icon window: 0x0<br />
WM_HINTS(WM_HINTS):<br />
Client accepts input or input focus: True<br />
Initial state is Normal State.<br />
window id # of group leader: 0xf600001<br />
_NET_WM_SYNC_REQUEST_COUNTER(CARDINAL) = 257949716<br />
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_NORMAL<br />
_NET_WM_USER_TIME_WINDOW(WINDOW): window id # 0xf600013<br />
WM_CLIENT_LEADER(WINDOW): window id # 0xf600001<br />
_NET_WM_PID(CARDINAL) = 476661<br />
WM_LOCALE_NAME(STRING) = "en_US.utf8"<br />
WM_CLIENT_MACHINE(STRING) = "localhost"<br />
WM_NORMAL_HINTS(WM_SIZE_HINTS):<br />
program specified minimum size: 32 by 34<br />
program specified resize increment: 8 by 17<br />
program specified base size: 16 by 0<br />
window gravity: NorthWest<br />
WM_PROTOCOLS(ATOM): protocols WM_DELETE_WINDOW, WM_TAKE_FOCUS, _NET_WM_PING, _NET_WM_SYNC_REQUEST<br />
WM_CLASS(STRING) = "emacs", "Emacs"<br />
WM_ICON_NAME(STRING) = "emacs@craft"<br />
_NET_WM_ICON_NAME(UTF8_STRING) = 0x45, 0x4d, 0x41, 0x43, 0x53<br />
WM_NAME(STRING) = "EMACS"<br />
_NET_WM_NAME(UTF8_STRING) = 0x45, 0x4d, 0x41, 0x43, 0x53<br />
</pre><br />
<br />
Note: the last several lines contain useful information like the CLASS and<br />
hinting information.<br />
<br />
==== What about other properties, such as WM_WINDOW_ROLE? ====<br />
Use <code>stringProperty</code> to extract string information, for<br />
example:<br />
<br />
<pre><br />
stringProperty "WM_WINDOW_ROLE" =? "presentationWidget" --> doFloat<br />
</pre><br />
<br />
For non-string properties, try [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-ManageHelpers.html XMonad.Hooks.ManageHelpers].<br />
<br />
Consult the [http://xmonad.org/xmonad-docs/xmonad/XMonad-ManageHook.html XMonad.ManageHook] documentation for more information.<br />
<br />
==== A handy script to print out window information ====<br />
<br />
This script will print window information (if available) in formats usable within <tt>xmonad.hs</tt>. It is also included in the $src/XMonadContrib/scripts directory with<br />
darcs XMonadContrib (>= 0.10).<br />
<br />
#! /bin/sh<br />
exec xprop -notype \<br />
-f WM_NAME 8s ':\n title =\? $0\n' \<br />
-f WM_CLASS 8s ':\n appName =\? $0\n className =\? $1\n' \<br />
-f WM_WINDOW_ROLE 8s ':\n stringProperty "WM_WINDOW_ROLE" =\? $0\n' \<br />
WM_NAME WM_CLASS WM_WINDOW_ROLE \<br />
${1+"$@"}<br />
<br />
It works like <tt>xprop</tt>: by default you click on a window with the crosshairs, or you can specify windows using the <tt>-id</tt> or <tt>-name</tt> options. (The <tt>-root</tt> and <tt>-font</tt> selectors could be used, but are less than useful. Also, <tt>-frame</tt> is unlikely to do anything useful.)<br />
<br />
See [[Xmonad/General_xmonad.hs_config_tips#Matching_specific_windows_by_setting_the_resource_name_or_class|Matching specific windows by setting the resource name or class]] for how you can change what programs use for some of these strings.<br />
<br />
=== What is the xK_ value for this key? ===<br />
Pressing the key of interest while focusing a xev window gives useful information.<br />
To limit xev's output use something like:<br />
<br />
<code>xev | sed -ne '/^KeyPress/,/^$/p'</code><br />
<br />
A complete list can be found at [[Xmonad/Key_codes|XMonad key symbols]].<br />
<br />
=== How can I send a key sequence to a window? ===<br />
<br />
This can be useful when some application uses a hotkey that you<br />
want to use in XMonad, yet be able to send the application window the<br />
hotkey when needed.<br />
<br />
A solution is to use [http://www.semicomplete.com/projects/xdotool/ xdotool], <br />
which can (among other nifty things), send a fake keypress to the<br />
currently focused window. So, for instance, you can use the following<br />
keybinding to send Alt+L to the focused window by pressing Ctrl+Alt+L:<br />
<br />
, ((mod1Mask|controlMask, xK_l), spawn "xdotool key alt+l")<br />
<br />
[http://www.semicomplete.com/projects/xdotool/ xdotool] can also paste<br />
a line of ASCII text into the focused window. For instance, the<br />
following keybinding will insert the email address email@example.org<br />
each time the key Ctrl+Alt+e is pressed:<br />
<br />
, ((mod1Mask|controlMask, xK_e), spawn "xdotool text 'email@example.org'")<br />
<br />
The <code>XMonad.Util.Paste</code> module (in >= xmonad-contrib-0.9) defines functions to to the same with<br />
pure Haskell code.<br />
<br />
=== I don't use a statusbar, but I'd like to have layout displayed for some time when it changes ===<br />
<br />
Let's assume you have <hask>import qualified XMonad.StackSet as W</hask> in xmonad.hs.<br />
<br />
Add the following declaration somewhere in the toplevel:<br />
<haskell>curLayout :: X String<br />
curLayout = gets windowset >>= return . description . W.layout . W.workspace . W.current</haskell><br />
<br />
Then add the keybinding:<br />
<haskell><br />
, ((mod1Mask, xK_a ), sendMessage NextLayout >> (curLayout >>= \d->spawn $"xmessage "++d))<br />
</haskell><br />
<br />
You might want to change xmessage to the more friendly program, such as osd_cat, qt-dialog or dzen2.<br />
<br />
Another option is to use<br />
[http://www.xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-ShowWName.html Layout.ShowWName] <br />
which has some user configurable options such as font, color and fade timings.<br />
<br />
More flexible way is to use <code>dynamicLogString</code> from <code>XMonad.Hooks.DynamicLog</code> (was added after 0.6 release), which can also display current workspace, window name, layout, and even arbitrary <hask>[X (Maybe String)]</hask>, and format them nicely, printing them to xmonad's stdout.<br />
<br />
===How can I make xmonad use UTF8?===<br />
<br />
TODO: is this still accurate? Doesn't xmonad-0.8 and greater always use UTF8 with no extra imports or configuration changes?<br />
<br />
Due to extensions like [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-DynamicLog.html DynamicLog], xmonad is capable of text outputting which is not by default but can be encoded in UTF8. Therefore, if you want to output non-ASCII characters, you can take advantage of the [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/utf8-string System.IO.UTF8] module.<br />
<br />
For example using DynamicLog you can define its output [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-DynamicLog.html#v%3AppOutput ppOutput] like his:<br />
<haskell><br />
import qualified System.IO.UTF8<br />
-- lots of other stuff<br />
ppLog = defaultPP<br />
{ ppOutput = \s -> do<br />
h <- openFile "/home/$USER/.xmonad/xmonad.log" WriteMode<br />
System.IO.UTF8.hPutStrLn h s<br />
hClose h<br />
}<br />
</haskell><br />
<br />
As it may not be ideal to reopen the file before every writing, you can just place the code somewhere else. See ray's config in xmonad's [[Xmonad/Config_archive|config archive]].<br />
<br />
===How do I use compositing with xmonad?===<br />
<br />
Xmonad has the ability to use some compositing features yet still be actually useable ;-). For example, some really nice transparency can be used with a composite aware app like urxvt and xcompmgr. <br />
<br />
First enable compositing in your X server configuration by including the following in your xorg.conf<br />
<br />
<pre><br />
Section "Extensions"<br />
Option "Composite" "enable"<br />
EndSection<br />
</pre><br />
<br />
restart the X server and confirm it's working with xdpyinfo | grep Composite. If it returns Composite, then good...<br />
<br />
Include this in ~/.Xdefaults<br />
<br />
<pre><br />
URxvt.depth: 32<br />
URxvt*background: rgba:0000/0000/0000/cccc<br />
</pre><br />
<br />
this specifies that urxvt uses 32 bit colors and uses a transparent black background. The four c's specify the amount of alpha with ffff being full black and 0000 being fully transparent. You can also use the fading and blurRadius resources to give some nice effects in the transparency. see man urxvt.<br />
<br />
finally you need to fire up xcompgr so that this will all actually work. probably you'll want to include it in your ~/.xinitrc or ~/.xsession file:<br />
<br />
<pre><br />
xcompmgr -c &<br />
</pre><br />
<br />
the -c option provides a soft shadow around your windows. There are many options, see man xcompmgr. <br />
<br />
For an example with screenshots see andrewsw's config in the [[Xmonad/Config_archive|config archive]].<br />
<br />
On newer versions of XMonad, see also '''XMonad.Hooks.FadeInactive''' documentation.<br />
<br />
=== How do I find a function which does ...? ===<br />
<br />
[http://holumbus.fh-wedel.de/hayoo/hayoo.html Hayoo!] API search can be used to find existing functions within XMonad and XMonadContrib which do useful things. For example, the search string<br />
(next AND screen) package:xmonad<br />
will find all existing functions which mention moving to the next Xinerama screen.<br />
<br />
==Troubleshooting==<br />
<br />
===Multi head or xinerama troubles===<br />
====xmonad does not detect my multi-head setup====<br />
<br />
To diagnose the problem, execute the following on the command line:<br />
<br />
ghc -e Graphics.X11.Xinerama.compiledWithXinerama<br />
<br />
If the output is True, skip to the getScreenInfo test below. If the output is False, your Haskell X11 library was not built against Xinerama. This is true of old Debian and Ubuntu packages, and may also occur if you built from source.<br />
<br />
First, be sure that the Xinerama development headers are installed (libxinerama-dev in Debian and Ubuntu).<br />
<br />
Next, check the configure output for the Haskell X11 library for the following lines (If using cabal: cabal install X11 -v --reinstall):<br />
<br />
checking X11/extensions/Xinerama.h usability... yes<br />
checking X11/extensions/Xinerama.h presence... yes<br />
checking for X11/extensions/Xinerama.h... yes<br />
<br />
If any of these lines end in "no", the Xinerama headers are not installed. If the lines end in "yes", execute:<br />
<br />
runghc Setup clean<br />
runghc Setup configure --user --prefix=$HOME<br />
runghc Setup build<br />
runghc Setup install<br />
<br />
In the X11, xmonad and xmonad-contrib source directories. Try the compiledWithXinerama diagnostic again, this time it should return True. As always, execute "xmonad --recompile" when reinstalling any part of xmonad.<br />
<br />
If compiledWithXinerama is True and multi-head still doesn't work, execute "xmonad --recompile" and press mod-q. If the problem persists, execute this command:<br />
<br />
ghc -e "Graphics.X11.openDisplay [] >>= Graphics.X11.Xinerama.getScreenInfo"<br />
<br />
Here is a sample output from a system with two 1280 by 1024 monitors, oriented side by side:<br />
<br />
[Rectangle {rect_x = 0, rect_y = 0, rect_width = 1280, rect_height = 1024}, Rectangle {rect_x = 1280, rect_y = 0, rect_width = 1280, rect_height = 1024}]<br />
<br />
Check to see whether there is a Rectangle corresponding to each of your screens. If there is not, and the compiledWithXinerama diagnostic returns True, there may be a problem with your X server configuration. The most common one is having your monitors set to ''clone'' one another. See 'man xrandr', or, if using the proprietary nvidia drivers, 'nvidia-settings' to see how reconfigure them.<br />
<br />
Also, there can be two versions of the X11 haskell library installed, one of them built with Xinerama, and other without it. If XMonad is using the one built with Xinerama, and the output of the commands use the version without it, all these tests will work but these problems will persist. Check the output of ghc-pkg to see if there is more than one version of X11 installed.<br />
<br />
====Missing X11 headers====<br />
<br />
Your build will fail if you've not installed the X11 C library headers<br />
at some point. ./configure for the Haskell X11 library will fail. To<br />
install the X11 C libs:<br />
<br />
* debian<br />
<br />
apt-get install libx11-dev<br />
<br />
====X11 fails to find libX11 or libXinerama====<br />
<br />
Cabal has difficulty locating library directories on some<br />
platforms (such as the Mac or RHEL4). First, locate the<br />
directory that contains libX11.so (libX11.dylib on Mac OS<br />
X). Add the following line to the .cabal file for the<br />
package:<br />
<br />
extra-lib-dirs: /your/path/here/<br />
<br />
For example, on a 64 bit machine you might need to add:<br />
<br />
extra-lib-dirs: /usr/X11R6/lib/lib64<br />
<br />
You can also add the paths to your .buildinfo file, or set the<br />
LD_LIBRARY_PATH environment variable.<br />
<br />
====Something is weird with multi head windows or workspaces (desktops)====<br />
See [[#Multi head and workspaces (desktops)|Configuration: Multi head and workspaces]]<br />
<br />
===X Error of failed request: BadAccess (attempt to access private resource denied)===<br />
This message seen at xmonad's stdout when starting xmonad means that another window manager is already running. If the other WM was started from a DE, you can use [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Util-Replace.html Util.Replace] to have xmonad ask the other WM to exit before starting up. Note: If exiting your previously running wm would lead to your X session ending, then this method won't work. <br />
<br />
Otherwise refer to the appropriate page for starting xmonad instead of your other WM ([[Xmonad/Using xmonad in Gnome|Gnome]], [[Xmonad/Using xmonad in KDE|KDE]]).<br />
<br />
===mod-q doesn't work===<br />
====Upgraded GHC and now xmonad xmonad-contrib etc are not found====<br />
When you change ghc versions you need to rebuild or reinstall haskell libraries to make sure they are compatible and registered with the new ghc. Often your distro packagers will try to make this as automatic as possible, by making it just happen. Or at least they will make it easier, e.g. gentoo's ghc-updater and haskell-updater. (This isn't just a Haskell/ghc issue; it's true for other languages, too: c.f. python-updater scripts, distro policies regarding gcc and glibc changes.)<br />
<br />
==== Changes to the config file ignored or 'xmonad not found' when starting X ====<br />
<br />
Both ghc and xmonad must be in your display manager init's $PATH when starting X and xmonad for reconfiguration by mod-q. Make sure the environment from which you start xmonad has the appropriate settings.<br />
<br />
When changing the xmonad.hs and restarting with mod-q, xmonad will attempt to exec the xmonad binary. This means it must be in your $PATH environment variable, or the exec will fail silently and the old xmonad instance keeps running.<br />
<br />
With xmonad 0.5 and later, mod-q will also call ghc on your ~/.xmonad/xmonad.hs file, and will continue with defaults if ghc is not found.<br />
<br />
Additionally, if you change and reinstall the haskell-X11 or XMonadContrib library, changes to that package will not be noticed by xmonad's recompilation<br />
checker, so xmonad.hs won't be recompiled. ''(needs confirmation: is this true?)'' To fix this:<br />
<br />
xmonad --recompile<br />
<br />
after reinstalling the contrib library.<br />
<br />
===Tabbed or other decorated layouts not shown===<br />
Both xmobar and xmonad's default <br />
[http://hackage.haskell.org/packages/archive/xmonad-contrib/latest/doc/html/XMonad-Layout-Tabbed.html Theme] <br />
use the <code>-misc-fixed-*-*-*-*-10-*-*-*-*-*-*-*</code> font by default. This is<br />
possibly the most commonly installed font in the *nix world, but if it's not installed,<br />
or core fonts aren't working for some reason, you'll have problems. Without the font<br />
you have set in your Theme....<br />
<br />
tabs and other decorated layouts will simply not draw. There should be font related errors<br />
in .xsession-errors or wherever your display manager directs stderr to help confirm that<br />
this is the cause of missing decorations. xmobar will spit out a cryptic error message<br />
and refuse to run.<br />
<br />
Check with xfontsel that you have the fixed 10 font if you want to use the defaults.<br />
For xft, check that your xmonad and xmobar were compiled with xft support. (They are<br />
by default on most distros) Then customize your theme by using something like the<br />
following in your layoutHook<br />
<haskell><br />
myTabbed = tabbed shrinkText defaultTheme {<br />
fontName = "xft:terminus:size=12" -- choose an installed font<br />
-- more theme customizations<br />
}<br />
<br />
main = do<br />
-- skipped<br />
, layoutHook = avoidStruts $ myTabbed ||| layoutHook defaultConfig<br />
} <br />
</haskell> <br />
<br />
===DE panels pagers or EwmhDesktops are broken (just upgraded to >0.8)===<br />
Starting with 0.9, <br />
EwmhDesktops users ''must'' [http://code.haskell.org/XMonadContrib/XMonad/Hooks/EwmhDesktops.hs change configuration] by removing the obsolete ewmhDesktopsLayout from layoutHook, (it no longer exists), and updating to the current ewmh support which still includes a logHook, but in place of the old layout modifier, uses a startupHook and handleEventHook (see ff.).''(No need to change config if using ewmh via Config.Desktop, Config.Gnome, etc. Your config will automatically be updated to use current ewmh support.)<br />
<br />
Users of defaultConfig that explicitly include EwmhDesktops hooks and the ewmhDesktopsLayout modifier should remove them and instead use the new <hask>ewmh</hask> function which adds EWMH support to <hask>defaultConfig</hask> all at once. You should keep avoidStruts and manageDocks if you're using them.<br />
<br />
The 0.9 way to use EwmhDesktops rather than a desktop config is:<br />
<haskell><br />
import XMonad<br />
import XMonad.Hooks.EwmhDesktops<br />
<br />
main = xmonad $ ewmh defaultConfig {<br />
-- normal customizations<br />
}<br />
</haskell><br />
<br />
===defaultGaps doesn't work any more! (just upgraded to >0.7)===<br />
See [[#Make space for a panel dock or tray | Make space for a panel]] section: use XMonad.Hooks.ManageDocks avoidStruts for this instead of Gaps, or import XMonad.Layout.Gaps.<br />
<br />
===Showing fractions of lines in gvim, urxvt,etc.===<br />
<br />
This is due to certain layouts doesn't care about so called size hints<br />
(resize increments) specifically the WM_NORMAL_HINTS(WM_SIZE_HINTS) (use<br />
xprop to see it). This, combined with certain programs, like gvim, which<br />
doesn't check if it gets enough size to render the last line and uses it anyway<br />
render this annoying behaviour. Aside from patching the offending program, you can:<br />
<br />
<ol><br />
<li>Use a layout which uses these size hints like Hinted Grid, or HintedTile</li><br />
<li>Use the [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-LayoutHints.html layoutHints] modifier on any layout</li><br />
<li>Workaround in .vimrc. These lines in your .vimrc lets you change the number of lines with F4/Shift-F4:</li><br />
<pre><br />
map <F4> :let &lines=&lines-1<CR><br />
map &lt;S-F4&gt; :let &lines=&lines+1<CR><br />
</pre><br />
<li>Change the color of default GTK background (white lines), to match gvim background</li><br />
<pre><br />
style "vimfix" { bg[NORMAL] = "#000000" }<br />
widget "vim-main-window.*GtkForm" style "vimfix"<br />
</pre><br />
</ol><br />
<br />
===Emacs mini-buffer starts at wrong size===<br />
ontoillogical says: Most people turn off menus and toolbars and adjust fonts in their .emacs. That's what breaks emacs' display in tiling WMs. To get emacs to look correctly, move all of the stuff that affects how emacs draws a frame to .Xdefaults/.Xresources<br />
<br />
For reference here is the relevant section of mine:<br />
<br />
Emacs.font: DejaVu Sans Mono-12<br />
Emacs.fontBackend: xft<br />
Emacs.menuBar: off<br />
Emacs.toolBar: -1<br />
Emacs.verticalScrollBars: off<br />
<br />
If you're having emacs sizing problems setting these in .Xdefaults is still worth a try even if you don't have any custom .emacs settings.<br />
<br />
===Losing text when resizing xterms===<br />
<br />
Being a dynamic tiling window manager, xmonad, like ion or dwm, makes heavy use of resizing. Clients such as xterm, might not take well to resizing and the window might require a refresh (Ctrl-L). To minimize this, several users recommend urxvt (rxvt-unicode), which handles resizing much better.<br />
<br />
=== I just resized my terminal, but the terminal app didn't resize. ===<br />
This is a SIGWINCH bug in the Linux kernel, believe it or not, in the 2.6.26 series. Details here: http://groups.google.com/group/fa.linux.kernel/browse_thread/thread/8044876def45c0b0/4b7f4cd87feafe5e?show_docid=4b7f4cd87feafe5e.<br />
<br />
The simplest solution is to up/downgrade to a kernel version without this bug.<br />
<br />
===XMonad is frozen!===<br />
<br />
==== XMonad stops but the current window still responds to keys ====<br />
<br />
Usually this is because a dynamicLog is writing to a pipe handle that's not being read. For example the xmonad.hs writes to some status bar in the logHook, but the status bar is not installed, not in $PATH, not set up to read its stdin, or just plain not running. Eventually the pipe fills up and blocks and xmonad waits for it to be read before continuing.<br />
<br />
To cat the full pipe and free up xmonad, find xmonad's pid via pgrep or htop, etc. let's say it's 1001, then <code>ls -l /proc/1001/fd/</code> and look for the largest numbered pipe. Let's use 4. Then <code>cat /proc/1001/fd/4</code> to unblock xmonad so you can fix your xmonad.hs and xmobarrc to work correctly. (If catting that pipe doesn't spew out a bunch of stuff and unfreeze things, try the others listed.)<br />
<br />
With the post 0.9 <hask>=<< xmobar</hask> and <hask>statusBar</hask> modifiers it isn't obvious that xmonad is writing to a pipe. If you don't want xmonad info shown in your<br />
status bar, you will probably be better off launching it by other means such as .xinitrc. You can also customize your PP's ppOutput field to use the default <hask>hPutStrLn</hask> to write to stdout, or change it to <hask>\s -> return ()</hask> to do nothing at all.<br />
<br />
<em>With xmobar</em>, if your logHook is writing to its stdin via <hask>ppOutput = hPutStrLn foo</hask>, make sure the .xmobarrc <hask>commands</hask> include a <hask>Run StdinReader</hask> line, and the <hask>template</hask> includes <hask>%StdinReader%</hask>.<br />
<br />
For examples of an .xmobarrc with working StdinReader, see this [https://wiki.archlinux.org/index.php/Xmonad#Using_xmobar_with_xmonad arch linux help page] or [[Xmonad/Config_archive/John_Goerzen%27s_Configuration|John Goerzen's xmonad config tutorial]].<br />
<br />
See also [http://code.google.com/p/xmonad/issues/detail?id=91 this issue] on the xmonad bug tracker.<br />
<br />
==== XMonad stops responding to keys (usually due to unclutter) ====<br />
<br />
The number one cause for this is the 'unclutter' program, which can fool<br />
some clients into thinking they've lost the pointer, when in fact they have<br />
not. See the '-noevents' flag to unclutter.<br />
Or use [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Actions-Warp.html XMonad.Actions.Warp] or [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Actions-UpdatePointer.html XMonad.Actions.UpdatePointer] xmonad-contrib extension instead.<br />
<br />
==== An app seems to have frozen and xmonad stops responding to keys ====<br />
<br />
Often you can get X to behave again by running 'xclock -display :0' on the appropriate display via ssh or from a virtual terminal. If that's not enough kill suspect apps similarly.<br />
<br />
There is also an option in (pre evdev versions of) xorg.conf which enables the key combination '''Ctrl+Alt+Keypad-Divide''' to break active keyboard and mouse grabs. <br />
<br />
This may allow xmonad to continue normally in such cases. To enable this key combination, add the following line to your xorg.conf in the Section ''Server Flags'' then restart X:<br />
<br />
Option "AllowDeactivateGrabs" "on"<br />
<br />
=== Problems with Java applications, Applet java console ===<br />
<br />
There are two classes of problems: blank, grey windows and windows that can't be focused for keyboard input. The latter should be fixed in the newest xmonad, so follow the instructions on the website for getting a copy of the darcs repository and build it. Remember to rebuild xmonad-contrib (preferably also from darcs) afterwards! The remainder of this section covers the blank, grey window problems.<br />
<br />
The Java gui toolkit has a hardcoded list of so-called "non-reparenting"<br />
window managers. xmonad is not on this list (nor are many of the newer window<br />
managers). Attempts to run Java applications may result in `grey blobs' where<br />
windows should be, as the Java gui code gets confused.<br />
<br />
====Preferred Method====<br />
If you are using openjdk6 >= 1.6.1, the cleanest way to work around the hardcoded list is to warn the vm that xmonad is non-reparenting by exporting the appropriate environment variable:<br />
<br />
_JAVA_AWT_WM_NONREPARENTING=1<br />
<br />
Using JDK 7 seems to work well, too, see below.<br />
<br />
====Using SetWMName====<br />
Otherwise, you can lie to Java about what window manager you are using, by having the [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-SetWMName.html SetWMName] extension convince Java that xmonad is '''"LG3D"'''. Normally you would use this in<br />
startup hook, like this:<br />
<br />
<haskell><br />
-- etc<br />
import XMonad.Hooks.SetWMName<br />
<br />
main = do<br />
xmonad $ defaultConfig<br />
{ modMask = mod4Mask<br />
, startupHook = setWMName "LG3D"<br />
-- other customizations<br />
}<br />
</haskell><br />
'''However''', modules using Hooks.EwmhDesktops, such as Config.Gnome, Config.Desktops, etc. also set WM Name as part of supporting Extended Window Manager Hints. Combining EWMH support with the "LG3D" workaround takes special attention to modifying the appropriate hook for your xmonad version:<br />
<br />
'''Starting with xmonad-0.9'''. the window manager name is set once in EWMH '''''startupHook''''' after each mod-q, along with other EWMH initialization, but after that can be changed and not overwritten till the next mod-q. See below for example startupHooks combining both startupHooks.<br />
<br />
'''In xmonad versions 0.7 and 0.8''' the EWMH configs setWMName to "xmonad" on each '''''logHook''''' event, so to use "LG3D" instead, it's necessary to either<br />
* patch the XMonad.Hooks.EwmhDesktops source and rebuild xmonad-contrib<br />
OR<br />
* use the version 0.8.* hack shown below to repeatedly setWMName "LG3D" after the ewmh logHook runs.<br />
<br />
==== Using SetWMName with EwmhDesktops ====<br />
<br />
For '''xmonad-0.9 0.9.1 or darcs''':<br />
<br />
Add ewmhDesktopsStartup, (or 'startupHook gnomeConfig', etc.) to '''''startupHook''''' ''before'' setWMName.<br />
<br />
Defining the EWMH hooks yourself:<br />
<haskell><br />
-- etc<br />
import XMonad.Hooks.EwmhDesktops<br />
import XMonad.Hooks.SetWMName<br />
<br />
main = xmonad defaultConfig<br />
{ -- skipped<br />
, startupHook = ewmhDesktopsStartup >> setWMName "LG3D"<br />
}<br />
</haskell><br />
<br />
Using a desktop config as your base:<br />
<haskell><br />
xmonad desktopConfig<br />
{ -- skipped<br />
, startupHook = startupHook desktopConfig >> setWMName "LG3D"<br />
}<br />
</haskell><br />
<br />
If instead you're using the ewmh config modifier to add EWMH support, then define your config at top-level to allow over-riding the startupHook definition with your own version:<br />
<haskell><br />
-- etc<br />
import XMonad.Hooks.EwmhDesktops<br />
import XMonad.Hooks.SetWMName<br />
<br />
-- define an EWMH base config to use later in main<br />
conf = ewmh defaultConfig<br />
{ manageHook = myManageHooks <+> manageDocks <+> manageHook defaultConfig<br />
, layoutHook = avoidStruts $ myLayout ||| layoutHook defaultConfig<br />
, logHook = dynamicLogWithPP xmobarPP<br />
{ ppOutput = hPutStrLn xmproc<br />
, ppLayout = const ""<br />
, ppTitle = xmobarColor "green" "" . shorten 80<br />
}<br />
}<br />
<br />
-- Override the WM Name setting for the "LG3D" workaround<br />
-- but still use the rest of the EWMH base config you just<br />
-- defined, including its startupHook ewmh initialization<br />
<br />
main = do<br />
xmproc <- spawnPipe "xmobar"<br />
xmonad conf<br />
{ startupHook = startupHook conf >> setWMName "LG3D"<br />
}<br />
</haskell><br />
<br />
For '''xmonad-0.8.*''' :<br />
<haskell><br />
-- etc<br />
import XMonad.Hooks.EwmhDesktops<br />
import XMonad.Hooks.ManageDocks<br />
import XMonad.Hooks.SetWMName<br />
<br />
main = do<br />
xmproc <- spawnPipe "xmobar"<br />
xmonad $ defaultConfig<br />
{ manageHook = myManageHooks <+> manageDocks <+> manageHook defaultConfig<br />
, layoutHook = avoidStruts $ ewmhDesktopsLayout $ myLayout ||| layoutHook defaultConfig<br />
-- NOTE: no '$' is used between dynamicLogWithPP and xmobarPP<br />
, logHook = dynamicLogWithPP xmobarPP<br />
{ ppOutput = hPutStrLn xmproc<br />
, ppLayout = const ""<br />
, ppTitle = xmobarColor "green" "" . shorten 80<br />
}<br />
>> ewmhDesktopsLogHook<br />
>> setWMName "LG3D"<br />
<br />
---- or with a desktop config, e.g.<br />
-- , logHook = logHook gnomeConfig >> setWMName "LG3D"<br />
}<br />
</haskell><br />
<br />
With xmonad-0.9 or greater there is no need to spam the X server with setWMName in logHook, see above for how to modify startupHook instead.<br />
<br />
==== Changing AWT Toolkit ====<br />
Another option is to use an AWT toolkit that is more window manager agnostic, (Some report that this causes keyboard to fail in some java applications. It also doesn't seem to work as widely or reliably as setWMName or other preferred methods above.) If you want to try it, set the environment variable:<br />
<br />
AWT_TOOLKIT=MToolkit<br />
<br />
This seems to fix some versions of:<br />
<br />
* MATLAB<br />
* cgoban3<br />
* Netbeans<br />
* processing [http://processing.org]<br />
<br />
Even if you don't use Bash, you can often set environmental variables by putting them in .profile and logging back in:<br />
<br />
export AWT_TOOLKIT=MToolkit<br />
<br />
Using the free blackdown java runtime also seems to work correctly to fix this issue.<br />
<br />
==== Use JDK 7 ====<br />
* Using JDK 7 also seems to work well.<br />
<br />
Anthony Brown writes: <blockquote>I just downloaded and early binary release of JDK 7 and it looks like the new Java version behaves properly ... I tried using some Gui apps that gave me the infamous grey windows with Java6 (or Java5 without setting AWT_TOOLKIT=MToolkit) and so far no problems occured.</blockquote><br />
<br />
Gunnar Ahlberg #xmonad: <blockquote>JDK 7 solved problems remaining even when using setWMName "LG3D" in logHook.</blockquote><br />
<br />
==== Persuade a java application to use a specific java runtime (JRE) ====<br />
<br />
Sometimes it turns out that a program works with a specific JRE version, but not with another. Commercial programs tend to ship with their own JRE, so you may even notice that one program works while another doesn't. (For example, I've had a setup where Maple had problems while Matlab behaved well.) A java symlink in the right place can do wonders here. See [https://bugs.launchpad.net/xorg-server/+bug/185311 this Ubuntu bug report] for a number of examples.<br />
<br />
===XMonad doesn't save my layouts and windows===<br />
<br />
xmonad will remember your workspace layouts during dynamic restart<br />
(mod-q), but not when quitting X altogether. Note that this means <br />
if you add or remove layouts to the config.hs file, the changes won't be<br />
noticed during a hot-restart (the state from the previous session will<br />
be used).<br />
<br />
You can reinitialise the xmonad state dynamically with mod-shift-space.<br />
<br />
===Some keys not working===<br />
If you've an unusual keyboard, X may not know precisely which keys<br />
you've bound xmonad actions to. An example is when you use a<br />
French keyboard layout. You may need to set your own mod key, or use<br />
different key bindings in xmonad.hs. See the xmonad.org docs on configuring and customizing for advice on rebinding keys. Also currently xmonad only handles the first of duplicate key symbols bound, so if you have for example multiple xK_Backspace keys not all will be bound. There are patches available on the xmonad mailing list (or darcswatch) to change this.<br />
<br />
====Media keys====<br />
XMonad.Util.EZConfig additionalKeysP or Graphics.X11.ExtraTypes are the best way to bind the XF86 family of special keys. Note that some special laptop keys are handled by acpi and may show up as button events instead, or even bypass X completely.<br />
<br />
====French keyboard workspace switching====<br />
See XMonad.Config.Azerty for an azertyConfig to use in place of defaultConfig. This will adjust keybindings for the azerty layout, fixing workspaces switching, etc.<br />
<br />
====Numeric keypad keys like xK_KP_2 not working====<br />
Bind to the non-numeric versions of these keys. They work regardless of NumLock status. To avoid conflicts with other apps you probably want to use them with modifiers. Here is an example of using them to navigate workspaces in the usual mod-N mod-shift-N way, but on the key pad:<br />
<br />
<haskell><br />
myWorkspaces = ["1","2","3","4","5","6","7","8","9","0"]<br />
<br />
modm = mod4Mask -- win key for mod<br />
<br />
myKeys = -- use with EZConfig.additionalKeys or edit to match your key binding method<br />
[<br />
-- more custom keybindings<br />
]<br />
++<br />
[((m .|. modm, k), windows $ f i)<br />
| (i, k) <- zip myWorkspaces numPadKeys<br />
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]<br />
]<br />
<br />
-- Non-numeric num pad keys, sorted by number <br />
numPadKeys = [ xK_KP_End, xK_KP_Down, xK_KP_Page_Down -- 1, 2, 3<br />
, xK_KP_Left, xK_KP_Begin, xK_KP_Right -- 4, 5, 6<br />
, xK_KP_Home, xK_KP_Up, xK_KP_Page_Up -- 7, 8, 9<br />
, xK_KP_Insert] -- 0 <br />
</haskell><br />
<br />
====Keybindings dont work with rdesktop====<br />
Try running with the "-K" (keep window manager key bindings) switch. For example, <code>rdesktop -K -f 666.666.666.666</code> then press Ctrl-Alt-Enter, or simply <code>rdesktop -K 666.666.666.666</code><br />
<br />
===Copy and Paste on the Mac===<br />
<br />
When using X11 for Mac OS X, and you switch from the quartz WM to<br />
xmonad, you can lose copy/paste functionality between X windows and<br />
normal Mac apps. To fix this, and restore copy and paste, add<br />
<br />
quartz-wm --only-proxy &<br />
<br />
in your .xinitrc above the line that runs xmonad. It will capture and<br />
syncronize copy/paste events in both environments. More specifically,<br />
it mirrors OS X copy actions into both PRIMARY and CLIPBOARD, but only<br />
CLIPBOARD into OS X paste.<br />
<br />
===OpenOffice looks bad===<br />
<br />
OpenOffice won't use (strangely) the GTK look, unless the following<br />
environment variable is set:<br />
<br />
OOO_FORCE_DESKTOP=gnome<br />
<br />
Use this if you don't like the default look of OpenOffice in xmonad.<br />
<br />
=== Help! xmonad just segfaulted ===<br />
<br />
Due to this bug in GHC's recompilation checker,<br />
<br />
http://hackage.haskell.org/trac/ghc/ticket/1372<br />
<br />
if you updated a previously built xmonad, or XMonadContrib, when a<br />
dependent library has changed in the meantime, GHC will happily go ahead<br />
and link your libraries together, into a broken binary. This will at<br />
best produce a linker error, and at worst, a version of xmonad that will<br />
segfault. <br />
<br />
The rule is: when rebuilding, for example, XMonadContrib, always clean<br />
first if any library it depends on has changed.<br />
<br />
runhaskell Setup.lhs clean<br />
<br />
You may also want to make sure your config gets rebuilt:<br />
<br />
xmonad --recompile<br />
<br />
Another possibility is your xmonad was compiled against a very old<br />
version of the haskell-x11 library. Use haskell-X11-1.4.2 or newer.<br />
This version incorporates a couple of WM_HINTS related segfault bug<br />
fixes.<br />
<br />
=== Cabal: Executable stanza starting with field 'flag small_base description' ===<br />
<br />
When using ghc 6.6, or old versions of Cabal, you may get errors when configuring:<br />
<br />
*** Exception: getSection got a line without a '{'. Consider this a bug.<br />
<br />
These are all symptoms of trying to compile xmonad with an old version<br />
of cabal.<br />
<br />
The darcs version after xmonad 0.4 switched to requiring Cabal 1.2 to<br />
build xmonad. You '''must''' have Cabal 1.2 or newer to build xmonad<br />
older than 0.4. It will work fine with ghc 6.6.1, and you do not need to<br />
updated ghc. This will also not break older packages. Get cabal from Hackage:<br />
<br />
http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Cabal<br />
<br />
Build and install as usual, then rebuild xmonad.<br />
<br />
To build Cabal with ghc 6.6.1 you will also need the filepath library,<br />
which is also (of course) available from hackage:<br />
<br />
http://hackage.haskell.org/cgi-bin/hackage-scripts/package/filepath<br />
<br />
=== configure: error: cannot run C compiled programs. ===<br />
<br />
This typically means that you have /tmp mounted with noexec. To use another directory, make an alias that temporarily changes $TMPDIR, like<br />
<br />
alias cabal="TMPDIR=[insert directory here, eg ~/.cabal/build but make sure the directory exists] cabal"<br />
<br />
=== A manage hook is having no effect ===<br />
<br />
If a manage hook that checks an attribute of a window(e.g. resource =? "foo"<br />
--> bar) doesn't work even though the property is the same as reported by<br />
xprop, it can be caused by a program setting the corresponding property after<br />
the window has been created. To debug whether or not the term on the right<br />
hand side is at fault, it is useful to log which resource (or other property)<br />
xmonad sees:<br />
<br />
<haskell><br />
(resource >>= io . appendFile "/home/<youruser>/xmonad_debug" >> idHook)<br />
</haskell><br />
<br />
If opening the desired window causes xmonad to produce a log entry with the<br />
resource you were interested in, it means that the term on the right-hand side<br />
of --> is not working.<br />
<br />
[[Category:XMonad]]</div>Kini