https://wiki.haskell.org/api.php?action=feedcontributions&user=Dmwit&feedformat=atomHaskellWiki - User contributions [en]2015-11-28T22:49:49ZUser contributionsMediaWiki 1.19.14+dfsg-1https://wiki.haskell.org/Show_instance_for_functionsShow instance for functions2015-02-25T18:52:22Z<p>Dmwit: /* Theoretical answer */</p>
<hr />
<div>== Question ==<br />
<br />
Why is there no <hask>Show</hask> instance for functions for showable argument and value types?<br />
Why can't I enter <hask>\x -> x+x</hask> into GHCi or Hugs and get the same expression as answer?<br />
<br />
Why is there a Show instance, but it only prints the type?<br />
<br />
Prelude> :m + Text.Show.Functions<br />
Prelude Text.Show.Functions> show Char.ord<br />
"<function>"<br />
<br />
How can lambdabot display this:<br />
<br />
dons > ord<br />
lambdabot> <Char -> Int><br />
<br />
== Answer ==<br />
<br />
=== Practical answer ===<br />
<br />
The Haskell compiler doesn't maintain the expressions as they are, but translates them to machine code or some other low-level representation.<br />
The function <hask>\x -> x - x + x :: Int -> Int</hask> might have been optimized to <hask>\x -> x :: Int -> Int</hask>.<br />
The variable name <hask>x</hask> is not stored anywhere.<br />
You might have thought, that Haskell is like a scripting language, maintaining expressions at runtime.<br />
This is not the case.<br />
[[Lambda abstraction|Lambda expression]]s are just [[anonymous function]]s.<br />
You will not find a possibility to request the name of a variable at runtime,<br />
or inspect the structure of a function definition.<br />
You can also not receive an expression from the program user, which invokes variables of your program, and evaluate it accordingly.<br />
That is, Haskell is not [[reflexive language|reflexive]].<br />
Everything can be compiled.<br />
A slight exception is [[hs-plugins]].<br />
<br />
=== Theoretical answer ===<br />
<br />
Functional programming is about functions.<br />
A mathematical function is entirely defined by its graph, that is by pairs of objects (argument, value).<br />
E.g.<br />
*<math> \sqrt{\ } = \{(0,0), (1,1), (4,2), (9,3), \dots \} </math><br />
*<math> (\lambda x.\ x+x) = \{(0,0), (1,2), (2,4), (3,6), \dots \} </math><br />
Since the graphs of <math> \lambda x.\ x+x </math> and <math> \lambda x.\ 2\cdot x </math> are equal<br />
these both expressions denote the same function.<br />
Now imagine both terms would be echoed by Hugs or GHCi as they are.<br />
This would mean that equal functions lead to different output.<br />
The interactive Haskell environments use the regular <hask>show</hask> function,<br />
and thus it would mean <math> \mathrm{show}(\lambda x.\ x+x) \ne \mathrm{show}(\lambda x.\ 2\cdot x) </math>.<br />
This would break [[referential transparency]].<br />
<br />
It follows that the only sensible way to show functions is to show their graph.<br />
<haskell><br />
Prelude> \x -> x+x<br />
functionFromGraph [(0,0), (1,2), (2,4), (3,6),<br />
Interrupted.<br />
</haskell><br />
<br />
Code to do this is available in the [http://hackage.haskell.org/package/universe-reverse-instances universe-reverse-instances] package (which is also installed when installing the top-level [http://hackage.haskell.org/package/universe universe] package).<br />
<br />
== Source ==<br />
<br />
http://www.haskell.org/pipermail/haskell-cafe/2006-April/015161.html<br />
<br />
[[Category:FAQ]]</div>Dmwithttps://wiki.haskell.org/FAQFAQ2014-07-06T07:34:42Z<p>Dmwit: add a question about ?info</p>
<hr />
<div>This FAQ is based on actual frequently-asked questions from [[IRC channel|<tt>#haskell</tt> IRC]]. The goal is simply to collect and edit some common answers. Beginner questions are still welcome on IRC, as always.<br />
<br />
This is a wiki, so please edit the text with any improvements you have. And feel free to add new questions, if they are frequently asked.<br />
<br />
== See also ==<br />
<br />
* [[:Category:FAQ|Other FAQs]]<br />
* The [[Introduction|introduction to Haskell]], and the FAQ at the end of that document.<br />
<br />
__TOC__<br />
<br />
= The real world =<br />
<br />
== Should I learn Haskell? ==<br />
<br />
That depends on your goals. In general, Haskellers will tell you that you should learn Haskell. :)<br />
<br />
Learning Haskell is fun. It will expand your mind and make you a better programmer in other languages. These are the immediate benefits.<br />
<br />
Haskell is also a great tool for solving real-world problems, but it can take many months of study to get to that point.<br />
<br />
== Is Haskell hard to learn? ==<br />
<br />
Any competent programmer can learn Haskell, but it will take more time and motivation than you may expect.<br />
<br />
Haskell requires learning a new way to think, not just new syntax for old concepts. This can be incredibly frustrating, as simple tasks seem impossibly difficult.<br />
<br />
Those with no prior programming experience may actually have an easier time learning Haskell, because they have less to un-learn.<br />
<br />
== How can I get started with Haskell ''right now''? ==<br />
<br />
Check out [http://tryhaskell.org/ Try Haskell].<br />
<br />
== What should I read for learning Haskell? ==<br />
<br />
The most popular resources are [http://learnyouahaskell.com/ ''Learn You a Haskell''] and [http://book.realworldhaskell.org/ ''Real World Haskell'']. Each is available online for free, or can be purchased in hardcopy.<br />
<br />
Many other [[tutorials]], [[books]], and [[Learning Haskell|other resources]] are available.<br />
<br />
== How can I get help with learning Haskell? ==<br />
<br />
Your options include:<br />
<br />
* [[IRC channel|<tt>#haskell</tt> on Freenode IRC]]<br />
* [http://stackoverflow.com/questions/tagged/haskell Stack Overflow]<br />
* The [http://www.haskell.org/mailman/listinfo/haskell-cafe Haskell-Cafe] mailing list<br />
<br />
== Will Haskell get me a job? ==<br />
<br />
There are plenty of [[Haskell in industry|companies using Haskell]], but it's still a tiny number compared to the software industry as a whole.<br />
<br />
There are also many companies which do not use Haskell, but prefer to hire people who know Haskell. It indicates that you learned something hard and obscure just for fun, which employers take as a sign of intelligence.<br />
<br />
== Is Haskell similar to Language X? ==<br />
<br />
Probably not. It's best if you approach Haskell with a clean slate. Most analogies to another language will break down somewhere, often in a subtle and misleading way. If you first learn the Haskell concepts for what they are, you can then draw useful connections to other languages.<br />
<br />
== What's the relationship between Haskell and GHC? ==<br />
<br />
Haskell is not a piece of software; it is a specification for a standardized programming language. The [[Language and library specification|latest version of the spec]] is the Haskell 2010 Report.<br />
<br />
[http://www.haskell.org/ghc/ GHC] is the Glorious Glasgow Haskell Compiler. It is by far the most popular and &quot;production-ready&quot; implementation of the standard Haskell language. It also implements many [http://www.haskell.org/ghc/docs/latest/html/users_guide/ghc-language-features.html extension] features that go above and beyond standard Haskell. Many programs use these features and so aren't &quot;written in Haskell&quot; in the strictest sense.<br />
<br />
You can use the term &quot;Haskell&quot; to refer to the standard language, and &quot;GHC Haskell&quot; when including GHC extensions.<br />
<br />
Besides GHC, several other [[implementations]] of Haskell are available. Each one provides its own extensions, some of which don't exist in GHC.<br />
<br />
== What is the Haskell Platform? ==<br />
<br />
The [http://hackage.haskell.org/platform/ Haskell Platform] is a copy of GHC bundled with a &quot;blessed&quot; set of useful libraries. It is the easiest way to get started with Haskell. It's not essential to start with the Platform, because you can install the same libraries as needed.<br />
<br />
== What is Haskell Prime (Haskell')? ==<br />
<br />
[http://hackage.haskell.org/trac/haskell-prime/ Haskell Prime] is a process which produces new versions of the Haskell language spec. It does not refer to a particular present or future version of Haskell.<br />
<br />
== My textbook uses Haskell 98. Is it very different from Haskell 2010? ==<br />
<br />
No. Haskell 2010 is a [http://www.haskell.org/pipermail/haskell/2009-November/021750.html very conservative change] to Haskell 98. It fixes small syntactic flaws, and standardizes several well-behaved extensions which GHC has supported for years.<br />
<br />
The standardization process is very slow because standardizing a flawed language can be a costly mistake. Extensions are accepted only once they are considered mature and well-understood.<br />
<br />
== How do I get libraries for Haskell? ==<br />
<br />
You can find libraries on [http://hackage.haskell.org/packages/archive/pkg-list.html Hackage], and install them with [[Cabal-Install|<tt>cabal-install</tt>]].<br />
<br />
== Is Haskell compiled? ==<br />
<br />
Usually. GHC, the most popular Haskell implementation, has an optimizing ahead-of-time native-code compiler, as well as a bytecode compiler and interpreter for interactive use.<br />
<br />
Haskell itself is not a &quot;compiled language&quot; because nothing in the Haskell spec requires implementations to be compilers.<br />
<br />
== Does Haskell have an interpreter? ==<br />
<br />
Yes, but maybe you instead mean &quot;Is there a program where I can type Haskell code and see it run immediately?&quot;. GHCi provides such a &quot;read-evaluate-print loop&quot;.<br />
<br />
= Paradigms =<br />
<br />
== Is learning Haskell the best way to learn functional programming? ==<br />
<br />
Not necessarily! Haskell is not a ''typical'' functional language. It can be overwhelming to learn the basic concepts of functional programming alongside static types, algebraic data, laziness, type classes, first-class IO, etc. For an introduction to FP by itself you might want to learn Scheme, or play with the FP features in your current favorite language.<br />
<br />
That said, many people choose Haskell as an introduction to FP and have success with that approach. Haskell has an extremely active community of people teaching, doing research, writing libraries, etc. Haskell is where interesting things happen in the FP space, so it's an exciting place to jump in.<br />
<br />
== I heard Haskell is pure functional. Does that mean I can't do imperative / OOP / aspect-oriented / logic programming in Haskell? ==<br />
<br />
No, &quot;pure functional&quot; has a specific technical meaning. It doesn't mean that functional is the only supported paradigm.<br />
<br />
Paradigms describe the techniques used in a particular program. For example, the Linux kernel is written in C, with pervasive use of functional, object-oriented, and aspect-oriented programming. The most we can say about a ''language'' is that it encourages or discourages a particular paradigm. Haskell is very flexible and can comfortably accommodate most paradigms, even when there is no built-in support.<br />
<br />
== I heard Haskell is pure functional. Does that mean it can't do IO? ==<br />
<br />
No; [[Introduction to IO|IO in Haskell]] is straightforward.<br />
<br />
== I heard Haskell is pure functional. Does that mean it doesn't have mutable state? ==<br />
<br />
No; see [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-IORef.html <tt>IORef</tt>] for a simple example. A more sophisticated example is [http://book.realworldhaskell.org/read/software-transactional-memory.html software transactional memory], which provides concurrent state more sophisticated than you'll find in most other imperative languages.<br />
<br />
== Wait, is Haskell imperative or is it functional? ==<br />
<br />
Both. In Haskell, functions are first class, and so are imperative actions.<br />
<br />
There is no reason to consider &quot;imperative language&quot; and &quot;functional language&quot; as mutually exclusive. It's only a historical accident that a few of the most popular imperative languages are unusually bad at functional programming. Functional imperative programming is extremely powerful and is supported by many languages.<br />
<br />
= Math =<br />
<br />
== Was Haskell designed by mathematicians? ==<br />
<br />
Haskell was designed by people studying programming language design. Perhaps programmers would consider them to be mathematicians, while mathematicians would consider them to be programmers.<br />
<br />
Designing a programming language is a hard thing to do. There are many non-obvious tradeoffs, and many lessons to be learned from past failures and successes. Yet many of today's most popular languages were designed by people who hadn't done their homework.<br />
<br />
Haskell was designed by people who knew what they were doing. It's not perfect, but the contrast to an amateur's design is striking.<br />
<br />
== Do I need to know advanced math in order to use Haskell? ==<br />
<br />
No. Certain concepts in Haskell are named after concepts in advanced math. But other languages also appropriate math terminology: consider &quot;[http://en.wikipedia.org/wiki/Singleton_pattern singleton]&quot;, not to mention &quot;function&quot; and &quot;variable&quot;. The way these programming concepts relate to actual mathematics is not necessarily important or relevant.<br />
<br />
In addition, some people write articles about advanced math, using Haskell syntax as their notation. These articles are interesting, but the connection to everyday programming work is usually remote.<br />
<br />
Knowing advanced math will enrich your experience using Haskell, but is by no means a prerequisite.<br />
<br />
= Types =<br />
<br />
== Doesn't a static type system just make it harder to write programs? ==<br />
<br />
Yes. In particular, it makes it ''much'' harder to write ''incorrect'' programs.<br />
<br />
The tradeoff is that correct programs also become somewhat harder to write. In Haskell, features like type inference mitigate this burden to a large extent.<br />
<br />
== How do I make a list with elements of different types? ==<br />
<br />
Are you sure that's what you want? Consider instead creating a single data type to encompass the alternatives:<br />
<br />
<haskell><br />
data Identifier<br />
= ByNumber Int<br />
| ByName String<br />
<br />
doStuff :: [Identifier] -> Whatever<br />
</haskell><br />
<br />
In many dynamically-typed languages you aren't allowed to create &quot;variant types&quot; like this. The type system itself is used as a single ad-hoc global variant type. Keep this in mind if you're translating designs from a dynamically-typed language to Haskell.<br />
<br />
== No really, how do I make a list of elements of different types? ==<br />
<br />
Well, you can't avoid putting all your values into one type. But sometimes the &quot;variant type&quot; approach above is too restrictive. Maybe you need to let other people add to the set of allowed types, the way [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Exception.html Control.Exception] allows users to define new exception types.<br />
<br />
You can use an [[existential type]], possibly with a type class. Or you can use [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Dynamic.html Data.Dynamic].<br />
<br />
== I'm making an RPG. Should I define a type for each kind of monster, and a type class for them? ==<br />
<br />
Probably not. Some languages require a new type for each new behavior. In Haskell, behaviors are functions or IO actions, which are first-class values. So you can store behaviors in an ordinary data type:<br />
<br />
<haskell><br />
data MonsterOps = MonsterOps<br />
{ new :: Monster<br />
, move :: Monster -> Monster<br />
, attack :: Monster -> Player -> Player }<br />
<br />
data Monster = Monster<br />
{ position :: (Int, Int)<br />
, hitpoints :: Double }<br />
<br />
beholder :: MonsterOps<br />
beholder = MonsterOps new move attack where<br />
new = Monster (0,0) 9000<br />
move self = ...<br />
attack self player = ...<br />
</haskell><br />
<br />
This approach is especially nice if you want to generate or transform behaviors on the fly. See the article [http://lukepalmer.wordpress.com/2010/01/24/haskell-antipattern-existential-typeclass/ &quot;Haskell Antipattern: Existential Typeclass&quot;] for a longer discussion.<br />
<br />
== What's the difference between <hask>Integer</hask> and <hask>Int</hask>? ==<br />
<br />
<p><hask>Integer</hask> can represent arbitrarily large integers, up to using all of the storage on your machine.</p><br />
<br />
<p><hask>Int</hask> can only represent integers in a finite range. The [http://www.haskell.org/onlinereport/haskell2010/haskellch6.html#dx13-135009 language standard] only guarantees a range of -2<sup>29</sup> to (2<sup>29</sup> - 1). Most implementations will provide a full machine-size signed integer, i.e. 32 or 64 bits.</p><br />
<br />
Operations on <hask>Int</hask> can be much faster than operations on <hask>Integer</hask>, but overflow and underflow can cause weird bugs. Using <hask>Int</hask> in an initial design could be considered premature optimization. Unfortunately, many standard library functions (e.g. <hask>length</hask>, <hask>take</hask>) use <hask>Int</hask>.<br />
<br />
== How do I convert type <tt>A</tt> to type <tt>B</tt>? ==<br />
<br />
This is just another way of asking for a function of type <hask>A -> B</hask>. For example, you can convert <hask>Double</hask> to <hask>Int</hask> with <hask>round</hask>, <hask>ceiling</hask>, or <hask>floor</hask>. Haskell does not privilege one of these as ''the'' conversion.<br />
<br />
== Does Haskell have type casts? ==<br />
<br />
The word &quot;cast&quot; can mean a lot of different things.<br />
<br />
* You want to convert a value from one type to another, preserving some idea of what it means. For example, you might convert an <hask>Int</hask> to a <hask>Double</hask> which represents the same integer. In this case you'd just use a function of type <hask>Int -> Double</hask>, such as <hask>fromIntegral</hask>. Haskell doesn't provide special rules or syntax for these functions. See also the previous question.<br /><br /><br />
* You want to pass a value of more specific type to a function expecting a less specific type. There's no syntax for this in Haskell; you just do it. For example you can pass <hask>x :: Int</hask> to <hask>show :: (Show a) => a -> String</hask>, which automatically specializes the type of <hask>show</hask> to <hask>Int -> String</hask>. Note that Haskell does not have subtyping, so this only happens in the context of instantiating type variables.<br /><br /><br />
* You want to use a value of less specific type under the assumption of a more specific type, with a checkable runtime error if they do not match. This is rarely the right way to do things in Haskell, and probably indicates a conceptual / design problem instead. If you really do need such a cast, you can use [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Typeable.html#v:cast <tt>cast</tt>] from [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Typeable.html Data.Typeable]. In this case the &quot;checkable runtime error&quot; is <hask>cast</hask> returning <hask>Nothing</hask>. Note that Haskell does not have subtyping, so this only happens in the context of instantiating type variables.<br /><br /><br />
* You want to use a value of less specific type under the assumption of a more specific type, and if the assumption is incorrect, the program is allowed to segfault / silently corrupt data / give the attacker a root shell / send illicit photos to your boss. Also known as &quot;C cast&quot;. GHC Haskell has a way to do this, but I dare not speak its name. It's so dangerous and so unlikely to be what you want that it has no place in a general FAQ. You can ask on IRC or read the docs if you have the right kind of morbid curiosity.<br />
<br />
== How do I convert from one numeric type to another? ==<br />
<br />
Probably using one of these:<br />
<br />
<haskell><br />
fromIntegral :: (Integral a, Num b ) => a -> b<br />
realToFrac :: (Real a, Fractional b) => a -> b<br />
</haskell><br />
<br />
<p><hask>fromIntegral</hask> converts to a wider range of types, but <hask>realToFrac</hask> converts from types which aren't integers.</p><br />
<br />
== How do I convert <hask>Maybe Int</hask> to <hask>Int</hask>? ==<br />
<br />
Use pattern-matching. If <hask>mx :: Maybe Int</hask>:<br />
<br />
<haskell><br />
case mx of<br />
Just x -> ...<br />
Nothing -> ...<br />
</haskell><br />
<br />
This forces you to consider the <hask>Nothing</hask> case, and is the main advantage of <hask>Maybe</hask>, compared to adding a <tt>null</tt> value to every type.<br />
<br />
See also the functions [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html#v:maybe <tt>maybe</tt>] and [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html#v:fromMaybe <tt>fromMaybe</tt>] in the module [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html Data.Maybe].<br />
<br />
''Do not'' use <hask>fromJust</hask>, because passing <hask>Nothing</hask> will crash your program with a supremely unhelpful error message. Even when you want to assume the value is not <hask>Nothing</hask>, you can provide a better error message:<br />
<br />
<haskell><br />
let x = fromMaybe (error "custom error message") mx in ...<br />
</haskell><br />
<br />
If you pattern-match without a <hask>Nothing</hask> case:<br />
<br />
<haskell><br />
let Just x = mx in ...<br />
</haskell><br />
<br />
you'll at least get a line number in the error message:<br />
<br />
<pre><br />
*** Exception: foo.hs:2:9-24: Irrefutable pattern failed for pattern Data.Maybe.Just x<br />
</pre><br />
<br />
== How do I convert <hask>IO Int</hask> to <hask>Int</hask>? ==<br />
<br />
You can't; they represent totally different things. An <hask>Int</hask> is an integer. An <hask>IO Int</hask> is a description of how some IO could be performed, in the future, to produce an integer. The IO hasn't been performed yet, and might never happen or might happen more than once.<br />
<br />
See the [[Introduction to IO]].<br />
<br />
== How do I convert between <hask>String</hask> (or <hask>Text</hask>) and <hask>ByteString</hask>? ==<br />
<br />
<p><hask>String</hask> represents a sequence of Unicode characters. <hask>ByteString</hask> represents a sequence of bytes. There are many different, incompatible ways to represent Unicode characters as bytes. See [http://www.joelonsoftware.com/articles/Unicode.html this article] if you're fuzzy on the character / byte distinction.</p><br />
<br />
The module [http://hackage.haskell.org/packages/archive/text/0.11.1.5/doc/html/Data-Text-Encoding.html Data.Text.Encoding] from the <tt>text</tt> package provides functions for common Unicode encodings. For more obscure / legacy encodings, see the [http://hackage.haskell.org/package/text-icu <tt>text-icu</tt>] package.<br />
<br />
== How do I catch the error thrown by <hask>read</hask> on a parse failure? ==<br />
<br />
Don't. Instead use<br />
<br />
<haskell><br />
reads :: (Read a) => String -> [(a, String)]<br />
</haskell><br />
<br />
which returns a list of parses, each with a value and a remaining string. An example:<br />
<br />
<haskell><br />
safeRead :: (Read a) => String -> Maybe a<br />
safeRead x = case reads x of<br />
[(v,"")] -> Just v<br />
_ -> Nothing<br />
</haskell><br />
<br />
== What's the difference between <hask>type</hask>, <hask>data</hask>, and <hask>newtype</hask>? ==<br />
<br />
<p><hask>type</hask> introduces a synonym, which is fully interchangeable with the original type:</p><br />
<br />
<haskell><br />
type Foo = Int<br />
<br />
main = print ((2 :: Int) + (3 :: Foo))<br />
</haskell><br />
<br />
So it provides convenience and documentation, but no additional type checking.<br />
<br />
<p><hask>data</hask> is used to define new data types, distinct from any existing type.</p><br />
<br />
<p><hask>newtype</hask> can mostly be understood as a restricted form of <hask>data</hask>. You can use <hask>newtype</hask> when you have exactly one constructor with exactly one field. In those cases, <hask>newtype</hask> can give better performance than <hask>data</hask>.</p><br />
<br />
There is, however, a [[Newtype|subtle difference]] between <hask>data</hask> and <hask>newtype</hask> semantics, which is why the <hask>newtype</hask> optimization is not applied automatically.<br />
<br />
= Making it work =<br />
<br />
== How can I find type errors? ==<br />
<br />
There's no silver bullet, but here are a few useful techniques:<br />
<br />
* Comment out type signatures and see what GHC infers, using <tt>:t</tt> in GHCi.<br />
* Add more type signatures, for example inside <hask>let</hask>. This makes your assumptions clearer, so GHC's error message may better explain how your assumptions are inconsistent.<br />
* Replace some subexpressions with <hask>undefined</hask>, which can assume any type.<br />
<br />
== How can I find bugs that occur at runtime? ==<br />
<br />
With pure functions, correctness is a matter of getting the right output for a given input. If one function gives incorrect results, you test the functions it calls, and so on until the bad code is located. You can perform these tests directly in GHCi, or with the help of a tool like QuickCheck.<br />
<br />
You can trace evaluation using [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Debug-Trace.html Debug.Trace]. You'll get a printout when the expression is evaluated. Due to lazy evaluation, this might be at an unexpected time. But this property is useful when debugging problems related to excessive laziness.<br />
<br />
GHCi also implements a [http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci-debugger.html &quot;simple imperative-style debugger&quot;].<br />
<br />
Haskell is a natural fit for novel [http://ww2.cs.mu.oz.au/~bjpop/buddha/ &quot;declarative debugging&quot; tools] but to our knowledge, no such tool is production-ready.<br />
<br />
== Why do I get an &quot;undefined symbol&quot; linker error when compiling? ==<br />
<br />
If you're using GHC 6, you should pass <tt>--make</tt> so that GHC will automatically link the appropriate Haskell libraries.<br />
<br />
== How can I get a stack backtrace when my program throws an exception? ==<br />
<br />
The standard stack in GHC Haskell doesn't represent nested function calls. The more informative stack is the profiling cost-center stack, which only exists if your code is built for profiling.<br />
<br />
With GHC 7 you can do something like this:<br />
<br />
<pre>$ ghc -fforce-recomp -prof -auto-all -rtsopts foo.hs</pre><br />
For GHC 6 you should leave off <tt>-rtsopts</tt>, and you'll probably want <tt>--make</tt>.<br />
<br />
You can then run your program with the [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-debugging <tt>-xc</tt> RTS option`]:<br />
<br />
<pre>$ ./foo +RTS -xc</pre><br />
== How can I do automated unit testing? ==<br />
<br />
See the [http://book.realworldhaskell.org/read/testing-and-quality-assurance.html testing chapter] in ''Real World Haskell''.<br />
<br />
== How can I find and fix performance problems? ==<br />
<br />
See the [http://book.realworldhaskell.org/read/profiling-and-optimization.html profiling and optimization chapter] in ''Real World Haskell''.<br />
<br />
= Modules =<br />
<br />
== How do I deal with name clashes between modules? ==<br />
<br />
You can disambiguate by prefixing a module name:<br />
<br />
<haskell><br />
import Data.List<br />
import Data.Map<br />
<br />
f = Data.List.lookup 7<br />
g = Data.Map.lookup 7<br />
</haskell><br />
<br />
The import syntax gives you additional control:<br />
<br />
* With <hask>import qualified Foo</hask> the names from <hask>Foo</hask> can ''only'' be used qualified, and won't clash with unqualified names.<br />
<br />
* With <hask>import Foo as M</hask> you'd write <hask>M.x</hask> instead of <hask>Foo.x</hask>.<br />
<br />
You can combine these two features. A more common way to write the above example is:<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
f = lookup 7 -- unqualified, from Prelude<br />
g = M.lookup 7<br />
</haskell><br />
<br />
In general, most combinations of <hask>import</hask> features are allowed. You<br />
can combine <hask>as</hask> and <hask>qualified</hask> with import and<br />
<hask>hiding</hask> lists. You can import two modules <hask>as</hask> the same<br />
name, or one module <hask>as</hask> two names, with different import and<br />
<hask>hiding</hask> lists, <hask>qualified</hask> or unqualified, etc.<br />
<br />
== How do I control the <hask>Prelude</hask> import? ==<br />
<br />
Haskell modules implicitly import <hask>Prelude</hask>, unless an explicit import is given. So you can write<br />
<br />
<haskell><br />
import Prelude as P hiding (length, head)<br />
</haskell><br />
<br />
== How do I qualify the name of an infix operator? ==<br />
<br />
You prefix the module name, as usual:<br />
<br />
<haskell><br />
x = 2 + 3<br />
y = 2 Prelude.+ 3<br />
<br />
f = (+) 7<br />
g = (Prelude.+) 7<br />
</haskell><br />
<br />
This looks weird but works fine. The syntax does clash a bit:<br />
<br />
<haskell><br />
xs = [False..True] -- wrong, parses as qualified name<br />
xs = [False .. True] -- ok<br />
</haskell><br />
<br />
== How do I mention an infix operator in an export / import / <hask>hiding</hask> list? ==<br />
<br />
The same way as elsewhere: enclose it in parentheses.<br />
<br />
<haskell><br />
import Prelude ( succ, (+), length, (*) )<br />
</haskell><br />
<br />
== I listed a data type in my import list but its data constructors aren't in scope. How do I fix it? ==<br />
<br />
You have to import data constructors explicitly:<br />
<br />
<haskell><br />
import Prelude ( Maybe ) -- the type only<br />
import Prelude ( Maybe(Nothing) ) -- type and specific constructor(s)<br />
import Prelude ( Maybe(..) ) -- type and all its constructors<br />
</haskell><br />
<br />
== How can I import and re-export a whole module? ==<br />
<br />
<haskell><br />
module Bar ( module Foo ) where<br />
import Foo<br />
</haskell><br />
<br />
== How can I export another module ''and'' everything defined in this module? ==<br />
<br />
<haskell><br />
module Bar ( module Bar, module Foo ) where<br />
import Foo<br />
</haskell><br />
<br />
= The M-word =<br />
<br />
See also &quot;[[What a Monad is not]]&quot;.<br />
<br />
== I heard Haskell is about monads. I heard that the core feature of Haskell is monads. Is that true? ==<br />
<br />
Absolutely not.<br />
<br />
== Do I need to understand monads in order to do IO? ==<br />
<br />
Not really. &quot;<tt>Monad</tt>&quot; is the name of a generic API that applies to many different types, including the <hask>IO</hask> type. If you're only thinking about IO, you don't need to worry about how this API generalizes.<br />
<br />
See the [[Introduction to IO]].<br />
<br />
== What should I know before trying to understand monads? ==<br />
<br />
Let's look at part of the definition of <hask>Monad</hask>:<br /><br /><br />
<br />
<haskell><br />
class Monad m where<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
</haskell><br />
<br />
This uses a lot of features:<br />
<br />
* first-class functions: the second argument to <hask>(>>=)</hask> is a function<br />
<br />
* type constructors (here <hask>m</hask>)<br />
<br />
* type class polymorphism<br />
<br />
* type class polymorphism ''over'' type constructors (which few other languages have)<br />
<br />
* parametric (not type class) polymorphism, over <hask>a</hask> and <hask>b</hask><br />
<br />
Each of these features is more fundamental than the specific idea of monads. If you understand each feature, then <hask>Monad</hask> is a small example of how they fit together. <hask>Functor</hask> is a slightly simpler example, and you can start there instead (see [[Typeclassopedia]]).<br />
<br />
== Aren't monads just a hack for handling impure things in a pure language? ==<br />
<br />
No. This is wrong in several ways.<br />
<br />
First, '''<hask>Monad</hask> isn't special.''' <hask>Monad</hask> is an ordinary Haskell type class. You can define it yourself in a few lines of pure Haskell code, so it's definitely not adding magical new capabilities to the language. Besides that, <hask>Monad</hask> is an API, not an implementation.<br /><br /><br />
<br />
(The <hask>do</hask> syntax ''is'' special, but it's only [[syntactic sugar]]. There's a straightforward translation to ordinary function calls, lambdas, etc.)<br /><br /><br />
<br />
Second, '''most monads have nothing to do with effects or "impurity".''' The <hask>Monad</hask> API is implemented by many different type constructors, including <hask>Maybe</hask> and <hask>[]</hask>. Lists and <hask>Maybe</hask> values are straightforward, familiar data values. There's nothing "impure" about them.<br /><br /><br />
<br />
Third, '''<hask>IO</hask> is not an exception to purity.''' IO actions are pure, first-class values like any other. You can create, store, and evaluate them without causing side effects. IO actions are just ''descriptions'' of IO which ''could'' be performed.<br /><br />
<br />
In short, Haskell programs are pure-functional programs which compute imperative programs.<br />
<br />
It's true that <hask>IO</hask> implements the <hask>Monad</hask> API, but that's not fundamental. You could instead use non-overloaded functions like<br /><br /><br />
<br />
<haskell><br />
returnIO :: a -> IO a<br />
bindIO :: IO a -> (a -> IO b) -> IO b<br />
</haskell><br />
<br />
<br />to glue together IO actions, and it would all work out basically the same. We use the generic <hask>Monad</hask> API for <hask>IO</hask> not because we have to, but because it lets us reuse convenient syntax and [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html libraries]. Indeed, you can [[Introduction to IO|introduce <tt>IO</tt>]] without mentioning <hask>Monad</hask> at all.<br />
<br />
== I heard monads are like burritos or space suits full of nuclear waste. Is that true? ==<br />
<br />
These analogies are not helpful. See [http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/ &quot;Abstraction, intuition, and the 'monad tutorial fallacy&quot;'].<br />
<br />
== I can use monads but I feel like I still don't &quot;get&quot; them. What am I missing? ==<br />
<br />
You're not necessarily missing anything. &quot;<tt>Monad</tt>&quot; is just the name of a generic API that applies to many different types. The types implementing the <tt>Monad</tt> API don't have a lot in common.<br />
<br />
You might want to read &quot;[[Typeclassopedia]]&quot; to see how <tt>Monad</tt> fits in with other similar APIs.<br />
<br />
== What's the difference between <hask>State s</hask> and <hask>ST s</hask> monads? ==<br />
<br />
<tt>State s a</tt> is just a wrapper for the function type <hask>s -> (a, s)</hask>: a function that takes an &quot;old state&quot; and returns a &quot;new state&quot; along with its result. You can implement <hask>State</hask> in a few lines of standard Haskell, without any special help from the compiler.<br />
<br />
<hask>ST</hask> gives you true mutable variables with in-place update. You can't implement it yourself in standard Haskell. In GHC, <hask>STRef</hask> and <hask>IORef</hask> will behave the same way at runtime. The difference is the extra compile-time safety checking associated with <hask>runST</hask>.<br />
<br />
= Concurrency and parallelism =<br />
<br />
See also notes on [[parallel]] and [[Concurrency|concurrent]] programming.<br />
<br />
== How can I do X without resorting to threads? ==<br />
<br />
That's usually the wrong attitude. Threads are useful for solving problems. The attitude comes from other languages where some combination of the following holds:<br />
<br />
* Per-thread overhead consumes a lot of memory or CPU<br />
<br />
* Thread APIs are cumbersome, sometimes due to lacking first-class functions or IO actions<br />
<br />
* The thread implementation is fundamentally broken, e.g. a global interpreter lock<br />
<br />
* Threads break easily because programs constantly mutate implicitly-shared state<br />
<br />
None of these is true in GHC Haskell. Threads have disadvantages and are not always the right tool. But avoiding them at all costs is counterproductive.<br />
<br />
== What's the difference between concurrency and parallelism? ==<br />
<br />
Briefly: concurrency describes semantics; parallelism describes an implementation property.<br />
<br />
Concurrent programs are written with explicit threads of control. Concurrent semantics fit naturally with certain real-world problems, like a network server talking to many simultaneous clients. This is still a nice model for writing a network server, even if you only intend to run it on one CPU core — concurrency without parallelism.<br />
<br />
Parallel programs are those which run on multiple CPU cores simultaneously, regardless of how they were implemented.<br />
<br />
Concurrency is a popular way to obtain parallel performance, but converting a pure computation to use concurrent semantics is difficult and error-prone. GHC Haskell provides "[http://hackage.haskell.org/packages/archive/parallel/latest/doc/html/Control-Parallel-Strategies.html semi-implicit parallelism]" as an alternative. Adding these "annotations" to a program cannot change its behavior.<br />
<br />
There's a longer discussion on the [http://ghcmutterings.wordpress.com/2009/10/06/parallelism-concurrency/ GHC blog].<br />
<br />
== How do <hask>par</hask>, <hask>pseq</hask>, and <hask>seq</hask> relate? ==<br />
<br />
The expression <hask>par x y</hask> is semantically equivalent to <hask>y</hask>, but suggests to the runtime system that evaluating <hask>x</hask> in parallel might be a good idea. Usually <hask>x</hask> would be a variable referring to a thunk (unevaluated expression) that will later be needed.<br /><br /><br />
<br />
Now consider <hask>par x (x+y)</hask>. Evaluating this expression suggests evaluating <hask>x</hask> in parallel. But before the runtime system can act on that suggestion, we evaluate <hask>(x+y)</hask>, which will evaluate both <hask>x</hask> and <hask>y</hask> in sequence. It would be better to work on <hask>y</hask> for a while, and only demand <hask>x</hask> later, after perhaps some parallel work has occurred. We can use <hask>pseq</hask> to force this evaluation order, as in <hask>par x (pseq y (x+y))</hask>.<br /><br /><br />
<br />
The [http://hackage.haskell.org/packages/archive/parallel/latest/doc/html/Control-Parallel-Strategies.html Strategies] module provides a nicer interface to these <hask>par</hask> / <hask>pseq</hask> tricks.<br />
<br />
<p><hask>seq</hask> is similar to <hask>pseq</hask> but provides a weaker guarantee. [http://www.mail-archive.com/glasgow-haskell-users@haskell.org/msg10973.html The details] are subtle; suffice to say that if you're controlling evaluation order, you want <hask>pseq</hask>.</p><br />
<br />
== How do I do event-based IO in GHC Haskell? Should I call <tt>select</tt>, <tt>epoll</tt>, etc? ==<br />
<br />
No; just do blocking IO from multiple threads, and GHC's runtime system will make these calls for you. GHC Haskell gives you the performance benefits of event-based IO without making you turn your code inside-out.<br />
<br />
Threads in GHC are lightweight — both in performance and in the mental effort of using them. You can handle [http://blog.johantibell.com/2010/09/final-version-of-our-ghc-io-manager.html ten thousand concurrent requests] at high throughput with a naive "one thread per client" model.<br />
<br />
== What's the difference between <hask>forkIO</hask> and <hask>forkOS</hask>? ==<br />
<br />
It only matters if you're calling into a C library that cares about thread-local state. In that case, <hask>forkOS</hask> guarantees that the C library will see the same OS thread each time. Any difference beyond that is an implementation detail and subject to change.<br />
<br />
== How can I wait for a thread to finish and produce a result? ==<br />
<br />
There's a few libraries for this on Hackage, like [http://hackage.haskell.org/package/async <tt>async</tt>], [http://hackage.haskell.org/package/spawn <tt>spawn</tt>], and [http://hackage.haskell.org/package/threads <tt>threads</tt>].<br />
<br />
It's not hard to implement this yourself using [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent-MVar.html <tt>MVar</tt>], though it's harder to get the exception handling right.<br />
<br />
= IRC =<br />
<br />
== What does lambdabot's "info" command do? ==<br />
<br />
At first, it seems like it just echos whatever you type:<br />
<br />
<user> ?info foo bar baz<br />
<lambdabot> foo bar baz<br />
<br />
What is actually happening is that it autocorrects to the "undo" command, which desugars do blocks according to the Report's rules. So, a more interesting example might look like this:<br />
<br />
<user> ?info do { foo; x <- bar; baz }<br />
<lambdabot> foo >> bar >>= \ x -> baz<br />
<br />
[[Category:FAQ]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-27T20:47:07Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|-<br />
|<br />
| R. Clayton<br />
|-<br />
|<br />
| Nikos Vasilakis<br />
|-<br />
| bergey<br />
| Daniel Bergey<br />
|-<br />
|<br />
| Xiao Ling<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
|<br />
| Gregg Lebovitz<br />
|-<br />
|<br />
| Spencer Gordon<br />
|-<br />
| tikhonjelvis<br />
| Tikhon Jelvis<br />
|-<br />
| dstcruz<br />
| Daniel Santa Cruz<br />
|-<br />
| mjo<br />
| Michael Orlitzky<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
|<br />
| Alexander Jerneck<br />
|-<br />
| wavewash<br />
| Mo K.<br />
|-<br />
| vilhelm_s<br />
| Vilhelm Sjoberg<br />
|-<br />
| wavewave<br />
| Ian-Woo Kim<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/All_About_MonadsAll About Monads2013-05-27T14:28:12Z<p>Dmwit: /* Definition */ correct the definition of listens</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.mediafire.com/?no3dq024hgacye4 here]. And [http://web.archive.org/web/20061211101052/http://www.nomaware.com/monads/html/index.html here] is a version of the article which includes [http://web.archive.org/web/20061210172052/http://www.nomaware.com/monads/html/examples.html source code].<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 />
= 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 />
== A 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 />
= 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 />
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 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 />
= 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 />
= 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 -> 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>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-24T18:58:31Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|-<br />
|<br />
| R. Clayton<br />
|-<br />
|<br />
| Nikos Vasilakis<br />
|-<br />
| bergey<br />
| Daniel Bergey<br />
|-<br />
|<br />
| Xiao Ling<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
|<br />
| Gregg Lebovitz<br />
|-<br />
|<br />
| Spencer Gordon<br />
|-<br />
| tikhonjelvis<br />
| Tikhon Jelvis<br />
|-<br />
| dstcruz<br />
| Daniel Santa Cruz<br />
|-<br />
| mjo<br />
| Michael Orlitzky<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
|<br />
| Alexander Jerneck<br />
|-<br />
| wavewash<br />
| Mo K.<br />
|-<br />
| vilhelm_s<br />
| Vilhelm Sjoberg<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-24T18:26:24Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|-<br />
|<br />
| R. Clayton<br />
|-<br />
|<br />
| Nikos Vasilakis<br />
|-<br />
| bergey<br />
| Daniel Bergey<br />
|-<br />
|<br />
| Xiao Ling<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
|<br />
| Gregg Lebovitz<br />
|-<br />
|<br />
| Spencer Gordon<br />
|-<br />
| tikhonjelvis<br />
| Tikhon Jelvis<br />
|-<br />
| dstcruz<br />
| Daniel Santa Cruz<br />
|-<br />
| mjo<br />
| Michael Orlitzky<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
|<br />
| Alexander Jerneck<br />
|-<br />
| wavewash<br />
| Mo K.<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-23T22:33:10Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|-<br />
|<br />
| R. Clayton<br />
|-<br />
|<br />
| Nikos Vasilakis<br />
|-<br />
| bergey<br />
| Daniel Bergey<br />
|-<br />
|<br />
| Xiao Ling<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
|<br />
| Gregg Lebovitz<br />
|-<br />
|<br />
| Spencer Gordon<br />
|-<br />
| tikhonjelvis<br />
| Tikhon Jelvis<br />
|-<br />
| dstcruz<br />
| Daniel Santa Cruz<br />
|-<br />
| mjo<br />
| Michael Orlitzky<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-23T14:07:18Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|-<br />
|<br />
| R. Clayton<br />
|-<br />
|<br />
| Nikos Vasilakis<br />
|-<br />
| bergey<br />
| Daniel Bergey<br />
|-<br />
|<br />
| Xiao Ling<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
|<br />
| Gregg Lebovitz<br />
|-<br />
|<br />
| Spencer Gordon<br />
|-<br />
| tikhonjelvis<br />
| Tikhon Jelvis<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-22T20:10:41Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|-<br />
|<br />
| R. Clayton<br />
|-<br />
|<br />
| Nikos Vasilakis<br />
|-<br />
| bergey<br />
| Daniel Bergey<br />
|-<br />
|<br />
| Xiao Ling<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-20T18:59:05Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|-<br />
|<br />
| R. Clayton<br />
|-<br />
|<br />
| Nikos Vasilakis<br />
|-<br />
| bergey<br />
| Daniel Bergey<br />
|-<br />
|<br />
| Xiao Ling<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-17T11:20:13Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|-<br />
|<br />
| R. Clayton<br />
|-<br />
|<br />
| Nikos Vasilakis<br />
|-<br />
| bergey<br />
| Daniel Bergey<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-16T15:05:35Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|-<br />
|<br />
| R. Clayton<br />
|-<br />
|<br />
| Nikos Vasilakis<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-15T16:08:17Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|-<br />
|<br />
| Arthur Azevedo de Amorim<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-15T13:23:24Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|-<br />
| cmccann<br />
| Casey McCann<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-13T21:07:54Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|-<br />
| fizbin<br />
| Daniel Martin<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-11T04:39:39Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| fryguybob<br />
| Ryan Yates<br />
|-<br />
|<br />
| Pavel Frolov<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-07T04:31:09Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|-<br />
| osnr<br />
| Omar Rizwan<br />
|-<br />
|<br />
| Katherine Ye<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-06T20:23:07Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|-<br />
|<br />
| Andrey Basko<br />
|-<br />
|<br />
| Gershom Bazerman<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-06T19:32:18Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|-<br />
| carter<br />
| Carter Schonwald<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-05T20:25:13Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Eric Robert Fulmer<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-05-05T14:04:13Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857) 244-1001<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| ddarius<br />
| Derek Elkins<br />
|-<br />
| ozataman<br />
| Ozgun Ataman<br />
|-<br />
|<br />
| Emilio Jesús Gallego Arias<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86Hac φ2013-04-30T15:01:59Z<p>Dmwit: /* Sponsors */ add MSR and fix Jane St. link (without really understanding what was broken to begin with)</p>
<hr />
<div>'''June 7-9, 2013'''<br />
<br />
Philadelphia, Pennsylvania, USA<br />
<br />
== About ==<br />
<br />
The Haskell Hackathon is an international, grassroots collaborative coding festival with a simple focus: build and improve Haskell libraries, tools, and infrastructure.<br />
<br />
Hac φ will be held June 7-9, 2013 at the [http://www.upenn.edu/ University of Pennsylvania] in [http://en.wikipedia.org/wiki/Philadelphia Philadelphia]. It is open to all -- you do not have to be a Haskell guru to attend. All you need is a basic knowledge of Haskell, a willingness to learn, and a [[/Projects|project]] you're excited to help with (or a project of your own to work on).<br />
<br />
There will be lots of hacking, some talks, good food, and, of course, fun!<br />
<br />
* IRC channel: #haskell-hacphi (freenode)<br />
* Mailing list: [http://www.haskell.org/mailman/listinfo/hackathon hackathon@haskell.org]<br />
<br />
== Sponsors ==<br />
<br />
Hac φ 2012 is sponsored by [http://www.janestcapital.com/ Jane St. Capital] and [https://research.microsoft.com/en-us/labs/cambridge/ MSR Cambridge], both active users of functional programming!<br />
<br />
== Registration ==<br />
<br />
<!-- Registration is now closed. If you've already registered, you can --><br />
If you will be attending, please [[/Register|register]]. Registration is free, and open to everyone. If you like, you can also<br />
[[/Attendees|list yourself as an attendee]]. Then check out the [[/Projects|projects page]].<br />
<br />
Registration closes Friday, May 24, 2013 at 1430 local time (local to you!).<br />
<br />
== When ==<br />
<br />
June 7-9, 2013 from 2:30-8pm Friday, 9am-8pm Saturday, and 10am-5pm Sunday. There will probably be some talks Saturday afternoon.<br />
<br />
Although the hackathon won't officially kick off until 2:30pm on Friday, you are welcome to arrive the evening of Thursday the 2nd or Friday morning if it makes for easier travel. If enough people are around and interested, some sort of activity could be arranged for Thursday evening and/or Friday morning.<br />
<br />
== Talks ==<br />
<br />
If you'd be interested in giving a short (15-20 minute) talk, put your name and the subject of your talk on the [[/Talks|talks page]]. There will be a projector and blackboard available.<br />
<br />
== Location ==<br />
<br />
Check out the [http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=117635619663929119581.00046ad73c83c72a23d67&ll=39.954783,-75.194485&spn=0.001667,0.002403&t=h&z=15 Google map] for info on relevant locations.<br />
<br />
=== Getting to Philadelphia ===<br />
<br />
==== Air ====<br />
<br />
[http://www.phl.org/Pages/HomePage.aspx Philadelphia International Airport] (PHL) is the closest major airport.<br />
<br />
==== Train ====<br />
<br />
Take [http://www.amtrak.com Amtrak] to 30th Street Station (station code PHL), which is just a few blocks from Levine Hall; see the [http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=117635619663929119581.00046ad73c83c72a23d67&ll=39.954783,-75.194485&spn=0.001667,0.002403&t=h&z=15 Google map].<br />
<br />
==== Car ====<br />
<br />
UPenn's admissions office has [http://www.admissionsug.upenn.edu/visiting/directions.php driving directions] that take you right into the center of campus.<br />
<br />
=== Intra-city Transportation ===<br />
<br />
The Hackathon will be held in room 307 of Levine Hall. See Penn's searchable [http://www.facilities.upenn.edu/map.php campus map] for more on this location.<br />
<br />
==== Without a car ====<br />
<br />
* [http://www.septa.org/ SEPTA] operates the trains, busses, and trolleys in Philadelphia. The fare is $2 per trip, exact change (so save up your $1s before you come). You can also get tokens (which are cheaper, and don't require exact change to buy) at most big stops. Their site is a little bit unfriendly; I recommend using the [http://airs1.septa.org/bin/query.exe/en Trip Planner] to find out what routes to take, then consult the [http://www.septa.org/service.html route schedules] to find out how often those lines run, so you know how flexible your trip will be.<br />
* There are about a dozen cab companies serving various parts of the city; Google will point the way. You will likely be within Center City and University City (sometimes called West Philadelphia) for the duration of your visit. Hailing cabs is also theoretically possible, but I would recommend giving the radio dispatcher a call if you want to take a cab.<br />
* Walking is always an option. Philadelphia is a very walkable city.<br />
<br />
==== From the airport ====<br />
<br />
* There is a SEPTA Airport Express Train (R1) every half hour; the fare is $7 (pay after you get on the train). If coming directly to the hackathon, get off at University City station and walk a block west and a block north; otherwise, go one stop further to 30th Street Station to connect to other forms of transportation.<br />
* A cab from the airport to Center City or University City is about $30.<br />
* The PHL website has a [http://www.phl.org/passengerinfo/transportationservices/pages/rental_cars.aspx list of rental car companies]. UPenn's admissions office has [http://www.admissionsug.upenn.edu/visiting/directions.php driving directions] that take you right into the center of campus.<br />
* Walking is probably not an option.<br />
<br />
==== With a car ====<br />
<br />
There is some parking on-campus, as well as street-parking for $1/hour. To help with interpreting the maps below, Levine Hall is located at 34th and Walnut.<br />
<br />
* [http://www.admissionsug.upenn.edu/visiting/directions.php Parking on campus]<br />
* The [http://cms.business-services.upenn.edu/parking/ Penn Parking] site, especially the [http://cms.business-services.upenn.edu/parking/where-to-park/visitors-and-vendors.html Where to Park] page<br />
* [http://cms.business-services.upenn.edu/parking/images/stories/2010mapparking_staticrev4.pdf Parking map]<br />
<br />
The [http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=117635619663929119581.00046ad73c83c72a23d67&ll=39.954783,-75.194485&spn=0.001667,0.002403&t=h&z=15 Google map] also highlights the public parking locations near the hackathon; the fee is about $13/day.<br />
<br />
While you're planning your route, keep in mind that while the city is laid out mostly in a grid, about half of the roads are one-way.<br />
<br />
=== Accommodation ===<br />
<br />
<!--<br />
A block of single rooms has been reserved at the [http://www.clubquarters.com/loc_philadelphia.aspx Club Quarters hotel] in center city Philadelphia. These rooms are available for<br />
$87/night on May 21st and 22nd. Call them and mention the "PL Group"<br />
to receive this discount. You must reserve your room by April 23rd<br />
for the reduced rate.<br />
--><br />
Attendees often stay at the [http://www.clubquarters.com/loc_philadelphia.aspx Club Quarters hotel] in Center City Philadelphia. There are some additional hotel suggestions [http://www.admissionsug.upenn.edu/visiting/accommodations.php here] and in the "Hotels" section [http://www.upenn.edu/campus/philadelphia.php here]. There may also be some local residents willing to accommodate a few attendees. See the [[/Attendees|attendees page]] for more info.<br />
<br />
== Map ==<br />
<br />
Here is a [http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=117635619663929119581.00046ad73c83c72a23d67&ll=39.954783,-75.194485&spn=0.001667,0.002403&t=h&z=15 Google map] with relevant locations marked.<br />
<br />
== Preparations ==<br />
<br />
=== Before you arrive ===<br />
<br />
* Pick out a couple of projects to work on and familiarise yourself with them, or bring your own project(s) to work on. See the [[/Projects|projects page]] for a list of projects people plan to work on. If you plan to work on your own project, be sure to list it on the [[/Projects|projects page]] and set up a public repository if you don't already have one, so that other people can help hack on your project.<br />
* Install an up to date Haskell toolchain: at least ghc and cabal-install. If you don't already have these installed (or need to install from scratch on the laptop you're bringing), the easiest way is probably to install the [http://hackage.haskell.org/platform/ Haskell Platform].<br />
<br />
== Contact ==<br />
<br />
For any questions or emergencies, you can always call Brent Yorgey at (215) 350-4532, Daniel Wagner at (650) 353-1788 or Chris Casinghino at (603) 860-5301.<br />
<br />
== Attendees ==<br />
<br />
See the [[/Attendees | Attendees]] page.<br />
<br />
== Organization ==<br />
<br />
The organizers of Hac φ:<br />
<br />
* Daniel Wagner (dmwit)<br />
* Brent Yorgey (byorgey)<br />
* Chris Casinghino (ccasin)<br />
<br />
[[Category:Community]]<br />
[[Category:Events]]<br />
[[Category:Hackathon]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-04-27T13:51:43Z<p>Dmwit: /* Additional Comments */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
| (857)244-1001<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served. (now taken)<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Xmonad/Frequently_asked_questionsXmonad/Frequently asked questions2013-04-26T18:35:53Z<p>Dmwit: /* Watch fullscreen flash video */</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/package/xmonad-contrib 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>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-04-10T16:03:03Z<p>Dmwit: /* Additional Comments */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
I (Daniel Wagner) have space on my couch if somebody would like to crash with me for the weekend. Send me an email if you're interested; first-come, first-served.<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/TalksHac φ/Talks2013-04-10T15:41:45Z<p>Dmwit: /* Talks */ clear talk list in preparation for 2013</p>
<hr />
<div>If you'd like to give a talk, announce it here; tell us your name, the title of the talk, a short description. Please also let us know if you won't be attending Saturday afternoon and want to present at some other time.<br />
<br />
== Talks == <br />
<br />
{| class="wikitable"<br />
! Talk Name<br />
! Speaker<br />
<!-- copy this template to add your talk<br />
|-<br />
| A Stunning Talk on an Unfathomable Topic<br />
| Joe the Mighty<br />
--><br />
|}<br />
<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/ProjectsHac φ/Projects2013-04-10T15:39:55Z<p>Dmwit: /* Projects */ clear projects list in preparation for 2013 (feel free to add yourself back!)</p>
<hr />
<div>== Sharing your code ==<br />
<br />
If you need a place to host a project so that others can help with it, we suggest [http://patch-tag.com/ patch-tag], which offers free hosting for public darcs repositories. If you're using git, [http://github.com github] is just dandy as well.<br />
<br />
You can also apply for an account on <br />
[http://community.haskell.org/admin/ the community server].<br />
<br />
== Projects ==<br />
<br />
If you have a project that you want to work on at the Hackathon, please describe it here.<br />
<br />
Since Hackathons are great for teamwork, consider joining one of the projects mentioned below. If you're interested in one of these projects, add your name to the list of hackers under that project.<br />
<!-- Copy this template<br />
=== Project name ===<br />
<br />
I am a project. Love me.<br />
<br />
* Hacker 1<br />
* Hacker 2<br />
--><br />
<br />
== Experience ==<br />
<br />
Please list projects with which you are familiar. This way, people know whom to contact for more information or guidance on a particular project.<br />
<br />
{| class="wikitable"<br />
! Name<br />
! Projects<br />
|-<br />
| byorgey<br />
| [http://www.xmonad.org xmonad], [http://code.haskell.org/diagrams diagrams]<br />
|-<br />
| ccasin<br />
| [http://hcross.sourceforge.net hcross]<br />
|-<br />
| mightybyte<br />
| [http://snapframework.com snap], [http://hackage.haskell.org/package/heist heist]<br />
|- <br />
| sweirich<br />
| [http://code.google.com/p/replib/ RepLib and Unbound] <br />
|}<br />
<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2013-04-10T15:37:49Z<p>Dmwit: /* Attendees */ clear attendee list in preparation for 2013</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.<br />
<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/RegisterHac φ/Register2013-04-10T15:36:58Z<p>Dmwit: /* Registration */</p>
<hr />
<div>= Registration =<br />
<br />
<!--<br />
(Registration for the main event is now closed. For registration to the Berlin <br />
satellite event, see bottom of this section.)<br />
--><br />
<br />
Registration is via email to Daniel Wagner at<br />
<br />
wagnerdm@seas.upenn.edu<br />
<br />
with the subject<br />
<br />
Hac phi registration <br />
<br />
and body containing the following information:<br />
<br />
Name:<br />
#haskell nick: (if applicable)<br />
Email:<br />
Food restrictions:<br />
Days attending: <br />
Institution:<br />
<br />
There will be a public list of attendees' names and nicks; please include the word "private" after your information if you would like to opt out of the public list. Here is an example:<br />
<br />
Name: Daniel Wagner<br />
#haskell nick: dmwit<br />
Email: daniel@wagner-home.com<br />
Food restrictions: none<br />
Days attending: all<br />
Institution: Lambdas Ltd.<br />
<br />
Note: We need an "institution" for each attendee in order to get wireless access codes. Feel free to make it up if necessary.<br />
<br />
Once you're registered, you should also subscribe to the [http://www.haskell.org/mailman/listinfo/hackathon Hac φ mailing list]. We will send out useful information to all of the attendees on that list. You can also add your name to [[Hac φ/Attendees|the attendees page]].<br />
<br />
<!--<br />
=== registration for berlin ===<br />
<br />
If you want to attend in Berlin, write an e-mail to Matthias Fischmann at<br />
<br />
fis@etc-network.de<br />
<br />
following the above procedure. (Number of participants may be limited. Please wait for confirmation of your registration before you make any travel arrangements!)<br />
--><br />
<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/RegisterHac φ/Register2013-04-10T15:36:31Z<p>Dmwit: /* Registration */ make the example match up with the form</p>
<hr />
<div>= Registration =<br />
<br />
<!--<br />
(Registration for the main event is now closed. For registration to the Berlin <br />
satellite event, see bottom of this section.)<br />
--><br />
<br />
Registration is via email to Daniel Wagner at<br />
<br />
wagnerdm@seas.upenn.edu<br />
<br />
with the subject<br />
<br />
Hac phi registration <br />
<br />
and body containing the following information:<br />
<br />
Name:<br />
#haskell nick: (if applicable)<br />
Email:<br />
Food restrictions:<br />
Days attending: <br />
Institution:<br />
<br />
There will be a public list of attendees' names and nicks; please include the word "private" after your information if you would like to opt out of the public list. Here is an example:<br />
<br />
Name: Daniel Wagner<br />
#haskell nick: dmwit<br />
Email: daniel@wagner-home.com<br />
Food restrictions: none<br />
Days attending: September 2008-August 2017<br />
Institution: Lambdas Ltd.<br />
<br />
Note: We need an "institution" for each attendee in order to get wireless access codes. Feel free to make it up if necessary.<br />
<br />
Once you're registered, you should also subscribe to the [http://www.haskell.org/mailman/listinfo/hackathon Hac φ mailing list]. We will send out useful information to all of the attendees on that list. You can also add your name to [[Hac φ/Attendees|the attendees page]].<br />
<br />
<!--<br />
=== registration for berlin ===<br />
<br />
If you want to attend in Berlin, write an e-mail to Matthias Fischmann at<br />
<br />
fis@etc-network.de<br />
<br />
following the above procedure. (Number of participants may be limited. Please wait for confirmation of your registration before you make any travel arrangements!)<br />
--><br />
<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/RegisterHac φ/Register2013-04-10T15:35:39Z<p>Dmwit: /* Registration */ this isn't new this year any more!</p>
<hr />
<div>= Registration =<br />
<br />
<!--<br />
(Registration for the main event is now closed. For registration to the Berlin <br />
satellite event, see bottom of this section.)<br />
--><br />
<br />
Registration is via email to Daniel Wagner at<br />
<br />
wagnerdm@seas.upenn.edu<br />
<br />
with the subject<br />
<br />
Hac phi registration <br />
<br />
and body containing the following information:<br />
<br />
Name:<br />
#haskell nick: (if applicable)<br />
Email:<br />
Food restrictions:<br />
Days attending: <br />
Institution:<br />
<br />
There will be a public list of attendees' names and nicks; please include the word "private" after your information if you would like to opt out of the public list. Here is an example:<br />
<br />
Name: Daniel Wagner<br />
Nick: dmwit<br />
Email: daniel@wagner-home.com<br />
Food restrictions: none<br />
Days attending: September 2008-August 2017<br />
Institution: Lambdas Ltd.<br />
<br />
Note: We need an "institution" for each attendee in order to get wireless access codes. Feel free to make it up if necessary.<br />
<br />
Once you're registered, you should also subscribe to the [http://www.haskell.org/mailman/listinfo/hackathon Hac φ mailing list]. We will send out useful information to all of the attendees on that list. You can also add your name to [[Hac φ/Attendees|the attendees page]].<br />
<br />
<!--<br />
=== registration for berlin ===<br />
<br />
If you want to attend in Berlin, write an e-mail to Matthias Fischmann at<br />
<br />
fis@etc-network.de<br />
<br />
following the above procedure. (Number of participants may be limited. Please wait for confirmation of your registration before you make any travel arrangements!)<br />
--><br />
<br />
<br />
[[Category:Community]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86Hac φ2013-04-10T15:33:44Z<p>Dmwit: updates for 2013</p>
<hr />
<div>'''June 7-9, 2013'''<br />
<br />
Philadelphia, Pennsylvania, USA<br />
<br />
== About ==<br />
<br />
The Haskell Hackathon is an international, grassroots collaborative coding festival with a simple focus: build and improve Haskell libraries, tools, and infrastructure.<br />
<br />
Hac φ will be held June 7-9, 2013 at the [http://www.upenn.edu/ University of Pennsylvania] in [http://en.wikipedia.org/wiki/Philadelphia Philadelphia]. It is open to all -- you do not have to be a Haskell guru to attend. All you need is a basic knowledge of Haskell, a willingness to learn, and a [[/Projects|project]] you're excited to help with (or a project of your own to work on).<br />
<br />
There will be lots of hacking, some talks, good food, and, of course, fun!<br />
<br />
* IRC channel: #haskell-hacphi (freenode)<br />
* Mailing list: [http://www.haskell.org/mailman/listinfo/hackathon hackathon@haskell.org]<br />
<br />
<!-- reinstate if the Berlin thing happens again<br />
=== Berlin satellite ===<br />
<br />
For those who want to attend but are too far away from Philly, we are hosting a satellite workshop in Berlin, Germany. It's very informal, but will provide a local crowd, power & wifi, and a video link for the talks and to play with, and lots of restaurants, bars and hostels in walking distance.<br />
<br />
* Address: http://dasdeck.de/<br />
* Phone: +49 179 7733223<br />
<br />
Please check the [[/Register|registration section]] on how to register there. <b>We have limited space and will accept you first-come-first-serve</b>, so please wait for your confirmation before you start making travel arrangements!<br />
--><br />
<br />
== Registration ==<br />
<br />
<!-- Registration is now closed. If you've already registered, you can --><br />
If you will be attending, please [[/Register|register]]. Registration is free, and open to everyone. If you like, you can also<br />
[[/Attendees|list yourself as an attendee]]. Then check out the [[/Projects|projects page]].<br />
<br />
Registration closes Friday, May 24, 2013 at 1430 local time (local to you!).<br />
<br />
== When ==<br />
<br />
June 7-9, 2013 from 2:30-8pm Friday, 9am-8pm Saturday, and 10am-5pm Sunday. There will probably be some talks Saturday afternoon.<br />
<br />
Although the hackathon won't officially kick off until 2:30pm on Friday, you are welcome to arrive the evening of Thursday the 2nd or Friday morning if it makes for easier travel. If enough people are around and interested, some sort of activity could be arranged for Thursday evening and/or Friday morning.<br />
<br />
== Talks ==<br />
<br />
If you'd be interested in giving a short (15-20 minute) talk, put your name and the subject of your talk on the [[/Talks|talks page]]. There will be a projector and blackboard available.<br />
<br />
<!-- what are our sponsors this year?<br />
== Sponsors ==<br />
<br />
Hac φ 2012 is sponsored by [http://www.janestcapital.com/ Jane St. Capital] and [http://www.amgen.com/ Amgen]. Both of these companies are active users of functional programming!<br />
--><br />
<br />
== Location ==<br />
<br />
Check out the [http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=117635619663929119581.00046ad73c83c72a23d67&ll=39.954783,-75.194485&spn=0.001667,0.002403&t=h&z=15 Google map] for info on relevant locations.<br />
<br />
=== Getting to Philadelphia ===<br />
<br />
==== Air ====<br />
<br />
[http://www.phl.org/Pages/HomePage.aspx Philadelphia International Airport] (PHL) is the closest major airport.<br />
<br />
==== Train ====<br />
<br />
Take [http://www.amtrak.com Amtrak] to 30th Street Station (station code PHL), which is just a few blocks from Levine Hall; see the [http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=117635619663929119581.00046ad73c83c72a23d67&ll=39.954783,-75.194485&spn=0.001667,0.002403&t=h&z=15 Google map].<br />
<br />
==== Car ====<br />
<br />
UPenn's admissions office has [http://www.admissionsug.upenn.edu/visiting/directions.php driving directions] that take you right into the center of campus.<br />
<br />
=== Intra-city Transportation ===<br />
<br />
The Hackathon will be held in room 307 of Levine Hall. See Penn's searchable [http://www.facilities.upenn.edu/map.php campus map] for more on this location.<br />
<br />
==== Without a car ====<br />
<br />
* [http://www.septa.org/ SEPTA] operates the trains, busses, and trolleys in Philadelphia. The fare is $2 per trip, exact change (so save up your $1s before you come). You can also get tokens (which are cheaper, and don't require exact change to buy) at most big stops. Their site is a little bit unfriendly; I recommend using the [http://airs1.septa.org/bin/query.exe/en Trip Planner] to find out what routes to take, then consult the [http://www.septa.org/service.html route schedules] to find out how often those lines run, so you know how flexible your trip will be.<br />
* There are about a dozen cab companies serving various parts of the city; Google will point the way. You will likely be within Center City and University City (sometimes called West Philadelphia) for the duration of your visit. Hailing cabs is also theoretically possible, but I would recommend giving the radio dispatcher a call if you want to take a cab.<br />
* Walking is always an option. Philadelphia is a very walkable city.<br />
<br />
==== From the airport ====<br />
<br />
* There is a SEPTA Airport Express Train (R1) every half hour; the fare is $7 (pay after you get on the train). If coming directly to the hackathon, get off at University City station and walk a block west and a block north; otherwise, go one stop further to 30th Street Station to connect to other forms of transportation.<br />
* A cab from the airport to Center City or University City is about $30.<br />
* The PHL website has a [http://www.phl.org/passengerinfo/transportationservices/pages/rental_cars.aspx list of rental car companies]. UPenn's admissions office has [http://www.admissionsug.upenn.edu/visiting/directions.php driving directions] that take you right into the center of campus.<br />
* Walking is probably not an option.<br />
<br />
==== With a car ====<br />
<br />
There is some parking on-campus, as well as street-parking for $1/hour. To help with interpreting the maps below, Levine Hall is located at 34th and Walnut.<br />
<br />
* [http://www.admissionsug.upenn.edu/visiting/directions.php Parking on campus]<br />
* The [http://cms.business-services.upenn.edu/parking/ Penn Parking] site, especially the [http://cms.business-services.upenn.edu/parking/where-to-park/visitors-and-vendors.html Where to Park] page<br />
* [http://cms.business-services.upenn.edu/parking/images/stories/2010mapparking_staticrev4.pdf Parking map]<br />
<br />
The [http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=117635619663929119581.00046ad73c83c72a23d67&ll=39.954783,-75.194485&spn=0.001667,0.002403&t=h&z=15 Google map] also highlights the public parking locations near the hackathon; the fee is about $13/day.<br />
<br />
While you're planning your route, keep in mind that while the city is laid out mostly in a grid, about half of the roads are one-way.<br />
<br />
=== Accommodation ===<br />
<br />
<!--<br />
A block of single rooms has been reserved at the [http://www.clubquarters.com/loc_philadelphia.aspx Club Quarters hotel] in center city Philadelphia. These rooms are available for<br />
$87/night on May 21st and 22nd. Call them and mention the "PL Group"<br />
to receive this discount. You must reserve your room by April 23rd<br />
for the reduced rate.<br />
--><br />
You may get a discounted rate at the [http://www.clubquarters.com/loc_philadelphia.aspx Club Quarters hotel] in Center-City Philadelphia. When contacting them, tell them you are coming for a UPenn event. Call [http://www.cis.upenn.edu/cherylh.shtml Cheryl Hickey] if they give you a lot of grief.<br />
<br />
There are some additional hotel suggestions<br />
[http://www.admissionsug.upenn.edu/visiting/accommodations.php here]<br />
and in the "Hotels" section<br />
[http://www.upenn.edu/campus/philadelphia.php here]. There may also<br />
be some local residents willing to accommodate a few attendees. See<br />
the [[/Attendees|attendees page]] for more info.<br />
<br />
== Map ==<br />
<br />
Here is a [http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=117635619663929119581.00046ad73c83c72a23d67&ll=39.954783,-75.194485&spn=0.001667,0.002403&t=h&z=15 Google map] with relevant locations marked.<br />
<br />
== Preparations ==<br />
<br />
=== Before you arrive ===<br />
<br />
* Pick out a couple of projects to work on and familiarise yourself with them, or bring your own project(s) to work on. See the [[/Projects|projects page]] for a list of projects people plan to work on. If you plan to work on your own project, be sure to list it on the [[/Projects|projects page]] and set up a public repository if you don't already have one, so that other people can help hack on your project.<br />
* Install an up to date Haskell toolchain: at least ghc and cabal-install. If you don't already have these installed (or need to install from scratch on the laptop you're bringing), the easiest way is probably to install the [http://hackage.haskell.org/platform/ Haskell Platform].<br />
<br />
== Contact ==<br />
<br />
For any questions or emergencies, you can always call Brent Yorgey at (215) 350-4532, Daniel Wagner at (650) 353-1788 or Chris Casinghino at (603) 860-5301.<br />
<br />
== Attendees ==<br />
<br />
See the [[/Attendees | Attendees]] page.<br />
<br />
== Organization ==<br />
<br />
The organizers of Hac φ:<br />
<br />
* Daniel Wagner (dmwit)<br />
* Brent Yorgey (byorgey)<br />
* Chris Casinghino (ccasin)<br />
<br />
[[Category:Community]]<br />
[[Category:Events]]<br />
[[Category:Hackathon]]</div>Dmwithttps://wiki.haskell.org/How_to_get_rid_of_IOHow to get rid of IO2013-03-08T15:17:22Z<p>Dmwit: /* Answer */ copy editing: fix whitespace, remove acronyms, remove value judgments, correct grammar</p>
<hr />
<div>== Question ==<br />
<br />
I have something of type <hask>IO a</hask>, but I need something of type <hask>a</hask><br />
How can I get that?<br />
<br />
== Answer ==<br />
<br />
You can get rid of it, but you almost certainly don't need to. The special safety belt of Haskell is that you cannot get rid of IO! Nonetheless, the biggest parts of Haskell programs are and should be non-IO functions. Applications using both IO and non-IO functions are written by plugging together these two flavors of functions using functions like <hask>(>>=)</hask>. These functions allow useful IO while having all the safety properties of a pure [[functional programming]] language.<br />
<br />
You can hide some functions using [[do notation]], which looks like this:<br />
<haskell><br />
do text <- readFile "foo"<br />
writeFile "bar" (someComplicatedNonIOOperation text)<br />
</haskell><br />
Without hiding the functions, this would look like:<br />
<haskell><br />
writeFile "bar" . someComplicatedNonIOOperation =<< readFile "foo"<br />
</haskell><br />
<br />
=== What we didn't tell you at the beginning ===<br />
<br />
There is a function which directly answers the initial question, namely, <hask>unsafePerformIO</hask>.<br />
It is however not intended for conveniently getting rid of the <hask>IO</hask> constructor.<br />
It must only be used to wrap IO functions that behave like non-IO functions,<br />
Since this property cannot be checked by the compiler, it is your task and thus the <hask>unsafe</hask> part of the name.<br />
(Some library writers have abused that name component for [[partial function]]s. Don't get confused!)<br />
You will only need this in rare cases and only experienced programmers shall do this.<br />
<br />
== See also ==<br />
<br />
* [[Introduction to IO]]<br />
* [[Avoiding IO]] - Avoiding IO in the first place is a good thing, and we tell you how to achieve that<br />
* [[Tutorials#Practical_Haskell|Tackling the awkward squad]]<br />
* http://www.haskell.org/wikisnapshot/ThatAnnoyingIoType.html<br />
* http://www.haskell.org/wikisnapshot/UsingIo.html<br />
<br />
[[Category:FAQ]]<br />
[[Category:Monad]]</div>Dmwithttps://wiki.haskell.org/99_questions/1_to_1099 questions/1 to 102013-02-24T23:02:15Z<p>Dmwit: /* Problem 8 */ the sample input/output pair was a bit obtuse</p>
<hr />
<div>__NOTOC__<br />
<br />
This is part of [[H-99:_Ninety-Nine_Haskell_Problems|Ninety-Nine Haskell Problems]], based on [https://sites.google.com/site/prologsite/prolog-problems Ninety-Nine Prolog Problems] and [http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html Ninety-Nine Lisp Problems].<br />
<br />
== Problem 1 ==<br />
<br />
(*) Find the last element of a list.<br />
<br />
(Note that the Lisp transcription of this problem is incorrect.)<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> myLast [1,2,3,4]<br />
4<br />
Prelude> myLast ['x','y','z']<br />
'z'<br />
</haskell><br />
<br />
[[99 questions/Solutions/1 | Solutions]]<br />
<br />
<br />
== Problem 2 ==<br />
<br />
(*) Find the last but one element of a list.<br />
<br />
(Note that the Lisp transcription of this problem is incorrect.)<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> myButLast [1,2,3,4]<br />
3<br />
Prelude> myButLast ['a'..'z']<br />
'y'<br />
</haskell><br />
<br />
[[99 questions/Solutions/2 | Solutions]]<br />
<br />
<br />
== Problem 3 ==<br />
<br />
(*) Find the K'th element of a list. The first element in the list is number 1.<br />
<br />
Example:<br />
<br />
<pre><br />
* (element-at '(a b c d e) 3)<br />
c<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> elementAt [1,2,3] 2<br />
2<br />
Prelude> elementAt "haskell" 5<br />
'e'<br />
</haskell><br />
<br />
[[99 questions/Solutions/3 | Solutions]]<br />
<br />
<br />
== Problem 4 ==<br />
<br />
(*) Find the number of elements of a list.<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> myLength [123, 456, 789]<br />
3<br />
Prelude> myLength "Hello, world!"<br />
13<br />
</haskell><br />
<br />
[[99 questions/Solutions/4 | Solutions]]<br />
<br />
<br />
== Problem 5 ==<br />
<br />
(*) Reverse a list.<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> reverse "A man, a plan, a canal, panama!"<br />
"!amanap ,lanac a ,nalp a ,nam A"<br />
Prelude> reverse [1,2,3,4]<br />
[4,3,2,1]<br />
</haskell><br />
<br />
[[99 questions/Solutions/5 | Solutions]]<br />
<br />
<br />
== Problem 6 ==<br />
<br />
(*) Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x).<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
*Main> isPalindrome [1,2,3]<br />
False<br />
*Main> isPalindrome "madamimadam"<br />
True<br />
*Main> isPalindrome [1,2,4,8,16,8,4,2,1]<br />
True<br />
</haskell><br />
<br />
[[99 questions/Solutions/6 | Solutions]]<br />
<br />
<br />
== Problem 7 ==<br />
<br />
(**) Flatten a nested list structure.<br />
<br />
Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).<br />
<br />
Example:<br />
<br />
<pre><br />
* (my-flatten '(a (b (c d) e)))<br />
(A B C D E)<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
We have to define a new data type, because lists in Haskell are homogeneous. <br />
<haskell><br />
data NestedList a = Elem a | List [NestedList a]<br />
</haskell><br />
<br />
<haskell><br />
*Main> flatten (Elem 5)<br />
[5]<br />
*Main> flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])<br />
[1,2,3,4,5]<br />
*Main> flatten (List [])<br />
[]<br />
</haskell><br />
<br />
<br />
<br />
[[99 questions/Solutions/7 | Solutions]]<br />
<br />
== Problem 8 ==<br />
<br />
(**) Eliminate consecutive duplicates of list elements.<br />
<br />
If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.<br />
<br />
Example:<br />
<br />
<pre><br />
* (compress '(a a a a b c c a a d e e e e))<br />
(A B C A D E)<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
> compress "aaaabccaadeeee"<br />
"abcade"<br />
</haskell><br />
<br />
[[99 questions/Solutions/8 | Solutions]]<br />
<br />
== Problem 9 ==<br />
<br />
(**) Pack consecutive duplicates of list elements into sublists.<br />
If a list contains repeated elements they should be placed in separate sublists.<br />
<br />
Example:<br />
<br />
<pre><br />
* (pack '(a a a a b c c a a d e e e e))<br />
((A A A A) (B) (C C) (A A) (D) (E E E E))<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
*Main> pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', <br />
'a', 'd', 'e', 'e', 'e', 'e']<br />
["aaaa","b","cc","aa","d","eeee"]<br />
</haskell><br />
<br />
[[99 questions/Solutions/9 | Solutions]]<br />
<br />
== Problem 10 ==<br />
<br />
(*) Run-length encoding of a list.<br />
Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.<br />
<br />
Example:<br />
<pre><br />
* (encode '(a a a a b c c a a d e e e e))<br />
((4 A) (1 B) (2 C) (2 A) (1 D)(4 E))<br />
</pre><br />
<br />
Example in Haskell:<br />
<haskell><br />
encode "aaaabccaadeeee"<br />
[(4,'a'),(1,'b'),(2,'c'),(2,'a'),(1,'d'),(4,'e')]<br />
</haskell><br />
<br />
[[99 questions/Solutions/10 | Solutions]]<br />
<br />
<br />
[[Category:Tutorials]]</div>Dmwithttps://wiki.haskell.org/Xmonad/General_xmonad.hs_config_tipsXmonad/General xmonad.hs config tips2012-12-05T10:48:18Z<p>Dmwit: /* Doing things on another workspace while focus stays on current */ let this code typecheck</p>
<hr />
<div>[[Category:XMonad configuration]]<br />
<br />
This document assumes you're running >= XMonad-0.8.<br />
<br />
It describes general tips for configuring xmonad.hs, for example "How to make window ''X'' float by default" and others. If you can't find what you're searching for, you may want to look at the [[Xmonad/Config_archive|Config archive]] or ask for help on #xmonad@irc.freenode.net. <br />
<br />
Also useful, for an overview of how to configure bindings and hooks, and (somewhat out of date) summary of xmonad-contrib extensions, see [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Doc-Extending.html XMonad.Doc.Extending].<br />
<br />
Please add what you found useful, and of course improving existing tips or adding alternatives is highly appreciated!<br />
<br />
== Managing Windows aka Manage Hooks ==<br />
<hask>ManageHook</hask>s define special actions to be performed on newly created windows matching specific properties.<br />
<br />
=== Making window float by default, or send it to specific workspace ===<br />
====ManageHook examples====<br />
This example shifts '''Rhythmbox''' to workspace <tt>"="</tt> and '''XDvi''' to <tt>"7:dvi"</tt>, floats '''Xmessage''', and uses <hask>manageDocks</hask> to make docks visible on all workspaces. All this is combined with the default XMonad <hask>manageHook</hask>. [[Xmonad/Config_archive/John_Goerzen%27s_Configuration|This step-by-step tutorial]] covers initially setting up a <hask>manageHook</hask>, too.<br />
<br />
<haskell><br />
import XMonad<br />
import XMonad.Hooks.ManageDocks<br />
import XMonad.Util.EZConfig<br />
-- module imports and other top level definitions<br />
<br />
myManageHook = composeAll<br />
[ className =? "Rhythmbox" --> doShift "="<br />
, className =? "XDvi" --> doShift "7:dvi"<br />
, className =? "Xmessage" --> doFloat<br />
, manageDocks<br />
]<br />
<br />
main = xmonad $ defaultConfig<br />
{ workspaces = ["1:dev","2:mail","3:web","4:comm","5:ham","6:tmp","7:dvi","8","9","0","-","="]<br />
, manageHook = myManageHook <+> manageHook defaultConfig -- uses default too<br />
-- set terminal, modMask, etc.<br />
} `additionalKeysP` myKeys<br />
</haskell><br />
<br />
This example sends '''Firefox''' to workspace <tt>"web"</tt> when it starts. '''Gajim''' gets sent to workspace <tt>"jabber"</tt>. Finally, it floats '''Firefox''' dialog windows, '''Gajim''' and '''Xmessage''' windows, and windows with <tt>Google</tt> or <tt>Pidgin</tt> as any part of the class name; likewise, any window with <tt>VLC</tt> anywhere in its title.<br />
<haskell><br />
-- Data.List provides isPrefixOf isSuffixOf and isInfixOf<br />
import Data.List <br />
--<br />
myManageHook = composeAll . concat $<br />
[ [ className =? "Firefox-bin" --> doShift "web" ]<br />
, [ className =? "Gajim.py" --> doShift "jabber" ]<br />
, [(className =? "Firefox" <&&> resource =? "Dialog") --> doFloat]<br />
<br />
-- using list comprehensions and partial matches<br />
, [ className =? c --> doFloat | c <- myFloatsC ]<br />
, [ fmap ( c `isInfixOf`) className --> doFloat | c <- myMatchAnywhereFloatsC ]<br />
, [ fmap ( c `isInfixOf`) title --> doFloat | c <- myMatchAnywhereFloatsT ]<br />
]<br />
-- in a composeAll hook, you'd use: fmap ("VLC" `isInfixOf`) title --> doFloat<br />
where myFloatsC = ["Gajim.py", "Xmessage"]<br />
myMatchAnywhereFloatsC = ["Google","Pidgin"]<br />
myMatchAnywhereFloatsT = ["VLC"] -- this one is silly for only one string!<br />
</haskell><br />
<br />
Here's another example using both classes and titles:<br />
<haskell><br />
myManageHook :: ManageHook<br />
myManageHook = composeAll . concat $<br />
[ [ title =? t --> doFloat | t <- myTitleFloats]<br />
, [ className =? c --> doFloat | c <- myClassFloats ] ]<br />
where<br />
myTitleFloats = ["Transferring"] -- for the KDE "open link" popup from konsole<br />
myClassFloats = ["Pinentry"] -- for gpg passphrase entry<br />
</haskell><br />
<br />
====Shift an app to a workspace and view it====<br />
The following will put new '''FocusMeNow''' windows on the <tt>"doc"</tt> workspace and also <hask>greedyView</hask> that workspace.<br />
<haskell><br />
import Control.Monad (liftM2)<br />
<br />
myManageHook = composeAll<br />
[ className = "FocusMeNow" --> viewShift "doc"<br />
-- more hooks<br />
]<br />
where viewShift = doF . liftM2 (.) W.greedyView W.shift<br />
</haskell><br />
<br />
====Floating all new windows====<br />
To float all windows and manually tile them with <em>&lsaquo;mod&rsaquo;-</em>t, simply add <hask> <+> doFloat</hask> to your manage hooks. ''Warning:'' you don't want to combine this with hooks such as <hask>doF W.swapDown</hask> which put new windows below others. Also, the floating layer isn't designed for extensive use; if possible, limit <hask>doFloat</hask> to apps that really need it (see examples in previous section.)<br />
<haskell><br />
-- skipped<br />
main = xmonad defaultConfig<br />
{ manageHook = myManageHooks <+> doFloat<br />
-- more changes<br />
}<br />
</haskell><br />
<br />
==== Making windows unfloat ====<br />
A related task is - how do I unfloat windows of a particular class or name? See the <hask>unfloat</hask> hook defined in the following example:<br />
<br />
<haskell><br />
-- A manageHook to float everything by default and unfloat a few windows<br />
myManageHook :: ManageHook<br />
myManageHook = composeAll [ className =? "defcon.bin.x86" --> unfloat,<br />
className =? "Darwinia" --> unfloat ]<br />
<+> doFloat <+> manageDocks<br />
where unfloat = ask >>= doF . W.sink<br />
</haskell><br />
<br />
====More info about ManageHooks====<br />
See the FAQ about [[Xmonad/Frequently asked questions#I need to find the class title or some other X property of my program|using xprop]] to get the <hask>className</hask>, <hask>appName</hask>, <hask>title</hask> or other string properties of windows.<br />
<br />
See also the [http://xmonad.org/xmonad-docs/xmonad/XMonad-ManageHook.html documentation for ManageHook] or the ManageHook section in <br />
[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Doc-Extending.html#15 Extending XMonad].<br />
<br />
=== Gimp ===<br />
The most popular Gimp setups with xmonad are the default of floating all Gimp windows, or using two nested [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-IM.html Layout.IM] modifiers to put the toolbox and dock panels to either side of some other layout like [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-Tabbed.html tabbed] or <hask>(MyFavoriteTilingLayout ||| Full)</hask>, plus usually floating tool dialogs with <hask>manageHook</hask>s. Some people combine the toolbox and dock into a single panel. See [[#Tiling most windows in gimp|sample configs]] below.<br />
<br />
====Gimp windows as seen by xmonad====<br />
To choose how to work with the Gimp in XMonad, it's helpful to understand<br />
the different types of windows as XMonad sees them. If you just want<br />
some example setups, skip to the next section.<br />
<br />
* '''All Gimp windows''', i.e. those with <tt>WM_CLASS</tt> class of <tt>"Gimp"</tt>. These windows float if you have <hask>manageHook defaultConfig</hask> anywhere in your <hask>manageHook</hask>. You probably ''don't'' want this if you plan to tile even the Gimp tool setting dialogs. Otherwise keep the <hask>manageHook defaultConfig</hask>, and only unfloat the <tt>gimp-toolbox</tt>, <tt>gimp-image-window</tt>, and possibly <tt>gimp-dock</tt>.<br />
<br />
* '''Transient or fixed size windows''', like file open, ok/cancel, fixed size tool dialogs, etc. XMonad floats these by default for all applications, even ''without'' using <hask> manageHook defaultConfig</hask>. If you ''really'' want to, you can unfloat specific transients or fixed size windows -- see [[#Making_windows_unfloat|unfloat]] above.<br />
<br />
* '''Gimp toolbox or dock(s)''', matched with <tt>WM_WINDOW_ROLE(STRING)</tt> to use <hask>layoutHook</hask>s or <hask>manageHook</hask>s to place and manage them. Also, with drag and drop you can combine or separate their tabs and panes into one or more windows depending on how you want to use them.<br />
<br />
:On startup, a default Gimp install creates (1) an empty image window, (2) the '''toolbox''' window (brushes, eraser, etc. and their options), and (3) a single '''dock''' (layers, paths, etc.) Customize them by dragging tabs to and from existing panels or onto the "create panel separator" on either type of window, (it will highlight when a dragged tab is over it). (It's just below the fg/bg color swatches on the toolbox window.)<br />
<br />
* '''Gimp tool windows''', matched by suffix <tt>"tool"</tt> with <tt>WM_WINDOW_ROLE(STRING)</tt>. (Or with darcs XMonad (0.9) or XMonad 0.10, use <hask>isDialog</hask> from [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-ManageHelpers.html ManageHelpers]). These are the many tool settings popups like Levels, Threshold, Curves that normally don't have toolbox tabs. Most people probably want these floated; below is an example of how to do it if you're not starting from all gimp windows being floated.<br />
<br />
====Tiling most windows in Gimp====<br />
A good way to work with the Gimp in XMonad is to tile most windows with <tt>[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-ResizableTile.html resizableTall]</tt>, <tt>[http://xmonad.org/xmonad-docs/xmonad/XMonad-Layout.html#t:Full Full]</tt>, [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-Tabbed.html tabbed] (or several layout choices separated by <hask>|||</hask>) in the center of the screen, and....<br />
<br />
Use <tt>[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-IM.html withIM]</tt>, nested <hask>withIM</hask>s, or <tt>[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-LayoutCombinators.html XMonad.Layout.LayoutCombinators]</tt> to tile your toolbox, combined toolbox and dock, or separate toolbox and dock(s) at the screen edges. As needed, float or unfloat windows by role, or by using <tt>[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Hooks-ManageHelpers.html#v:isDialog Hooks.ManageHelpers.isDialog]</tt> from [http://hackage.haskell.org/package/xmonad-contrib xmonad-contrib].<br />
<br />
(See also [[#Gimp windows as seen by xmonad|Gimp windows section]].)<br />
<br />
To use nested <hask>withIM</hask>s to have the toolbox and dock treated separately, see [http://nathanhowell.net/2009/03/08/xmonad-and-the-gimp/ Nathan Howell's blog post about XMonad and the Gimp].<br />
<br />
:[[Image:Xmonadgimp.jpg|220px]]<br />
<br />
If the property matching doesn't seem to be working correctly, check class or role with xprop. See [[Xmonad/Frequently_asked_questions#I_need_to_find_the_class_title_or_some_other_X_property_of_my_program| Using xprop to find an X property]].<br />
<br />
Here are some sample Gimp related <hask>manageHook</hask> snippets.<br />
<br />
;For people using <hask>manageHook defaultConfig</hask> or <hask>className =? "Gimp"</hask>:<br />
<haskell><br />
import XMonad<br />
import qualified XMonad.StackSet as W<br />
<br />
myManageHook = composeAll<br />
[ (role =? "gimp-toolbox" <||> role =? "gimp-image-window") --> (ask >>= doF . W.sink)<br />
-- Note: hooks earlier in this list override later ones, so put the<br />
-- role hooks earlier than 'className =? "Gimp" ...' if you use both.<br />
<br />
-- other skipped manageHooks...<br />
]<br />
where role = stringProperty "WM_WINDOW_ROLE"<br />
</haskell><br />
<br />
;For people ''not'' using <hask>manageHook defaultConfig</hask> or <hask>className =? "Gimp"</hask>:<br />
<haskell><br />
import XMonad<br />
import Data.List -- for `isSuffixOf`<br />
-- etc<br />
<br />
myManageHook = composeAll<br />
[ -- other manageHooks<br />
, className =? "Gimp-2.6" --> doShift "*" -- may be "Gimp" or "Gimp-2.4" instead<br />
, (className =? "Gimp-2.6" <&&> fmap ("tool" `isSuffixOf`) role) --> doFloat<br />
]<br />
where role = stringProperty "WM_WINDOW_ROLE"<br />
</haskell><br />
<br />
If you use a <tt>[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-Tabbed.html Tabbed]</tt> or <tt>[http://xmonad.org/xmonad-docs/xmonad/XMonad-Layout.html#t:Full Full]</tt> layout as your main layout and get unwanted focus shifts using <tt>[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-IM.html#v:withIM withIM]</tt>, instead try <tt>[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-LayoutCombinators.html LayoutCombinators]</tt> or <tt>[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-ComboP.html ComboP]</tt>, or one of the other layout combiners in xmonad-0.9 and later. Also, make sure you're using <tt>[http://xmonad.org/xmonad-docs/xmonad/XMonad-StackSet.html#v:shiftMaster shiftMaster]</tt> instead of <tt>[http://xmonad.org/xmonad-docs/xmonad/XMonad-StackSet.html#v:swapMaster swapMaster]</tt> in your key and mouse bindings (<hask>swapMaster</hask> was the old default before xmonad-0.9, and some people may still have it in <tt>xmonad.hs</tt>.)<br />
<br />
Also, instead of picking the <hask>Full</hask>/<hask>Tabbed</hask> window with <em>&lsaquo;mod&rsaquo;-&lsaquo;tab&rsaquo;</em>, you can add the following to your mouse bindings, to be able to roll the mouse wheel over the Gimp toolbox until the correct window is focused, which seems to prevent the shifting around:<br />
<haskell><br />
import XMonad.Actions.FlexibleManipulate as Flex<br />
<br />
-- optional. but nicer than normal mouse move and size<br />
, ((mod4Mask, button3), Flex.mouseWindow Flex.discrete)<br />
-- scroll wheel window focusing<br />
, ((mod4Mask, button4), const $ windows W.swapDown)<br />
, ((mod4Mask, button5), const $ windows W.swapUp)<br />
</haskell><br />
<br />
;To use draggable width (<tt>[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-DragPane.html DragPane]</tt> combining <hask>Full</hask> and <hask>Tabbed</hask>) to put a single combined toolbox and dock to the right side of the screen:<br />
<br />
<haskell><br />
-- etc<br />
import XMonad.Hooks.ManageDocks<br />
import XMonad.Layout.NoBorders (smartBorders)<br />
import XMonad.Layout.DragPane<br />
import XMonad.Layout.LayoutCombinators hiding ((|||))<br />
import XMonad.Layout.Tabbed<br />
<br />
myLayoutHook = avoidStruts . smartBorders $<br />
Tall 1 (3 / 100) (1 / 2) ||| tabbedLayout ||| Full ||| gimpLayout<br />
where<br />
tabbedLayout = tabbedBottomAlways shrinkText defaultTheme<br />
gimpLayout = tabbedLayout ****||* Full<br />
</haskell><br />
<br />
:[[Image:AmphiGimpDragCombo.png|220px]]<br />
<br />
;To use <hask>withIM</hask> and a specific workspace (<tt>"*"</tt> here) for the Gimp:<br />
<br />
<haskell><br />
-- etc<br />
import XMonad.Layout.IM<br />
import XMonad.Layout.PerWorkspace<br />
import XMonad.Layout.ResizableTile -- Actions.WindowNavigation is nice too<br />
import XMonad.Util.EZConfig -- or use another method of binding resizable keys<br />
<br />
main = xmonad $ defaultConfig<br />
{ modMask = mod4Mask<br />
-- make sure to use the same workspace Id in workspaces, doShift, and onWorkspace<br />
, workspaces = ["a","b","c","d","e","f","g","*","i"]<br />
-- etc<br />
, manageHook = myManageHook<br />
-- note: the default manageHook floats gimp, so do not <+> manageHook defaultConfig<br />
, layoutHook = myLayouts<br />
} `additionalKeysP` myKeys<br />
<br />
myKeys = -- resize both axes in resizableTall<br />
[ ("M-C-k", sendMessage $ MirrorExpand)<br />
, ("M-C-j", sendMessage $ MirrorShrink)<br />
, ("M-C-h", sendMessage $ Shrink)<br />
, ("M-C-l", sendMessage $ Expand)<br />
]<br />
<br />
myLayoutHook =<br />
onWorkspace "*" gimpLayout $<br />
layoutHook defaultConfig -- layouts to use on other workspaces<br />
where<br />
gimpLayout = withIM (11/64) (Role "gimp-toolbox") $ ResizableTall 2 (1/118) (11/20) [1] ||| Full<br />
<br />
-- other variations<br />
--where<br />
-- mainLayouts = layoutHook defaultConfig<br />
-- gimpLayout = avoidStruts $ withIM (11/64) (Role "gimp-toolbox") $ mainLayouts<br />
-- gimpLayout = Full ||| (avoidStruts $ withIM (11/64) (Role "gimp-toolbox") $ ResizableTall 2 (1/118) (11/20) [1])<br />
-- etc<br />
</haskell><br />
<br />
=== Starting an app on more than one workspace ===<br />
To start emacs on workspaces 2, 3, and 4, for example, use something like the following in your manage hook:<br />
<haskell><br />
-- etc<br />
import XMonad.Actions.CopyWindow<br />
<br />
myManageHook = composeAll<br />
[ className =? "Emacs" --> (ask >>= doF . \w -> (\ws -> foldr ($) ws (copyToWss ["2","4"] w) ) . W.shift "3" ) :: ManageHook<br />
, resource =? "kdesktop" --> doIgnore<br />
]<br />
where copyToWss ids win = map (copyWindow win) ids -- TODO: find method that only calls windows once<br />
</haskell><br />
<br />
=== Ignoring a client (or having it sticky) ===<br />
You can have the position and geometry of a client window respected, and have that window <br />
be sticky, by ignoring it when it is created:<br />
<haskell><br />
main = xmonad $ defaultConfig<br />
{<br />
--<br />
, manageHook = manageHook defaultConfig<br />
<+><br />
(className =? "XClock" --> doIgnore)<br />
--<br />
}<br />
</haskell><br />
Would let xclock be sticky, and have its geometry respected.<br />
<br />
In >xmonad-0.8, the XMonad.Layout.Monitor offers some useful functions for managing such windows as well.<br />
<br />
=== Matching specific windows by setting the resource name or class ===<br />
<br />
Sometimes, instead of matching a program's resource name or window class, it is useful to change the program's name and/or class to something easier to detect. This is most useful when starting programs inside terminal emulators, but can also be used to distinguish between, say, editor sessions.<br />
<br />
Most X11 programs allow you to specify their resource name and/or class. Usually it's not possible to do so down to the level of individual windows, so you are likely to require <tt>[[Xmonad/Frequently_asked_questions#What_about_other_properties.2C_such_as_WM_WINDOW_ROLE.3F|WM_WINDOW_ROLE]]</tt> for that. Note that Java-based programs do not support any useful way to set either resource name or window class ([http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6528430 bug 6528430]).<br />
<br />
==== Gnome and KDE ====<br />
<br />
All Gnome and KDE programs support <tt>--name=</tt> and <tt>--class=</tt> options to specify the resource name and class for windows opened by those programs. Use the <tt>--help-all</tt> option to see these and other low-level options not normally visible.<br />
<br />
===== Terminal emulator factories =====<br />
<br />
<tt>gnome-terminal</tt> by default starts a single back-end "factory" and spawns terminal windows from it; all of these windows will share the same resource name and class. Use the <tt>--disable-factory</tt> option with <tt>--name=</tt> or <tt>--class=</tt> to ensure that the created window is not shared with unrelated terminals.<br />
<br />
Other terminal emulators for Gnome and KDE are likely to behave similarly. ('''[http://userbase.kde.org/Konsole Konsole]''' does not, at least as of this writing; but it does send itself to the background, which will break '''[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Actions-SpawnOn.html XMonad.Actions.SpawnOn]''' unless you use the <tt>--nofork</tt> option.) Look for options to disable shared sessions or factories.<br />
<br />
==== Xt (Xaw, Motif) applications ====<br />
<br />
Programs such as <tt>xterm</tt> and the <tt>rxvt</tt> family of terminal emulators use the standard X11 Xt toolkit, and accept standard toolkit options ("<tt>man 7 X</tt>"; see the '''OPTIONS''' section). Specifically of interest here is the <tt>-name</tt> option. You cannot set the window class; this is fixed by the toolkit to a constant string supplied by the application developer (see <tt>XrmInitialize()</tt>).<br />
<br />
===== urxvtc and urxvtd =====<br />
<br />
This combination uses a single backend (<tt>urxvtd</tt>) which is asked to open terminal windows by <tt>urxvtc</tt>. These windows will share the same resource name. Do not use <tt>-name</tt> with <tt>urxvtc</tt>; instead, use <tt>urxvt</tt> directly. (See [[#Terminal_emulator_factories|Terminal emulator factories]] above.)<br />
<br />
===== Caveat =====<br />
<br />
Programs using the standard X11 toolkit use the resource name and class to read configuration information from the app-defaults database and <tt>~/.Xresources</tt>. Be careful when changing the resource name to insure that it is not being used to select specific configuration information, or copy that configuration information to the new resource name you are using.<br />
<br />
==== Gtk+ and Qt ====<br />
<br />
Gtk+ and Qt programs are encouraged but not required to support <tt>--name</tt> and <tt>--class</tt> as specified in [[#Gnome_and_KDE|Gnome and KDE]] above. Unfortunately, if a given program doesn't support the standard options, it probably doesn't provide any way to control its resource name or class.<br />
<br />
==== Emacs ====<br />
<br />
When Emacs has been built with support for X11, both <tt>-name</tt> and <tt>--name</tt> options should work regardless of the X11 toolkit used. If Emacs only supports running in a terminal, you will need to control the terminal used to run it instead (e.g. <tt>"xterm -n myeditor -e emacs somefile"</tt>.)<br />
<br />
== Key and Mouse Bindings ==<br />
=== Adding your own keybindings ===<br />
<br />
This adds Mod-x keybinding for running ''xlock''.<br />
<haskell><br />
import qualified Data.Map as M<br />
--<br />
<br />
main = xmonad $ defaultConfig {<br />
--<br />
, keys = \c -> mykeys c `M.union` keys defaultConfig c<br />
--<br />
}<br />
where<br />
mykeys (XConfig {modMask = modm}) = M.fromList $<br />
[ ((modm , xK_x), spawn "xlock") ]<br />
</haskell><br />
For a list of the identifiers used for various keys, see<br />
[http://hackage.haskell.org/packages/archive/X11/1.4.5/doc/html/Graphics-X11-Types.html Graphics.X11.Types] and ExtraTypes.<br />
<br />
Also, the [http://code.haskell.org/XMonadContrib/XMonad/Actions/CycleWindows.hs Util.EZConfig] extension allows adding keybindings with simpler syntax, and even creates submaps for sequences like, e.g. "mod-x f" to launch firefox. You can use normal xmonad keybinding lists with its additionalKeys function, or with additionalKeysP, the bindings look like this:<br />
<haskell><br />
-- other imports<br />
import qualified XMonad.StackSet as W<br />
import XMonad.Util.EZConfig<br />
<br />
main = xmonad $ defaultConfig {<br />
terminal = "urxvt"<br />
, modMask = mod4Mask<br />
}<br />
`additionalKeysP`<br />
[ ("M-<Up>", windows W.swapUp)<br />
, ("M-x f", spawn "firefox")<br />
]<br />
`additionalMouseBindings`<br />
[ ((mod4Mask, button3), (\w -> focus w >> Flex.mouseResizeWindow w))<br />
, ((mod4Mask, button4), (\_ -> windows W.focusUp ))<br />
, ((mod4Mask, button5), (\_ -> windows W.focusDown))<br />
]<br />
</haskell><br />
<br />
This is also described in [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Doc-Extending.html#9]<br />
<br />
=== Adding your own mouse bindings ===<br />
Adding your own mouse bindings is explained in<br />
[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Doc-Extending.html#13]<br />
Also see the EZConfig example above.<br />
<br />
If you have a mouse with more than 5 buttons you can simply use '6'<br />
instead of 'button6' which isn't defined.<br />
<br />
e.g. with<br />
[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Util-EZConfig.html EZConfig]:<br />
<br />
,((0, 6), (\w -> focus w >> windows W.swapMaster))<br />
<br />
=== Displaying keybindings with dzen2 ===<br />
Sometimes, trying different xmonad.hs files, or while dialing in custom key bindings it can be nice to have a reminder of what does what. Of course, just editing or grepping the xmonad.hs is one solution, but for a nice colourized output, try adapting a script like this to your needs:<br />
<br />
<pre><br />
fgCol=green4<br />
bgCol=black<br />
titleCol=green4<br />
commentCol=slateblue<br />
keyCol=green2<br />
XCol=orange3<br />
startLine=3<br />
( echo " ^fg($titleCol) ----------- keys -----------^fg()";<br />
egrep 'xK_|eys' ~/.xmonad/xmonad.hs | tail -n +$startLine \<br />
| sed -e 's/\( *--\)\(.*eys*\)/\1^fg('$commentCol')\2^fg()/' \<br />
-e 's/((\(.*xK_.*\)), *\(.*\))/^fg('$keyCol')\1^fg(), ^fg('$XCol')\2^fg()/' <br />
echo '^togglecollapse()';<br />
echo '^scrollhome()' ) | dzen2 -fg $fgCol -bg $bgCol -x 700 -y 36 -l 22 -ta l -w 900 -p<br />
</pre><br />
<br />
Then bind a key to '''<hask>spawn "/path/to/my/showKeysScript"</hask>'''. While there's plenty of room for improvement in the parsing, this is fine for a quick and dirty display of normal or additionalKeys style bindings. It obviously would need to be changed to parse additionalKeysP style. To have comments displayed, note that it looks for indented comments containing 'eys' so use "Keys" or "keys" in " --" style comments to create keybinding subsections.<br />
<br />
Note that in older versions of dzen ^togglecollapse() and ^scrollhome() may not yet be supported. Use something like the following in dzen command line to get similar result:<br />
<br />
<pre><br />
-e 'onstart=togglecollapse,scrollhome;<br />
entertitle=uncollapse,grabkeys;<br />
enterslave=grabkeys;leaveslave=collapse,ungrabkeys;<br />
button2=togglestick;button3=exit:13;<br />
button4=scrollup;button5=scrolldown;<br />
key_Escape=ungrabkeys,exit'<br />
</pre><br />
<br />
[[image: Showkeys.png|220px]]<br />
<br />
=== Binding to the numeric keypad ===<br />
<br />
Bind to the non-numeric versions of these keys. They work<br />
regardless of NumLock status. To avoid conflicts with other apps<br />
you probably want to use them with modifiers. Here is an example<br />
of using them to navigate workspaces in the usual mod-N mod-shift-N<br />
way, but on the key pad:<br />
<br />
<haskell><br />
-- other imports<br />
import qualified XMonad.StackSet as W<br />
import XMonad.Util.EZConfig<br />
<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 />
=== Binding Workspaces on Function Keys ===<br />
'''With default key binding method or EZConfig.additionalKeys'''<br />
<br />
<haskell><br />
-- other imports<br />
import qualified XMonad.StackSet as W<br />
import XMonad.Util.EZConfig<br />
<br />
-- 'zip' will only bind as many keys as there are workspaces so define some more<br />
myWorkspaces = map show [1..12]<br />
<br />
modm = mod4Mask -- win key for mod<br />
<br />
main = xmonad $ defaultConfig<br />
{ workspaces = myWorkspaces<br />
} `additionalKeys` myKeys<br />
<br />
myKeys =<br />
[<br />
-- more custom keybindings<br />
]<br />
++<br />
[((m .|. modm, k), windows $ f i)<br />
| (i, k) <- zip myWorkspaces [xK_F1..xK_F12]<br />
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]<br />
]<br />
</haskell><br />
<br />
'''With EZConfig.additionalKeysP''' use something like the following myKeys instead:<br />
<br />
<haskell><br />
myKeys =<br />
[<br />
-- other "M-C-z" style keys<br />
]<br />
++<br />
[ (otherModMasks ++ "M-" ++ key, action tag)<br />
| (tag, key) <- zip myWorkspaces (map (\x -> "<F" ++ show x ++ ">") [1..12])<br />
, (otherModMasks, action) <- [ ("", windows . W.greedyView) -- or W.view<br />
, ("S-", windows . W.shift)]<br />
]<br />
</haskell><br />
<br />
For reference, the individual bindings assembled by the above list comprehensions look like this:<br />
<br />
<haskell><br />
-- default or additionalKeys style:<br />
-- skipped<br />
, ((modm, xK_F12), windows $ W.greedyView "12")<br />
, ((shiftMask .|. modm, xK_F1), windows $ W.shift "1")<br />
-- etc<br />
<br />
-- additionalKeysP style:<br />
-- skipped<br />
, ("M-<F12>", windows $ W.greedyView "12")<br />
, ("M-S-<F1>", windows $ W.shift "1")<br />
-- etc<br />
</haskell><br />
<br />
== Navigating and Displaying Workspaces ==<br />
=== Using Next Previous Recent Workspaces rather than mod-n ===<br />
The Actions.Plane, Actions.CycleWS, and Actions.CycleRecentWS<br />
extensions allow many ways to navigate workspaces, or shift <br />
windows to other workspaces. <br />
<br />
Plane is easier to set up, especially if you use Gnome. CycleWS<br />
allows binding to nearly any behavior you'd ever want.<br />
Actions.CycleRecentWS allows swapping with previous or next most<br />
recently viewed workspace similar to how many window managers <br />
cycle windows with alt tab.<br />
<br />
In [http://www.n-sch.de/hdocs/xmonad-contrib darcs xmonad-contrib] (will release as 0.9): Layout.IndependentScreens<br />
simulates dwm style workspaces per screen. For spatial navigation more <br />
general than Plane, i.e. four 3x3 grids of workspaces, see <br />
Actions.WorkspaceCursors.<br />
<br />
=== Skipping the Scratchpad workspace while using CycleWS ===<br />
The Util.Scratchpad module provides a configurable floating terminal that is easily shifted to the current workspace or banished to its own "SP" workspace. Most people want the "SP" tag ignored during workspace navigation. (Note that in xmonad newer than 0.8.*<br />
the scratchpad workspace has been renamed to "NSP".)<br />
<br />
Here's one way to do that with Actions.CycleWS, ready to be customized, for example to use HiddenEmptyWSs instead of HiddenNonEmptyWSs, etc.<br />
<br />
Note that <hask>notSP</hask> is defined in the where clause of this example. It is<br />
just another name for <hask>(return $ ("SP" /=) . W.tag) :: X (WindowSpace -> Bool)</hask><br />
Likewise, for <hask>getSortByIndexNoSP</hask>, look in where clause.<br />
<br />
<haskell><br />
--<br />
import qualified XMonad.StackSet as W<br />
import XMonad.Util.EZConfig -- optional, but helpful<br />
import Xmonad.Actions.CycleWS<br />
import XMonad.Util.Scratchpad<br />
import XMonad.Util.WorkspaceCompare<br />
<br />
modKey = mod4Mask<br />
<br />
-- other keybindings [ ]<br />
++<br />
-- focus /any/ workspace except scratchpad, even visible<br />
[ ((modKey, xK_Right ), moveTo Next (WSIs notSP))<br />
, ((modKey, xK_Left ), moveTo Prev (WSIs notSP))<br />
<br />
-- move window to /any/ workspace except scratchpad<br />
, ((modKey .|. shiftMask, xK_Right ), shiftTo Next (WSIs notSP))<br />
, ((modKey .|. shiftMask, xK_Left ), shiftTo Prev (WSIs notSP))<br />
<br />
-- focus HiddenNonEmpty wss except scratchpad<br />
, ((modKey .|. controlMask , xK_Right),<br />
windows . W.greedyView =<< findWorkspace getSortByIndexNoSP Next HiddenNonEmptyWS 1)<br />
, ((modKey .|. controlMask , xK_Left),<br />
windows . W.greedyView =<< findWorkspace getSortByIndexNoSP Prev HiddenNonEmptyWS 1)<br />
<br />
-- move window to HiddenNonEmpty wss except scratchpad <br />
, ((modKey .|. shiftMask, xK_Right),<br />
windows . W.shift =<< findWorkspace getSortByIndexNoSP Next HiddenNonEmptyWS 1)<br />
, ((modKey .|. shiftMask, xK_Left),<br />
windows . W.shift =<< findWorkspace getSortByIndexNoSP Prev HiddenNonEmptyWS 1)<br />
<br />
-- move window to and focus HiddenNonEmpty wss except scratchpad<br />
, ((modKey .|. controlMask .|. shiftMask, xK_Right), shiftAndView' Next)<br />
, ((modKey .|. controlMask .|. shiftMask, xK_Left), shiftAndView' Prev)<br />
<br />
-- toggle to the workspace displayed previously, except scratchpad**<br />
, ((modKey, xK_slash myToggle)<br />
]<br />
<br />
-- Make sure to put any where clause after your last list of key bindings*<br />
where notSP = (return $ ("SP" /=) . W.tag) :: X (WindowSpace -> Bool)<br />
-- | any workspace but scratchpad<br />
shiftAndView dir = findWorkspace getSortByIndex dir (WSIs notSP) 1<br />
>>= \t -> (windows . W.shift $ t) >> (windows . W.greedyView $ t)<br />
-- | hidden, non-empty workspaces less scratchpad<br />
shiftAndView' dir = findWorkspace getSortByIndexNoSP dir HiddenNonEmptyWS 1<br />
>>= \t -> (windows . W.shift $ t) >> (windows . W.greedyView $ t)<br />
getSortByIndexNoSP =<br />
fmap (.scratchpadFilterOutWorkspace) getSortByIndex<br />
-- | toggle any workspace but scratchpad<br />
myToggle = windows $ W.view =<< W.tag . head . filter <br />
((\x -> x /= "NSP" && x /= "SP") . W.tag) . W.hidden<br />
<br />
<br />
-- *For example, you could not (++) another list here<br />
<br />
-- ------------------------------------------------------------------------<br />
-- If notSP or some variant of the shiftAndView functions isn't needed, but<br />
-- you do want to use shiftTo or moveTo, delete notSP and use a version of:<br />
-- ((modKey, xK_Right ), moveTo Next . WSIs . return $ ("SP" /=) . W.tag)<br />
</haskell><br />
Also of course, the where definitions, or X () actions bound here can be moved out to<br />
top level definitions if you want to use them repeatedly.<br />
<br />
<nowiki>**</nowiki>This is another way to toggle workspaces except scratchpad.<br />
<br />
<haskell><br />
--<br />
import Control.Monad<br />
<br />
-- toggle to the workspace displayed previously, except scratchpad<br />
, ((modKey, xK_slash toggleSkip ["NSP"])<br />
<br />
-- | toggle any workspace but scratchpad<br />
toggleSkip :: [WorkspaceId] -> X ()<br />
toggleSkip skips = do<br />
hs <- gets (flip skipTags skips . W.hidden . windowset)<br />
unless (null hs) (windows . W.view . W.tag $ head hs)<br />
--<br />
</haskell><br />
<br />
===Do not show scratchpad workspace in status bar or dynamicLog===<br />
You can also use <hask>fmap (.scratchpadFilterOutWorkspace)</hask> on a ppSort<br />
in your logHook.<br />
<haskell><br />
, logHook = dynamicLogWithPP defaultPP {<br />
ppSort = fmap (.scratchpadFilterOutWorkspace) $ ppSort defaultPP<br />
</haskell><br />
or<br />
<haskell><br />
import XMonad.Util.WorkspaceCompare<br />
<br />
-- etc<br />
, logHook = dynamicLogWithPP defaultPP {<br />
ppSort = fmap (.scratchpadFilterOutWorkspace) getSortByTag<br />
--<br />
</haskell><br />
<br />
=== Doing things on another workspace while focus stays on current ===<br />
With darcs xmonad (will release as 0.9) -- see also<br />
[http://code.haskell.org/XMonadContrib/XMonad/Actions/OnScreen.hs Actions.OnScreen] and <code>onScr</code> below.<br />
<br />
You can use something like the following in your keybindings for a two<br />
monitor setup (or two screens via LayoutScreens.) <br />
<haskell><br />
import qualified XMonad.StackSet as W<br />
<br />
-- c here is your XConfig l, aka defaultConfig { ....<br />
, ((modMask c, xK_v), withOtherOf2 W.view) -- focus other visible screen<br />
, ((modMask c, xK_g), withOtherOf2 W.greedyView) -- swap workspaces on screens<br />
, ((modMask c, xK_f), withOtherOf2 W.shift) -- move current window to other screen<br />
, ((modMask c, xK_u), onOtherOf2 W.focusUp) -- focus up on other screen<br />
]<br />
<br />
withOtherOf2 :: (WorkspaceId -> WindowSet -> WindowSet) -> X ()<br />
withOtherOf2 fn = do<br />
tag <- join . gets $ screenWorkspace . (1 -) . W.screen . W.current . windowset<br />
flip whenJust (windows . fn) tag<br />
<br />
onOtherOf2 :: (WindowSet -> WindowSet) -> X ()<br />
onOtherOf2 fn' = do<br />
wset <- gets windowset<br />
other <- screenWorkspace . (1 -) . W.screen . W.current $ wset<br />
windows $ W.view (W.currentTag wset) . fn' . maybe id W.view other<br />
</haskell><br />
<br />
More generally<br />
<haskell><br />
onWorkspace :: WorkspaceId -> (WindowSet -> WindowSet)<br />
-> (WindowSet -> WindowSet)<br />
onWorkspace wsid f w = W.view (W.currentTag w) . f . W.view wsid $ w<br />
<br />
-- silly usage example: focus master on workspace "3"<br />
, ((modMask c, xK_F12), windows $ onWorkspace "3" W.focusMaster)<br />
</haskell><br />
<br />
==== Quick and dirty OnScreen helper ====<br />
With darcs xmonad (will release as 0.9) see also<br />
[http://code.haskell.org/XMonadContrib/XMonad/Actions/OnScreen.hs Actions.OnScreen]<br />
<br />
<haskell><br />
-- For example, to focus a specific workspace on the second screen<br />
-- use something like this in startupHook or a key binding:<br />
-- If the requested screen doesn't exist, the action is done on the<br />
-- current screen instead.<br />
<br />
import qualified XMonad.StackSet as W<br />
-- skipped<br />
, startupHook = onScr 1 W.greedyView "web" <br />
-- skipped<br />
<br />
onScr :: ScreenId -> (WorkspaceId -> WindowSet -> WindowSet) -> WorkspaceId -> X ()<br />
onScr n f i = screenWorkspace n >>= \sn -> windows (f i . maybe id W.view sn)<br />
</haskell><br />
<br />
== Arranging Windows aka Layouts ==<br />
=== Binding keys to a specific layout ===<br />
<br />
Sometimes people want to bind a key to a particular layout, rather<br />
than having to cycle through the available layouts:<br />
<br />
You can do this using the JumpToLayout message from the<br />
[http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-LayoutCombinators.html XMonad.Layout.LayoutCombinators] extension module. For example:<br />
<br />
<haskell><br />
import XMonad hiding ( (|||) ) -- don't use the normal ||| operator<br />
import XMonad.Layout.LayoutCombinators -- use the one from LayoutCombinators instead<br />
import XMonad.Util.EZConfig -- add keybindings easily<br />
<br />
main = xmonad myConfig<br />
<br />
myConfig = defaultConfig {<br />
-- <br />
layoutHook = tall ||| Mirror tall ||| Full<br />
-- <br />
} `additionalKeysP`<br />
[ ("M-<F1>", sendMessage $ JumpToLayout "Tall")<br />
, ("M-<F2>", sendMessage $ JumpToLayout "Mirror Tall")<br />
, ("M-<F3>", sendMessage $ JumpToLayout "Full") <br />
] <br />
<br />
tall = Tall 1 (3/100) (1/2)<br />
</haskell><br />
<br />
=== Docks, Monitors, Sticky Windows ===<br />
See [[#Ignoring a client (or having it sticky)]]<br />
<br />
== Misc ==<br />
=== Using local state in the config file ===<br />
<br />
See XMonad.Util.ExtensibleState for persistent custom state. (>0.9)<br />
<br />
''It's nearly always better to use ExtensibleState, but you may still find some use for IORef's:''<br />
<br />
As the xmonad config file is really just the entry point to the entire<br />
program, you can do arbitrary IO effects before running xmonad.<br />
Including initialising mutable "global" state. That state could even be<br />
made persistent , independent of xmonad's built-in persistence (by<br />
writing it to a file on mod-q).<br />
<br />
Here's an example where we store the layouts "IncMaster" value in a<br />
local mutable variable, so that we can provide a key binding that<br />
takes that value to compute an offset.<br />
<br />
<haskell><br />
import XMonad<br />
import XMonad.Util.EZConfig<br />
import Data.IORef<br />
import XMonad.Actions.FocusNth<br />
<br />
main = do<br />
offset <- newIORef 1<br />
xmonad $ defaultConfig<br />
`additionalKeys`<br />
([ ((modMask defaultConfig, xK_comma ),<br />
do io $ modifyIORef offset (\i -> max 0 (i-1))<br />
sendMessage (IncMasterN (-1))<br />
)<br />
<br />
, ((modMask defaultConfig, xK_period ),<br />
do io $ modifyIORef offset (+1)<br />
sendMessage (IncMasterN 1)<br />
) -- %! Expand the master area<br />
<br />
] ++ [((modMask defaultConfig .|. shiftMask, k), do<br />
n <- io $ readIORef offset<br />
focusNth (i+n))<br />
| (i, k) <- zip [0 .. 8] [xK_1 ..]]<br />
)<br />
</haskell><br />
<br />
Note IORef is allocated at startup.<br />
<br />
=== Sharing a configuration across different hosts ===<br />
<br />
It is possible to have different parts of the configuration file vary from one host to another, without needing a different config file for each host. Here is an example from my configuration file:<br />
<haskell><br />
import System.Posix.Unistd<br />
<br />
-- etc<br />
<br />
main = do<br />
host <- fmap nodeName getSystemID<br />
-- or -- host <- nodeName `fmap` getSystemID<br />
-- or -- host <- nodeName <$> getSystemID -- import Control.Applicative<br />
xmonad $ defaultConfig<br />
{ terminal = "rxvt"<br />
, modMask = (if host === "janice" then<br />
mod1Mask .|. controlMask<br />
else<br />
mod4Mask)<br />
-- also can pass hostname to functions outside main if needed<br />
, logHook = dynamicLogWithPP $ myPP host<br />
, startupHook = whereAmI host<br />
} where -- like this:<br />
whereAmI name = spawn $ xmessage "Silly, this host is " ++ name<br />
<br />
-- and this:<br />
myPP hostname =<br />
if hostname === "janice" then dzenPP else xmobarPP<br />
</haskell><br />
<br />
=== Multi head with VMs VNC or other non standard X ===<br />
To manually split your screen if your X server doesn't deal with xinerama correctly, see the [http://xmonad.org/xmonad-docs/xmonad-contrib/XMonad-Layout-LayoutScreens.html LayoutScreens extension] or [http://ktown.kde.org/~seli/fakexinerama Fake Xinerama].<br />
<br />
Also, if you're not sure if xmonad was compiled with xinerama support, see the xinerama sections in the [[Xmonad/Frequently_asked_questions|XMonad FAQ]] to check and remedy.</div>Dmwithttps://wiki.haskell.org/Gtk2Hs/InstallationGtk2Hs/Installation2012-12-01T20:46:38Z<p>Dmwit: /* Tested Configurations */ tested on Debian</p>
<hr />
<div>These instructions are for installing everything necessary to go from a newly installed operating system to a minimal (but working) Gtk2Hs installation.<br />
<br />
== Windows ==<br />
=== Haskell Build System ===<br />
You will need at least GHC and cabal-install. The simplest way to get these is to install [http://www.haskell.org/platform/ the Haskell Platform]. You will need to add cabal-install's executable directory to your %PATH% (it will tell you which path to add in a warning after you install your first executable there). See [[#Changing Environment Variables]] for details on how to do this.<br />
<br />
=== GTK Libraries ===<br />
Download an all-in-one bundle from [http://www.gtk.org/download/win32.php the Gtk+ website]. Unpack the bundle to a path that does not have spaces in it, and add the /bin directory created by unpacking to your %PATH%. Important points:<br />
* Get an all-in-one bundle. Do not install each of the packages separately.<br />
* Do not install the bundle to a path that has spaces in it.<br />
* Do not get the 2.16 bundle.<br />
<br />
You can check that you have done everything in this step correctly by opening a command prompt and entering<br />
<nowiki>pkg-config --cflags gtk+-2.0</nowiki><br />
If you see some compiler flags that contain the path into which you have installed the binary bundle, you are okay.<br />
<br />
=== Gtk2Hs Bindings ===<br />
This step should be as easy as running<br />
<nowiki><br />
cabal update<br />
cabal install gtk2hs-buildtools<br />
cabal install gtk</nowiki><br />
After installing gtk2hs-buildtools, make sure that gtk2hsC2hs is in a directory that is on your %PATH%.<br />
=== Changing Environment Variables ===<br />
The installation process involves modifying (or, if necessary, adding) the %PATH% environment variable. This subtopic describes how to do this. The %PATH% variable is a ';'-separated list of directories.<br />
<br />
==== Command Prompt ====<br />
You can see and modify variables with echo and set:<br />
<nowiki><br />
echo %PATH%<br />
set PATH=dir1;dir2;...</nowiki><br />
<br />
==== Windows XP GUI ====<br />
* Start -> Control Panel -> System -> Advanced -> Environment Variables<br />
* In the <em>top</em> window, click "New" to add a variable or "Edit" to modify an existing one.<br />
<br />
==== Windows 7 GUI ====<br />
* Click on the Windows symbol on the bottom-left where "Start" used to be<br />
* Choose Computer -> Properties -> Advanced System Settings<br />
* In the <em>top</em> window, click "New" to add a variable or "Edit" to modify an existing one.<br />
<br />
=== Unzipping ===<br />
There are many good tools for extracting zip archives on Windows. If you don't have one already, [http://www.7-zip.org/ 7-zip] is a fine choice to install. You can extract a file with a command like<br />
<nowiki><br />
cd c:\path\to\where\you\want\to\extract\files<br />
7za x c:\path\to\file.zip</nowiki><br />
<br />
=== Installing darcs ===<br />
You can get a copy of darcs for Windows from [http://darcs.net/Binaries the official download page].<br />
<br />
== Linux ==<br />
=== Preferred Way: Via Package Manager ===<br />
You should check if your package manager already has gtk2hs, as this is the easiest and most reliable way to get everything installed. Below is a short list of package names for some distributions (feel free to add your favorite).<br />
* Debian: libghc-gtk-dev<br />
* Fedora: ghc-gtk-devel<br />
* Gentoo: available in the haskell overlay as dev-haskell/gtk<br />
<br />
=== From Source ===<br />
First install the dependencies: a Haskell build system and the Gtk+ libraries. For the build system, you need at least GHC and cabal-install; for the Gtk+ libraries you will need (the development versions of) glib, gio, cairo, pango, and gtk. The names of the appropriate packages are listed below for some distributions (feel free to add your favorite).<br />
* Debian: ghc cabal-install libglib2.0-dev libcairo2-dev libpango1.0-dev libgtk2.0-dev<br />
* Fedora: ghc-compiler cabal-install glib2-devel cairo-devel pango-devel gtk2-devel<br />
<br />
You must add cabal's executable directory to your $PATH next. By default, this directory is $HOME/.cabal/bin. To do this locally for a single shell, write<br />
<nowiki>export PATH=$HOME/.cabal/bin:$PATH</nowiki><br />
Add a line with the same contents to your shell's rc file to make this change in all future invocations of your shell.<br />
<br />
You can now build Gtk2Hs itself, with the commands<br />
<nowiki><br />
cabal update<br />
cabal install gtk2hs-buildtools<br />
cabal install gtk</nowiki><br />
<br />
=== Installing darcs ===<br />
There are binaries available on [http://darcs.net/Binaries the official download page], or in almost all cases via your package manager as a package named darcs.<br />
<br />
== Mac ==<br />
There are one-off experience reports of varying age available at [[Gtk2Hs/Mac]]. Please write to the mailing list if you are willing to maintain good instructions (or just start editing this page!).<br />
<br />
== FreeBSD ==<br />
Gtk2Hs is available as [http://www.freshports.org/x11-toolkits/hs-gtk2hs/ hs-gtk2hs] in FreshPorts.<br />
<br />
== Appendix ==<br />
=== Supported Versions ===<br />
The most recent release of Gtk2Hs was tested on the a variety of systems. Below we offer two kinds of statistics; the second thing we give is a list of system configurations on which the minimal gtk2hs installation described above has been tested. (Please feel free to add your system configuration if you build gtk2hs.) Above that, we list the versions of each component for which some system configuration successfully built gtk2hs, with an asterisk marking those that are officially supported. Any system configuration containing officially supported versions of each component should be able to build gtk2hs successfully; please report a bug if you find this not to be true!<br />
<br />
==== Operating System ====<br />
* Windows XP*<br />
* Ubuntu 12.10*<br />
* Fedora 17*<br />
<br />
==== Gtk+ ====<br />
* 2.12*<br />
* 2.14*<br />
* 2.18*<br />
* 2.20*<br />
* 2.22*<br />
* 2.24*<br />
<br />
==== GHC ====<br />
* 7.0*<br />
* 7.2*<br />
* 7.4*<br />
* 7.6*<br />
<br />
==== Tested Configurations ====<br />
gtk-0.12.4:<br />
* Windows XP, Gtk+ 2.12, GHC 7.6<br />
* Windows XP, Gtk+ 2.14, GHC 7.6<br />
* Windows XP, Gtk+ 2.18, GHC 7.6<br />
* Windows XP, Gtk+ 2.20, GHC 7.6<br />
* Windows XP, Gtk+ 2.22, GHC 7.6<br />
* Windows XP, Gtk+ 2.24, GHC 7.6<br />
* Windows XP, Gtk+ 2.24, GHC 7.4<br />
* Windows XP, Gtk+ 2.24, GHC 7.2<br />
* Windows XP, Gtk+ 2.24, GHC 7.0<br />
* Fedora 17, Gtk+ 2.24, GHC 7.6<br />
* Debian sid, Gtk+ 2.24, GHC 7.6<br />
gtk-0.12.3:<br />
* Ubuntu 12.10, Gtk+ 2.24, GHC 7.4<br />
* Windows 7, Gtk+ ??, GHC ??<br />
<br />
=== Going Beyond Minimal: All Available Packages ===<br />
There are many packages available. The basic one installed by the above instructions are:<br />
<br />
* [http://hackage.haskell.org/package/gtk2hs-buildtools gtk2hs-buildtools]: build tools, required to build from source<br />
* [http://hackage.haskell.org/package/glib glib]: object type system and data structures<br />
* [http://hackage.haskell.org/package/gio gio]: an OS-agnostic file access API<br />
* [http://hackage.haskell.org/package/cairo cairo]: a 2D vector graphics library<br />
* [http://hackage.haskell.org/package/pango pango]: a Unicode-aware font rendering engine<br />
* [http://hackage.haskell.org/package/gtk gtk]: the base GUI library<br />
<br />
The following packages are also available:<br />
<br />
* [http://hackage.haskell.org/package/gconf gconf]: configuration database<br />
* [http://hackage.haskell.org/package/glade glade]: a library to build user interfaces from XML descriptions<br />
* [http://hackage.haskell.org/package/gstreamer gstreamer]: a multimedia streaming framework<br />
* [http://hackage.haskell.org/package/gtkglext gtkglext]: an OpenGL widget<br />
* [http://hackage.haskell.org/package/gtksourceview2 gtksourceview2]: a source-code widget<br />
* [http://hackage.haskell.org/package/soegtk soegtk]: an API providing functions for Paul Hudak's Haskell School of Expressions book<br />
* [http://hackage.haskell.org/package/svgcairo svgcairo]: writing Cairo graphics to SVG files<br />
* [http://hackage.haskell.org/package/vte vte]: a terminal widget<br />
* [http://hackage.haskell.org/package/webkit webkit]: a web-browser widget, based on Apple's webkit library<br />
<br />
The following deprecated packages are no longer supported, and are only available via darcs (see, funnily enough, [[#Getting the Latest and Greatest]] below for instructions on using this tool):<br />
<br />
* [http://www2.in.tum.de/~simona/sourceview sourceview]: version 1 of the SourceView widget<br />
* [http://www2.in.tum.de/~simona/gnomevfs gnomevfs]: Gnome Virtual File System, superseded by gio<br />
* [http://www2.in.tum.de/~simona/mozembed mozembed]: a web-browser widget, superseded by webkit<br />
<br />
=== Getting the Latest and Greatest ===<br />
First follow your operating system's instructions for installing dependencies and for installing darcs. You can then get a copy of the newest code by running the command<br />
<nowiki>darcs get --lazy http://code.haskell.org/gtk2hs</nowiki><br />
On Linux, you can build all the basic packages by running<br />
<nowiki>cd gtk2hs && sh bootstrap.sh</nowiki><br />
On Windows, run cabal install in each directory by hand:<br />
<nowiki><br />
cd gtk2hs/tools<br />
cabal install<br />
cd ../glib<br />
cabal install<br />
cd ../gio<br />
cabal install<br />
cd ../cairo<br />
cabal install<br />
cd ../pango<br />
cabal install<br />
cd ../gtk<br />
cabal install</nowiki><br />
<br />
One benefit of getting the source repository is that there are demos available in each package's demo directory. For example, you can run gtk's Hello World example by:<br />
<nowiki><br />
cd gtk2hs/gtk/demo/hello<br />
ghc World<br />
./World</nowiki><br />
There are also Makefiles in each directory if you have a suitable make installation.<br />
<br />
=== Getting the Oldest and Moldiest ===<br />
There are bundles of some very old versions available [http://sourceforge.net/project/showfiles.php?group_id=49207&package_id=42440 on the SourceForge downloads page]. For newer versions, follow the instructions for installing darcs for your operating system. You can then get version x.y.z with the command<br />
<nowiki>darcs get -t x.y.z http://code.haskell.org/gtk2hs</nowiki><br />
<br />
=== Troubleshooting ===<br />
==== glade.h is not found ====<br />
The symptom is this error message:<br />
<nowiki>gtk2hsC2hs.exe : glade/glade.h: File does not exist</nowiki><br />
Probably this means that instead of installing the GTK/Glade bundle you installed them separately. The Gtk+/glade bundle comes with the "include/libglade-2.0" containing a number of header files. For some reason this directory is not included in stand-alone Gtk+ and glade installers. Install the bundle and add this directory to the INCLUDE environment variable.<br />
<br />
==== cabal cannot find gtk2hsC2hs ====<br />
Either you forgot to install gtk2hs-buildtools, or you have not yet put cabal's executable directory in your path. Default directories are<br />
* Linux: $HOME/.cabal/bin<br />
* Windows XP: %USERPROFILE%\Application Data\cabal\bin<br />
* Windows 7: %USERPROFILE%\AppData\Roaming\cabal\bin<br />
See [[#Changing Environment Variables]] for instructions on changing environment variables on Windows.<br />
<br />
==== "Spinner" errors while trying to compile the "notebook" demo ====<br />
The symptom is errors like the following:<br />
<nowiki><br />
[1 of 1] Compiling Main ( Notebook.hs, Notebook.o )<br />
Notebook.hs:14:35:<br />
Not in scope: type constructor or class `Spinner'<br />
Notebook.hs:78:13: Not in scope: `spinnerNew'<br />
Notebook.hs:101:2: Not in scope: `spinnerStart'<br />
Notebook.hs:109:2: Not in scope: `spinnerStop'</nowiki><br />
The Spinner widget first appears in Gtk+-2.22, so this will happen if you installed an older version of Gtk+.<br />
<br />
=== Uninstalling ===<br />
Uninstallation is currently ill-supported. You can unregister packages with GHC using ghc-pkg unregister, and the installed files can be manually deleted from GHC's local directories, but cabal does not yet support automatic uninstallation.</div>Dmwithttps://wiki.haskell.org/Gtk2Hs/InstallationGtk2Hs/Installation2012-12-01T20:27:56Z<p>Dmwit: /* Going Beyond Minimal: All Available Packages */ change some fancy quotes to boring quotes</p>
<hr />
<div>These instructions are for installing everything necessary to go from a newly installed operating system to a minimal (but working) Gtk2Hs installation.<br />
<br />
== Windows ==<br />
=== Haskell Build System ===<br />
You will need at least GHC and cabal-install. The simplest way to get these is to install [http://www.haskell.org/platform/ the Haskell Platform]. You will need to add cabal-install's executable directory to your %PATH% (it will tell you which path to add in a warning after you install your first executable there). See [[#Changing Environment Variables]] for details on how to do this.<br />
<br />
=== GTK Libraries ===<br />
Download an all-in-one bundle from [http://www.gtk.org/download/win32.php the Gtk+ website]. Unpack the bundle to a path that does not have spaces in it, and add the /bin directory created by unpacking to your %PATH%. Important points:<br />
* Get an all-in-one bundle. Do not install each of the packages separately.<br />
* Do not install the bundle to a path that has spaces in it.<br />
* Do not get the 2.16 bundle.<br />
<br />
You can check that you have done everything in this step correctly by opening a command prompt and entering<br />
<nowiki>pkg-config --cflags gtk+-2.0</nowiki><br />
If you see some compiler flags that contain the path into which you have installed the binary bundle, you are okay.<br />
<br />
=== Gtk2Hs Bindings ===<br />
This step should be as easy as running<br />
<nowiki><br />
cabal update<br />
cabal install gtk2hs-buildtools<br />
cabal install gtk</nowiki><br />
After installing gtk2hs-buildtools, make sure that gtk2hsC2hs is in a directory that is on your %PATH%.<br />
=== Changing Environment Variables ===<br />
The installation process involves modifying (or, if necessary, adding) the %PATH% environment variable. This subtopic describes how to do this. The %PATH% variable is a ';'-separated list of directories.<br />
<br />
==== Command Prompt ====<br />
You can see and modify variables with echo and set:<br />
<nowiki><br />
echo %PATH%<br />
set PATH=dir1;dir2;...</nowiki><br />
<br />
==== Windows XP GUI ====<br />
* Start -> Control Panel -> System -> Advanced -> Environment Variables<br />
* In the <em>top</em> window, click "New" to add a variable or "Edit" to modify an existing one.<br />
<br />
==== Windows 7 GUI ====<br />
* Click on the Windows symbol on the bottom-left where "Start" used to be<br />
* Choose Computer -> Properties -> Advanced System Settings<br />
* In the <em>top</em> window, click "New" to add a variable or "Edit" to modify an existing one.<br />
<br />
=== Unzipping ===<br />
There are many good tools for extracting zip archives on Windows. If you don't have one already, [http://www.7-zip.org/ 7-zip] is a fine choice to install. You can extract a file with a command like<br />
<nowiki><br />
cd c:\path\to\where\you\want\to\extract\files<br />
7za x c:\path\to\file.zip</nowiki><br />
<br />
=== Installing darcs ===<br />
You can get a copy of darcs for Windows from [http://darcs.net/Binaries the official download page].<br />
<br />
== Linux ==<br />
=== Preferred Way: Via Package Manager ===<br />
You should check if your package manager already has gtk2hs, as this is the easiest and most reliable way to get everything installed. Below is a short list of package names for some distributions (feel free to add your favorite).<br />
* Debian: libghc-gtk-dev<br />
* Fedora: ghc-gtk-devel<br />
* Gentoo: available in the haskell overlay as dev-haskell/gtk<br />
<br />
=== From Source ===<br />
First install the dependencies: a Haskell build system and the Gtk+ libraries. For the build system, you need at least GHC and cabal-install; for the Gtk+ libraries you will need (the development versions of) glib, gio, cairo, pango, and gtk. The names of the appropriate packages are listed below for some distributions (feel free to add your favorite).<br />
* Debian: ghc cabal-install libglib2.0-dev libcairo2-dev libpango1.0-dev libgtk2.0-dev<br />
* Fedora: ghc-compiler cabal-install glib2-devel cairo-devel pango-devel gtk2-devel<br />
<br />
You must add cabal's executable directory to your $PATH next. By default, this directory is $HOME/.cabal/bin. To do this locally for a single shell, write<br />
<nowiki>export PATH=$HOME/.cabal/bin:$PATH</nowiki><br />
Add a line with the same contents to your shell's rc file to make this change in all future invocations of your shell.<br />
<br />
You can now build Gtk2Hs itself, with the commands<br />
<nowiki><br />
cabal update<br />
cabal install gtk2hs-buildtools<br />
cabal install gtk</nowiki><br />
<br />
=== Installing darcs ===<br />
There are binaries available on [http://darcs.net/Binaries the official download page], or in almost all cases via your package manager as a package named darcs.<br />
<br />
== Mac ==<br />
There are one-off experience reports of varying age available at [[Gtk2Hs/Mac]]. Please write to the mailing list if you are willing to maintain good instructions (or just start editing this page!).<br />
<br />
== FreeBSD ==<br />
Gtk2Hs is available as [http://www.freshports.org/x11-toolkits/hs-gtk2hs/ hs-gtk2hs] in FreshPorts.<br />
<br />
== Appendix ==<br />
=== Supported Versions ===<br />
The most recent release of Gtk2Hs was tested on the a variety of systems. Below we offer two kinds of statistics; the second thing we give is a list of system configurations on which the minimal gtk2hs installation described above has been tested. (Please feel free to add your system configuration if you build gtk2hs.) Above that, we list the versions of each component for which some system configuration successfully built gtk2hs, with an asterisk marking those that are officially supported. Any system configuration containing officially supported versions of each component should be able to build gtk2hs successfully; please report a bug if you find this not to be true!<br />
<br />
==== Operating System ====<br />
* Windows XP*<br />
* Ubuntu 12.10*<br />
* Fedora 17*<br />
<br />
==== Gtk+ ====<br />
* 2.12*<br />
* 2.14*<br />
* 2.18*<br />
* 2.20*<br />
* 2.22*<br />
* 2.24*<br />
<br />
==== GHC ====<br />
* 7.0*<br />
* 7.2*<br />
* 7.4*<br />
* 7.6*<br />
<br />
==== Tested Configurations ====<br />
gtk-0.12.4:<br />
* Windows XP, Gtk+ 2.12, GHC 7.6<br />
* Windows XP, Gtk+ 2.14, GHC 7.6<br />
* Windows XP, Gtk+ 2.18, GHC 7.6<br />
* Windows XP, Gtk+ 2.20, GHC 7.6<br />
* Windows XP, Gtk+ 2.22, GHC 7.6<br />
* Windows XP, Gtk+ 2.24, GHC 7.6<br />
* Windows XP, Gtk+ 2.24, GHC 7.4<br />
* Windows XP, Gtk+ 2.24, GHC 7.2<br />
* Windows XP, Gtk+ 2.24, GHC 7.0<br />
* Fedora 17, Gtk+ 2.24, GHC 7.6<br />
gtk-0.12.3:<br />
* Ubuntu 12.10, Gtk+ 2.24, GHC 7.4<br />
* Windows 7, Gtk+ ??, GHC ??<br />
<br />
=== Going Beyond Minimal: All Available Packages ===<br />
There are many packages available. The basic one installed by the above instructions are:<br />
<br />
* [http://hackage.haskell.org/package/gtk2hs-buildtools gtk2hs-buildtools]: build tools, required to build from source<br />
* [http://hackage.haskell.org/package/glib glib]: object type system and data structures<br />
* [http://hackage.haskell.org/package/gio gio]: an OS-agnostic file access API<br />
* [http://hackage.haskell.org/package/cairo cairo]: a 2D vector graphics library<br />
* [http://hackage.haskell.org/package/pango pango]: a Unicode-aware font rendering engine<br />
* [http://hackage.haskell.org/package/gtk gtk]: the base GUI library<br />
<br />
The following packages are also available:<br />
<br />
* [http://hackage.haskell.org/package/gconf gconf]: configuration database<br />
* [http://hackage.haskell.org/package/glade glade]: a library to build user interfaces from XML descriptions<br />
* [http://hackage.haskell.org/package/gstreamer gstreamer]: a multimedia streaming framework<br />
* [http://hackage.haskell.org/package/gtkglext gtkglext]: an OpenGL widget<br />
* [http://hackage.haskell.org/package/gtksourceview2 gtksourceview2]: a source-code widget<br />
* [http://hackage.haskell.org/package/soegtk soegtk]: an API providing functions for Paul Hudak's Haskell School of Expressions book<br />
* [http://hackage.haskell.org/package/svgcairo svgcairo]: writing Cairo graphics to SVG files<br />
* [http://hackage.haskell.org/package/vte vte]: a terminal widget<br />
* [http://hackage.haskell.org/package/webkit webkit]: a web-browser widget, based on Apple's webkit library<br />
<br />
The following deprecated packages are no longer supported, and are only available via darcs (see, funnily enough, [[#Getting the Latest and Greatest]] below for instructions on using this tool):<br />
<br />
* [http://www2.in.tum.de/~simona/sourceview sourceview]: version 1 of the SourceView widget<br />
* [http://www2.in.tum.de/~simona/gnomevfs gnomevfs]: Gnome Virtual File System, superseded by gio<br />
* [http://www2.in.tum.de/~simona/mozembed mozembed]: a web-browser widget, superseded by webkit<br />
<br />
=== Getting the Latest and Greatest ===<br />
First follow your operating system's instructions for installing dependencies and for installing darcs. You can then get a copy of the newest code by running the command<br />
<nowiki>darcs get --lazy http://code.haskell.org/gtk2hs</nowiki><br />
On Linux, you can build all the basic packages by running<br />
<nowiki>cd gtk2hs && sh bootstrap.sh</nowiki><br />
On Windows, run cabal install in each directory by hand:<br />
<nowiki><br />
cd gtk2hs/tools<br />
cabal install<br />
cd ../glib<br />
cabal install<br />
cd ../gio<br />
cabal install<br />
cd ../cairo<br />
cabal install<br />
cd ../pango<br />
cabal install<br />
cd ../gtk<br />
cabal install</nowiki><br />
<br />
One benefit of getting the source repository is that there are demos available in each package's demo directory. For example, you can run gtk's Hello World example by:<br />
<nowiki><br />
cd gtk2hs/gtk/demo/hello<br />
ghc World<br />
./World</nowiki><br />
There are also Makefiles in each directory if you have a suitable make installation.<br />
<br />
=== Getting the Oldest and Moldiest ===<br />
There are bundles of some very old versions available [http://sourceforge.net/project/showfiles.php?group_id=49207&package_id=42440 on the SourceForge downloads page]. For newer versions, follow the instructions for installing darcs for your operating system. You can then get version x.y.z with the command<br />
<nowiki>darcs get -t x.y.z http://code.haskell.org/gtk2hs</nowiki><br />
<br />
=== Troubleshooting ===<br />
==== glade.h is not found ====<br />
The symptom is this error message:<br />
<nowiki>gtk2hsC2hs.exe : glade/glade.h: File does not exist</nowiki><br />
Probably this means that instead of installing the GTK/Glade bundle you installed them separately. The Gtk+/glade bundle comes with the "include/libglade-2.0" containing a number of header files. For some reason this directory is not included in stand-alone Gtk+ and glade installers. Install the bundle and add this directory to the INCLUDE environment variable.<br />
<br />
==== cabal cannot find gtk2hsC2hs ====<br />
Either you forgot to install gtk2hs-buildtools, or you have not yet put cabal's executable directory in your path. Default directories are<br />
* Linux: $HOME/.cabal/bin<br />
* Windows XP: %USERPROFILE%\Application Data\cabal\bin<br />
* Windows 7: %USERPROFILE%\AppData\Roaming\cabal\bin<br />
See [[#Changing Environment Variables]] for instructions on changing environment variables on Windows.<br />
<br />
==== "Spinner" errors while trying to compile the "notebook" demo ====<br />
The symptom is errors like the following:<br />
<nowiki><br />
[1 of 1] Compiling Main ( Notebook.hs, Notebook.o )<br />
Notebook.hs:14:35:<br />
Not in scope: type constructor or class `Spinner'<br />
Notebook.hs:78:13: Not in scope: `spinnerNew'<br />
Notebook.hs:101:2: Not in scope: `spinnerStart'<br />
Notebook.hs:109:2: Not in scope: `spinnerStop'</nowiki><br />
The Spinner widget first appears in Gtk+-2.22, so this will happen if you installed an older version of Gtk+.<br />
<br />
=== Uninstalling ===<br />
Uninstallation is currently ill-supported. You can unregister packages with GHC using ghc-pkg unregister, and the installed files can be manually deleted from GHC's local directories, but cabal does not yet support automatic uninstallation.</div>Dmwithttps://wiki.haskell.org/Gtk2Hs/WindowsGtk2Hs/Windows2012-12-01T20:20:40Z<p>Dmwit: please don't use this page any more</p>
<hr />
<div><span style="color:red">Please read and update [[Gtk2Hs/Installation]] instead.</span><br />
<br />
== Windows 7 32 bit ==<br />
<br />
=== Changing Environment Variables ===<br />
<br />
This installation process involves adding/modifying environment variables. The rest of this subtopic shows you how to do that in Windows.<br />
* Using the Environment Variable GUI<br />
** Click to the Windows symbol on the bottom-left where "Start" used to be<br />
** Right-Click on "Computer", choose "Properties" and click the link for "Advanced System Settings"<br />
** In the *top* window, Click "New" add a variable or click "Edit" to modify an existing one.<br />
** The variable should be a ';' seperated list of directories.<br />
* At the DOS prompt<br />
** To see the current value of variable VAR:<br />
> echo %VAR%<br />
** To modify variable VAR:<br />
> set VAR=%VAR%;dir1;dir2 ...<br />
** To create variable VAR:<br />
> set VAR=dir1;dir2....<br />
<br />
=== Install Haskell Platform and MingW ===<br />
* Install the [http://hackage.haskell.org/platform/windows.html Haskell Platform] for Windows.<br />
* Optional : Install [http://mingw.org MinGW] as per the instructions on their web site. Also install MSYS and mingw-make. A version of MinGW does come with Haskell Platform but excludes MSYS and 'make'.<br />
=== Install libxml ===<br />
* Download and unzip the latest libxml2 and libxml2-dev archives from [http://ftp.gnome.org/pub/GNOME/binaries/win32/dependencies/ Gnome]. <br />
* To the PKG_CONFIG_PATH environment variable add the 'pkgconfig' directory in libxml2-dev\lib.<br />
* To the INCLUDE environment variable add the path to the 'include' directory from libxml2-dev.<br />
<br />
=== Install the GTK/Glade bundle ===<br />
* Download and install the [http://ftp.gnome.org/pub/GNOME/binaries/win32/glade3/3.6/glade3-3.6.7-with-GTK+.exe bundled GTK and Glade binary].<br />
* To the PKG_CONFIG_PATH environment variable add the 'pkgconfig' directory. The default path should be "C:\Program Files\Gtk+\lib\pkgconfig".<br />
* To the INCLUDE environment variable add the 'libglade-2.0' directory. The default path should be "C:\Program Files\Gtk+\include\libglade-2.0".<br />
=== Install the Haskell bindings ===<br />
* At the DOS prompt run 'cabal install gtk2hs-buildtools'. <br />
* At the DOS prompt run 'cabal install gtk'. Make sure you have at least 1.5 GB RAM otherwise this compilation will die.<br />
* At the DOS prompt run 'cabal install glade'.<br />
<br />
== Self check ==<br />
<br />
=== Test the GTK install ===<br />
* In some appropriate temporary directory run 'cabal unpack gtk'. This downloads and unpacks the Haskell sources. <br />
** Run the demos (using mingw-make)<br />
*** If you installed MinGW then in the 'demo' directory, navigate into the 'hello' directory and run mingw32-make.exe. Now run the executable that was created.<br />
** Run the demos (manual compilation)<br />
*** In the 'demo' directory, navigate into the 'hello' directory and run 'ghc --make World.hs -o helloworld.exe'. Now run the executable that was created.<br />
=== Test the Glade install ===<br />
* In some appropriate temporary directory run 'cabal unpack glade'. This downloads and unpacks the Haskell sources. <br />
** Run the demos (using mingw-make)<br />
*** If you installed MinGW then in the 'demo' directory, navigate into the 'gladetest' directory and run mingw32-make.exe. Now run the executable that was created.<br />
** Run the demos (manual compilation)<br />
*** In the 'demo' directory, navigate into the 'gladetest' directory and run 'ghc --make GladeTest.hs -o gladetest.exe'. Now run the executable that was created.<br />
<br />
== Common Errors ==<br />
* Glade.h is not found<br />
gtk2hsC2hs.exe : glade/glade.h: File does not exist<br />
Probably instead of installing the GTK/Glade bundle you installed them seperately. The GTK/Glade bundle comes with the "include/libglade-2.0" containing a number of header files. For some reason this directory is not included in stand-alone GTK and Glade installers. Install the bundle and add this directory to the INCLUDE environment variable.<br />
* Cabal cannot find gtk2hsC2hs.<br />
Please install gtk2hs-buildtools' first and check <br />
that the installdirectory is in your PATH (e.g. HOME/.cabal/bin). <br />
cabal: Error: some packages failed to install<br />
Somehow the path to the cabal bin directory has been lost. To the PATH environment variable re-add the cabal bin directory. The default path should be "%USERPROFILE%\AppData\Roaming\cabal\bin".<br />
* Spinner error with the 'notebook' demo<br />
Running the 'notebook' demo in the GTK install gives:<br />
[1 of 1] Compiling Main ( Notebook.hs, Notebook.o )<br />
Notebook.hs:14:35:<br />
Not in scope: type constructor or class `Spinner'<br />
Notebook.hs:78:13: Not in scope: `spinnerNew'<br />
Notebook.hs:101:2: Not in scope: `spinnerStart'<br />
Notebook.hs:109:2: Not in scope: `spinnerStop'<br />
mingw32-make: *** [notebook] Error 1<br />
This happens because this demo uses the new Spinner widget in GTK 2.22. Since this is not available in GTK 2.16 you get this error.</div>Dmwithttps://wiki.haskell.org/Gtk2Hs/LinuxGtk2Hs/Linux2012-12-01T20:20:15Z<p>Dmwit: don't use this page any more, please</p>
<hr />
<div><span style="color:red">Please read and update [[Gtk2Hs/Installation]] instead.</span><br />
<br />
== Ubuntu ==<br />
<br />
Installing gtk2hs on Ubuntu is easy. First, install the dependencies<br />
<br />
sudo apt-get install libgtk2.0-dev libpango1.0-dev libglib2.0-dev libcairo2-dev<br />
<br />
and then install gtk2hs<br />
<br />
cabal install gtk2hs-buildtools<br />
cabal install gtk</div>Dmwithttps://wiki.haskell.org/Gtk2HsGtk2Hs2012-12-01T20:16:36Z<p>Dmwit: delete outdated links + update some of the information</p>
<hr />
<div>[[Category:User interfaces]]<br />
== What is it? ==<br />
<br />
Gtk2Hs is a Haskell binding to Gtk+ 2.x.<br />
Using it, one can write Gtk+ based applications with GHC.<br />
<br />
== Homepage ==<br />
<br />
http://projects.haskell.org/gtk2hs/<br />
<br />
== Tutorials and Demos ==<br />
<br />
http://www.haskell.org/haskellwiki/Gtk2Hs/Tutorials<br />
<br />
Some demonstration programs can be found at:<br />
http://code.haskell.org/gtk2hs/gio/demo/<br />
http://code.haskell.org/gtk2hs/pango/demo/<br />
http://code.haskell.org/gtk2hs/cairo/demo/<br />
http://code.haskell.org/gtk2hs/gtk/demo/<br />
<br />
== Status ==<br />
<br />
See [[Gtk2Hs/Installation#Supported_Versions]] for details on which systems should be able to build Gtk2Hs and which are known to be able to build Gtk2Hs.<br />
<br />
== Installation Notes ==<br />
<br />
See [[Gtk2Hs/Installation]].<br />
<br />
== Demos ==<br />
<br />
=== OpenGL and Gtk2Hs ===<br />
<br />
[[Gtk2Hs/Demos/GtkGLext/hello.hs]]<br />
<br />
[[Gtk2Hs/Demos/GtkGLext/terrain.hs]] requires [[Gtk2Hs/Demos/GtkGLext/terrain.xpm]]<br />
<br />
==FAQs==<br />
These are links to FAQS on the main site.<br />
*[http://haskell.org/gtk2hs/archives/2005/06/23/hiding-the-console-on-windows/#more-26 Hiding the console on windows]<br />
*[http://haskell.org/gtk2hs/development/#darcs Checkout instructions]. Also see [[Darcs]]<br />
<br />
[[Category:Applications]]</div>Dmwithttps://wiki.haskell.org/Gtk2Hs/InstallationGtk2Hs/Installation2012-12-01T20:09:56Z<p>Dmwit: creation, bringing in material from many other sources</p>
<hr />
<div>These instructions are for installing everything necessary to go from a newly installed operating system to a minimal (but working) Gtk2Hs installation.<br />
<br />
== Windows ==<br />
=== Haskell Build System ===<br />
You will need at least GHC and cabal-install. The simplest way to get these is to install [http://www.haskell.org/platform/ the Haskell Platform]. You will need to add cabal-install's executable directory to your %PATH% (it will tell you which path to add in a warning after you install your first executable there). See [[#Changing Environment Variables]] for details on how to do this.<br />
<br />
=== GTK Libraries ===<br />
Download an all-in-one bundle from [http://www.gtk.org/download/win32.php the Gtk+ website]. Unpack the bundle to a path that does not have spaces in it, and add the /bin directory created by unpacking to your %PATH%. Important points:<br />
* Get an all-in-one bundle. Do not install each of the packages separately.<br />
* Do not install the bundle to a path that has spaces in it.<br />
* Do not get the 2.16 bundle.<br />
<br />
You can check that you have done everything in this step correctly by opening a command prompt and entering<br />
<nowiki>pkg-config --cflags gtk+-2.0</nowiki><br />
If you see some compiler flags that contain the path into which you have installed the binary bundle, you are okay.<br />
<br />
=== Gtk2Hs Bindings ===<br />
This step should be as easy as running<br />
<nowiki><br />
cabal update<br />
cabal install gtk2hs-buildtools<br />
cabal install gtk</nowiki><br />
After installing gtk2hs-buildtools, make sure that gtk2hsC2hs is in a directory that is on your %PATH%.<br />
=== Changing Environment Variables ===<br />
The installation process involves modifying (or, if necessary, adding) the %PATH% environment variable. This subtopic describes how to do this. The %PATH% variable is a ';'-separated list of directories.<br />
<br />
==== Command Prompt ====<br />
You can see and modify variables with echo and set:<br />
<nowiki><br />
echo %PATH%<br />
set PATH=dir1;dir2;...</nowiki><br />
<br />
==== Windows XP GUI ====<br />
* Start -> Control Panel -> System -> Advanced -> Environment Variables<br />
* In the <em>top</em> window, click "New" to add a variable or "Edit" to modify an existing one.<br />
<br />
==== Windows 7 GUI ====<br />
* Click on the Windows symbol on the bottom-left where "Start" used to be<br />
* Choose Computer -> Properties -> Advanced System Settings<br />
* In the <em>top</em> window, click "New" to add a variable or "Edit" to modify an existing one.<br />
<br />
=== Unzipping ===<br />
There are many good tools for extracting zip archives on Windows. If you don't have one already, [http://www.7-zip.org/ 7-zip] is a fine choice to install. You can extract a file with a command like<br />
<nowiki><br />
cd c:\path\to\where\you\want\to\extract\files<br />
7za x c:\path\to\file.zip</nowiki><br />
<br />
=== Installing darcs ===<br />
You can get a copy of darcs for Windows from [http://darcs.net/Binaries the official download page].<br />
<br />
== Linux ==<br />
=== Preferred Way: Via Package Manager ===<br />
You should check if your package manager already has gtk2hs, as this is the easiest and most reliable way to get everything installed. Below is a short list of package names for some distributions (feel free to add your favorite).<br />
* Debian: libghc-gtk-dev<br />
* Fedora: ghc-gtk-devel<br />
* Gentoo: available in the haskell overlay as dev-haskell/gtk<br />
<br />
=== From Source ===<br />
First install the dependencies: a Haskell build system and the Gtk+ libraries. For the build system, you need at least GHC and cabal-install; for the Gtk+ libraries you will need (the development versions of) glib, gio, cairo, pango, and gtk. The names of the appropriate packages are listed below for some distributions (feel free to add your favorite).<br />
* Debian: ghc cabal-install libglib2.0-dev libcairo2-dev libpango1.0-dev libgtk2.0-dev<br />
* Fedora: ghc-compiler cabal-install glib2-devel cairo-devel pango-devel gtk2-devel<br />
<br />
You must add cabal's executable directory to your $PATH next. By default, this directory is $HOME/.cabal/bin. To do this locally for a single shell, write<br />
<nowiki>export PATH=$HOME/.cabal/bin:$PATH</nowiki><br />
Add a line with the same contents to your shell's rc file to make this change in all future invocations of your shell.<br />
<br />
You can now build Gtk2Hs itself, with the commands<br />
<nowiki><br />
cabal update<br />
cabal install gtk2hs-buildtools<br />
cabal install gtk</nowiki><br />
<br />
=== Installing darcs ===<br />
There are binaries available on [http://darcs.net/Binaries the official download page], or in almost all cases via your package manager as a package named darcs.<br />
<br />
== Mac ==<br />
There are one-off experience reports of varying age available at [[Gtk2Hs/Mac]]. Please write to the mailing list if you are willing to maintain good instructions (or just start editing this page!).<br />
<br />
== FreeBSD ==<br />
Gtk2Hs is available as [http://www.freshports.org/x11-toolkits/hs-gtk2hs/ hs-gtk2hs] in FreshPorts.<br />
<br />
== Appendix ==<br />
=== Supported Versions ===<br />
The most recent release of Gtk2Hs was tested on the a variety of systems. Below we offer two kinds of statistics; the second thing we give is a list of system configurations on which the minimal gtk2hs installation described above has been tested. (Please feel free to add your system configuration if you build gtk2hs.) Above that, we list the versions of each component for which some system configuration successfully built gtk2hs, with an asterisk marking those that are officially supported. Any system configuration containing officially supported versions of each component should be able to build gtk2hs successfully; please report a bug if you find this not to be true!<br />
<br />
==== Operating System ====<br />
* Windows XP*<br />
* Ubuntu 12.10*<br />
* Fedora 17*<br />
<br />
==== Gtk+ ====<br />
* 2.12*<br />
* 2.14*<br />
* 2.18*<br />
* 2.20*<br />
* 2.22*<br />
* 2.24*<br />
<br />
==== GHC ====<br />
* 7.0*<br />
* 7.2*<br />
* 7.4*<br />
* 7.6*<br />
<br />
==== Tested Configurations ====<br />
gtk-0.12.4:<br />
* Windows XP, Gtk+ 2.12, GHC 7.6<br />
* Windows XP, Gtk+ 2.14, GHC 7.6<br />
* Windows XP, Gtk+ 2.18, GHC 7.6<br />
* Windows XP, Gtk+ 2.20, GHC 7.6<br />
* Windows XP, Gtk+ 2.22, GHC 7.6<br />
* Windows XP, Gtk+ 2.24, GHC 7.6<br />
* Windows XP, Gtk+ 2.24, GHC 7.4<br />
* Windows XP, Gtk+ 2.24, GHC 7.2<br />
* Windows XP, Gtk+ 2.24, GHC 7.0<br />
* Fedora 17, Gtk+ 2.24, GHC 7.6<br />
gtk-0.12.3:<br />
* Ubuntu 12.10, Gtk+ 2.24, GHC 7.4<br />
* Windows 7, Gtk+ ??, GHC ??<br />
<br />
=== Going Beyond Minimal: All Available Packages ===<br />
There are many packages available. The basic one installed by the above instructions are:<br />
<br />
* [http://hackage.haskell.org/package/gtk2hs-buildtools gtk2hs-buildtools]: build tools, required to build from source<br />
* [http://hackage.haskell.org/package/glib glib]: object type system and data structures<br />
* [http://hackage.haskell.org/package/gio gio]: an OS-agnostic file access API<br />
* [http://hackage.haskell.org/package/cairo cairo]: a 2D vector graphics library<br />
* [http://hackage.haskell.org/package/pango pango]: a Unicode-aware font rendering engine<br />
* [http://hackage.haskell.org/package/gtk gtk]: the base GUI library<br />
<br />
The following packages are also available:<br />
<br />
* [http://hackage.haskell.org/package/gconf gconf]: configuration database<br />
* [http://hackage.haskell.org/package/glade glade]: a library to build user interfaces from XML descriptions<br />
* [http://hackage.haskell.org/package/gstreamer gstreamer]: a multimedia streaming framework<br />
* [http://hackage.haskell.org/package/gtkglext gtkglext]: an OpenGL widget<br />
* [http://hackage.haskell.org/package/gtksourceview2 gtksourceview2]: a source-code widget<br />
* [http://hackage.haskell.org/package/soegtk soegtk]: an API providing functions for Paul Hudak’s Haskell School of Expressions book<br />
* [http://hackage.haskell.org/package/svgcairo svgcairo]: writing Cairo graphics to SVG files<br />
* [http://hackage.haskell.org/package/vte vte]: a terminal widget<br />
* [http://hackage.haskell.org/package/webkit webkit]: a web-browser widget, based on Apple’s webkit library<br />
<br />
The following deprecated packages are no longer supported, and are only available via darcs (see, funnily enough, [[#Getting the Latest and Greatest]] below for instructions on using this tool):<br />
<br />
* [http://www2.in.tum.de/~simona/sourceview sourceview]: version 1 of the SourceView widget<br />
* [http://www2.in.tum.de/~simona/gnomevfs gnomevfs]: Gnome Virtual File System, superseded by gio<br />
* [http://www2.in.tum.de/~simona/mozembed mozembed]: a web-browser widget, superseded by webkit<br />
<br />
=== Getting the Latest and Greatest ===<br />
First follow your operating system's instructions for installing dependencies and for installing darcs. You can then get a copy of the newest code by running the command<br />
<nowiki>darcs get --lazy http://code.haskell.org/gtk2hs</nowiki><br />
On Linux, you can build all the basic packages by running<br />
<nowiki>cd gtk2hs && sh bootstrap.sh</nowiki><br />
On Windows, run cabal install in each directory by hand:<br />
<nowiki><br />
cd gtk2hs/tools<br />
cabal install<br />
cd ../glib<br />
cabal install<br />
cd ../gio<br />
cabal install<br />
cd ../cairo<br />
cabal install<br />
cd ../pango<br />
cabal install<br />
cd ../gtk<br />
cabal install</nowiki><br />
<br />
One benefit of getting the source repository is that there are demos available in each package's demo directory. For example, you can run gtk's Hello World example by:<br />
<nowiki><br />
cd gtk2hs/gtk/demo/hello<br />
ghc World<br />
./World</nowiki><br />
There are also Makefiles in each directory if you have a suitable make installation.<br />
<br />
=== Getting the Oldest and Moldiest ===<br />
There are bundles of some very old versions available [http://sourceforge.net/project/showfiles.php?group_id=49207&package_id=42440 on the SourceForge downloads page]. For newer versions, follow the instructions for installing darcs for your operating system. You can then get version x.y.z with the command<br />
<nowiki>darcs get -t x.y.z http://code.haskell.org/gtk2hs</nowiki><br />
<br />
=== Troubleshooting ===<br />
==== glade.h is not found ====<br />
The symptom is this error message:<br />
<nowiki>gtk2hsC2hs.exe : glade/glade.h: File does not exist</nowiki><br />
Probably this means that instead of installing the GTK/Glade bundle you installed them separately. The Gtk+/glade bundle comes with the "include/libglade-2.0" containing a number of header files. For some reason this directory is not included in stand-alone Gtk+ and glade installers. Install the bundle and add this directory to the INCLUDE environment variable.<br />
<br />
==== cabal cannot find gtk2hsC2hs ====<br />
Either you forgot to install gtk2hs-buildtools, or you have not yet put cabal's executable directory in your path. Default directories are<br />
* Linux: $HOME/.cabal/bin<br />
* Windows XP: %USERPROFILE%\Application Data\cabal\bin<br />
* Windows 7: %USERPROFILE%\AppData\Roaming\cabal\bin<br />
See [[#Changing Environment Variables]] for instructions on changing environment variables on Windows.<br />
<br />
==== "Spinner" errors while trying to compile the "notebook" demo ====<br />
The symptom is errors like the following:<br />
<nowiki><br />
[1 of 1] Compiling Main ( Notebook.hs, Notebook.o )<br />
Notebook.hs:14:35:<br />
Not in scope: type constructor or class `Spinner'<br />
Notebook.hs:78:13: Not in scope: `spinnerNew'<br />
Notebook.hs:101:2: Not in scope: `spinnerStart'<br />
Notebook.hs:109:2: Not in scope: `spinnerStop'</nowiki><br />
The Spinner widget first appears in Gtk+-2.22, so this will happen if you installed an older version of Gtk+.<br />
<br />
=== Uninstalling ===<br />
Uninstallation is currently ill-supported. You can unregister packages with GHC using ghc-pkg unregister, and the installed files can be manually deleted from GHC's local directories, but cabal does not yet support automatic uninstallation.</div>Dmwithttps://wiki.haskell.org/Xmonad/Frequently_asked_questionsXmonad/Frequently asked questions2012-11-16T15:50:29Z<p>Dmwit: /* Problems with Java applications, Applet java console */ this is fixed in darcs now, so recommend building from there</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/package/xmonad-contrib 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 flash, etc. should tile or full screen without needing any of the following edits to xmonad.hs. However, if you're here you must be having problems. Try some or all of the following hooks that worked in the past.<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>Dmwithttps://wiki.haskell.org/Xmonad/Frequently_asked_questionsXmonad/Frequently asked questions2012-10-22T20:49:15Z<p>Dmwit: /* Problems with Java applications, Applet java console */ link to the specific patch that fixes everything</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/package/xmonad-contrib 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 flash, etc. should tile or full screen without needing any of the following edits to xmonad.hs. However, if you're here you must be having problems. Try some or all of the following hooks that worked in the past.<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 />
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 />
The following workarounds also fix an issue with Java gui applications where menus are not "selectable". (Clicking on the menu item opens the dropdown list of options but you can't select one, or the menu disappears when you are looking at it.)<br />
<br />
If you are still having focus problems, even after implementing the workarounds, see also<br />
[http://code.google.com/p/xmonad/issues/detail?id=177 issue 177]; specifically, install the patch given in [http://code.google.com/p/xmonad/issues/detail?id=177#c33 comment 33]. For example:<br />
<br />
<pre><br />
darcs get http://code.haskell.org/xmonad<br />
cd xmonad<br />
darcs apply /path/to/where/you/saved/track-currently-processing-event.dpatch<br />
cabal install<br />
</pre><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>Dmwithttps://wiki.haskell.org/MonadMonad2012-09-03T22:09:14Z<p>Dmwit: /* Commutative monads */ no reason to restrict this to functions that return actions</p>
<hr />
<div>{{Standard class|Monad|module=Control.Monad|module-doc=Control-Monad|package=base}}<br />
<br />
'''''Monads''''' in Haskell can be thought of as ''composable'' computation descriptions. The essence of monad is thus ''separation'' of ''composition timeline'' from the composed computation's ''execution timeline'', as well as the ability of ''computation'' to implicitly carry extra data, as pertaining to the computation itself, in addition to its ''one'' (hence the name) output, that it '''''will produce''''' when run (or queried, or called upon). This lends monads to supplementing ''pure'' calculations with features like I/O, common environment or state, and to ''preprocessing'' of computations (simplification, optimization etc.). <br />
<br />
Each monad, or computation type, provides means, subject to '''''Monad Laws''''', to '''''(a)''''' ''create'' a description of computation action that will produce (a.k.a. "return") a given Haskell value, '''''(b)''''' somehow ''run'' a computation action description (possibly getting its output back into Haskell should the monad choose to allow it, if computations described by the monad are pure, or causing the prescribed side effects if it's not), and '''''(c)''''' ''combine'' (a.k.a. "bind") a computation action description with a ''reaction'' to it &ndash; a regular Haskell function of one argument (that will receive computation-produced value) returning another action description (using or dependent on that value, if need be) &ndash; thus creating a combined computation action description that will feed the original action's output through the reaction while automatically taking care of the particulars of the computational process itself. A monad might also define additional primitives to provide access to and/or enable manipulation of data it implicitly carries, specific to its nature.<br />
<br />
[[Image:Monads inter-dependencies 2.png|center]]<br />
<br />
Thus in Haskell, though it is a purely-functional language, side effects that '''''will be performed''''' by a computation can be dealt with and combined ''purely'' at the monad's composition time. Monads thus resemble programs in a particular [[DSL]]. While programs may describe impure effects and actions ''outside'' Haskell, they can still be combined and processed (''"assembled"'') purely, ''inside'' Haskell, creating a pure Haskell value - a computation action description that describes an impure calculation. That is how Monads in Haskell '''''separate''''' between the ''pure'' and the ''impure''. <br />
<br />
The computation doesn't have to be impure and can be pure itself as well. Then monads serve to provide the benefits of separation of concerns, and automatic creation of a computational "pipeline". Because they are very useful in practice but rather mind-twisting for the beginners, numerous tutorials that deal exclusively with monads were created (see [[Monad#Monad tutorials|monad tutorials]]).<br />
<br />
== Common monads ==<br />
Most common applications of monads include:<br />
* Representing failure using <hask>Maybe</hask> monad<br />
* Nondeterminism using <hask>List</hask> monad to represent carrying multiple values<br />
* State using <hask>State</hask> monad<br />
* Read-only environment using <hask>Reader</hask> monad<br />
* I/O using <hask>IO</hask> monad<br />
<br />
== Monad class ==<br />
<br />
Monads can be viewed as a standard programming interface to various data or control structures, which is captured by the <hask>Monad</hask> class. All common monads are members of it:<br />
<br />
<haskell><br />
class Monad m where<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
(>>) :: m a -> m b -> m b<br />
return :: a -> m a<br />
fail :: String -> m a<br />
</haskell><br />
<br />
In addition to implementing the class functions, all instances of Monad should obey the following equations, or '''''Monad Laws''''':<br />
<br />
<haskell><br />
return a >>= k = k a<br />
m >>= return = m<br />
m >>= (\x -> k x >>= h) = (m >>= k) >>= h<br />
</haskell><br />
<br />
See [[Monad laws|this intuitive explanation]] of why they should obey the Monad laws. It basically says that monad's reactions should be associative under Kleisli composition, defined as <code>(f >=> g) x = f x >>= g</code>, with <code>return</code> its left and right identity element.<br />
<br />
Any Monad can be made a [[Functor]] by defining <br />
<br />
<haskell><br />
fmap ab ma = ma >>= (return . ab)<br />
</haskell><br />
<br />
However, the Functor class is not a superclass of the Monad class. See [[Functor hierarchy proposal]].<br />
<br />
== Special notation ==<br />
<br />
In order to improve the look of code that uses monads Haskell provides a special [[syntactic sugar]] called <hask>do</hask>-notation. For example, following expression:<br />
<haskell><br />
thing1 >>= (\x -> func1 x >>= (\y -> thing2 <br />
>>= (\_ -> func2 y (\z -> return z))))<br />
</haskell><br />
which can be written more clearly by breaking it into several lines and omitting parentheses:<br />
<haskell><br />
thing1 >>= \x -><br />
func1 x >>= \y -><br />
thing2 >>= \_ -><br />
func2 y >>= \z -><br />
return z<br />
</haskell><br />
can be also written using the <hask>do</hask>-notation as follows:<br />
<haskell><br />
do<br />
x <- thing1<br />
y <- func1 x<br />
thing2<br />
z <- func2 y<br />
return z<br />
</haskell><br />
Code written using the <hask>do</hask>-notation is transformed by the compiler to ordinary expressions that use <hask>Monad</hask> class functions.<br />
<br />
When using the <hask>do</hask>-notation and a monad like <hask>State</hask> or <hask>IO</hask> programs look very much like programs written in an imperative language as each line contains a statement that can change the simulated global state of the program and optionally binds a (local) variable that can be used by the statements later in the code block.<br />
<br />
It is possible to intermix the <hask>do</hask>-notation with regular notation.<br />
<br />
More on the <hask>do</hask>-notation can be found in a section of [[Monads as computation#Do notation|Monads as computation]] and in other [[Monad#Monad tutorials|tutorials]].<br />
<br />
== Commutative monads ==<br />
'''Commutative monads''' are monads for which the order of actions makes no difference (they '''commute'''), that is when following code:<br />
<haskell><br />
do<br />
a <- actA<br />
b <- actB<br />
m a b<br />
</haskell><br />
is the same as:<br />
<haskell><br />
do<br />
b <- actB<br />
a <- actA<br />
m a b<br />
</haskell><br />
<br />
Examples of commutative include:<br />
* <hask>Reader</hask> monad<br />
* <hask>Maybe</hask> monad<br />
<br />
== Monad tutorials ==<br />
<br />
Monads are known for being deeply confusing to lots of people, so there are plenty of tutorials specifically related to monads. Each takes a different approach to Monads, and hopefully everyone will find something useful.<br />
<br />
See the [[Monad tutorials timeline]] for a comprehensive list of monad tutorials.<br />
<br />
== Monad reference guides ==<br />
<br />
An explanation of the basic Monad functions, with examples, can be found in the reference guide [http://members.chello.nl/hjgtuyl/tourdemonad.html A tour of the Haskell Monad functions], by Henk-Jan van Tuyl.<br />
<br />
== Monad research ==<br />
<br />
A collection of [[Research_papers/Monads_and_arrows|research papers]] about monads.<br />
<br />
== Monads in other languages ==<br />
<br />
Implementations of monads in other languages.<br />
<br />
* [http://programming.reddit.com/goto?id=1761q C]<br />
* [http://www-static.cc.gatech.edu/~yannis/fc++/FC++.1.5/monad.h C++], [http://www-static.cc.gatech.edu/~yannis/fc++/New1.5/lambda.html#monad doc]<br />
* [http://cml.cs.uchicago.edu/pages/cml.html CML.event] ?<br />
* [http://www.st.cs.ru.nl/papers/2010/CleanStdEnvAPI.pdf Clean] State monad<br />
* [http://clojure.googlegroups.com/web/monads.clj Clojure]<br />
* [http://cratylus.freewebspace.com/monads-in-javascript.htm JavaScript]<br />
* [http://www.ccs.neu.edu/home/dherman/browse/code/monads/JavaMonads/ Java]<br />
* [http://permalink.gmane.org/gmane.comp.lang.concatenative/1506 Joy]<br />
* [http://research.microsoft.com/~emeijer/Papers/XLinq%20XML%20Programming%20Refactored%20(The%20Return%20Of%20The%20Monoids).htm LINQ], [http://www.idealliance.org/xmlusa/05/call/xmlpapers/63.1015/.63.html#S4. more, C#, VB] (inaccessible)<br />
* [http://sleepingsquirrel.org/monads/monads.lisp Lisp]<br />
* [http://lambda-the-ultimate.org/node/1136#comment-12448 Miranda]<br />
* OCaml:<br />
** [http://www.cas.mcmaster.ca/~carette/pa_monad/ OCaml]<br />
** [https://mailman.rice.edu/pipermail/metaocaml-users-l/2005-March/000057.html more]<br />
** [http://www.pps.jussieu.fr/~beffara/darcs/pivm/caml-vm/monad.mli also]<br />
** [http://www.cas.mcmaster.ca/~carette/metamonads/ MetaOcaml]<br />
** [http://enfranchisedmind.com/blog/posts/a-monad-tutorial-for-ocaml/ A Monad Tutorial for Ocaml]<br />
* [http://sleepingsquirrel.org/monads/monads.html Perl]<br />
* [http://programming.reddit.com/info/p66e/comments Perl6 ?]<br />
* [http://logic.csci.unt.edu/tarau/research/PapersHTML/monadic.html Prolog] <br />
* Python<br />
** [http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439361 Python]<br />
** [http://www.etsimo.uniovi.es/python/pycon/papers/deferex/ here]<br />
** Twisted's [http://programming.reddit.com/info/p66e/comments/cp8eh Deferred monad]<br />
* Ruby:<br />
** [http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html Ruby]<br />
** [http://meta-meta.blogspot.com/2006/12/monads-in-ruby-part-1-identity.htmland other implementation]<br />
* Scala: <br />
** [http://scala.epfl.ch/examples/files/simpleInterpreter.html Scala]<br />
** [http://scala.epfl.ch/examples/files/callccInterpreter.html A continuation monad]<br />
* Scheme:<br />
** [http://okmij.org/ftp/Scheme/monad-in-Scheme.html Scheme]<br />
** [http://www.ccs.neu.edu/home/dherman/research/tutorials/monads-for-schemers.txt also]<br />
* [http://wiki.tcl.tk/13844 Tcl]<br />
* [http://okmij.org/ftp/Computation/monadic-shell.html The Unix Shell]<br />
* [http://okmij.org/ftp/Computation/monads.html More monads by Oleg]<br />
* [http://lambda-the-ultimate.org/node/2322 CLL]: a concurrent language based on a first-order intuitionistic linear logic where all right synchronous connectives are restricted to a monad. <br />
<br />
Unfinished:<br />
<br />
* [http://slate.tunes.org/repos/main/src/unfinished/monad.slate Slate]<br />
* [http://wiki.tcl.tk/14295 Parsing], [http://wiki.tcl.tk/13844 Maybe and Error] in Tcl<br />
<br />
And possibly there exist:<br />
<br />
* Standard ML (via modules?)<br />
<br />
Please add them if you know of other implementations.<br />
<br />
[http://lambda-the-ultimate.org/node/1136 Collection of links to monad implementations in various languages.] on [http://lambda-the-ultimate/ Lambda The Ultimate].<br />
<br />
==Interesting monads==<br />
<br />
A list of monads for various evaluation strategies and games:<br />
<br />
* [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Identity.html Identity monad]<br />
* [http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html Optional results]<br />
* [http://haskell.org/haskellwiki/New_monads/MonadRandom Random values]<br />
* [http://haskell.org/ghc/docs/latest/html/libraries/mtl/Control-Monad-Reader.html Read only state]<br />
* [http://haskell.org/ghc/docs/latest/html/libraries/mtl/Control-Monad-Writer.html Writable state]<br />
* [http://haskell.org/haskellwiki/New_monads/MonadSupply Unique supply]<br />
* [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad-ST.html ST - memory-only effects]<br />
* [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State.html Global state]<br />
* [http://haskell.org/haskellwiki/New_monads/MonadUndo Undoable state effects]<br />
* [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad-Instances.html Function application]<br />
* [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Error.html Functions which may error]<br />
* [http://haskell.org/ghc/docs/latest/html/libraries/stm/Control-Monad-STM.html Atomic memory transactions]<br />
* [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Cont.html Continuations]<br />
* [http://haskell.org/ghc/docs/latest/html/libraries/base/System-IO.html#t%3AIO IO - unrestricted side effects]<br />
* [http://www.haskell.org/haskellwiki/Sudoku Non-deterministic evaluation]<br />
* [http://haskell.org/ghc/docs/latest/html/libraries/mtl/Control-Monad-List.html List monad: computations with multiple choices]<br />
* [http://www.math.chalmers.se/~koen/pubs/entry-jfp99-monad.html Concurrent threads]<br />
* [http://logic.csci.unt.edu/tarau/research/PapersHTML/monadic.html Backtracking computations]<br />
* [http://www.cs.cornell.edu/people/fluet/research/rgn-monad/index.html Region allocation effects]<br />
* [http://okmij.org/ftp/Computation/monads.html#LogicT LogicT: backtracking monad transformer with fair operations and pruning]<br />
* [http://tsukimi.agusa.i.is.nagoya-u.ac.jp/~sydney/PiMonad/ Pi calculus as a monad]<br />
* [http://www.haskell.org/halfs/ Halfs], uses a read-only and write-only monad for filesystem work.<br />
* House's H monad for safe hardware access<br />
* [http://www-fp.dcs.st-and.ac.uk/~kh/papers/pasco94/subsubsectionstar3_3_2_3.html Commutable monads for parallel programming]<br />
* [http://hackage.haskell.org/package/QIO The Quantum computing monad]<br />
* [http://hackage.haskell.org/package/stream-monad Simple, Fair and Terminating Backtracking Monad]<br />
* [http://hackage.haskell.org/package/control-monad-exception Typed exceptions with call traces as a monad]<br />
* [http://hackage.haskell.org/package/control-monad-omega Breadth first list monad]<br />
* [http://hackage.haskell.org/package/control-monad-queue Continuation-based queues as monads]<br />
* [http://hackage.haskell.org/package/full-sessions Typed network protocol monad]<br />
* [http://hackage.haskell.org/package/level-monad Non-Determinism Monad for Level-Wise Search]<br />
* [http://hackage.haskell.org/package/monad-tx Transactional state monad]<br />
* [http://hackage.haskell.org/package/monadiccp A constraint programming monad]<br />
* [http://hackage.haskell.org/package/ProbabilityMonads A probability distribution monad]<br />
<br />
<br />
There are many more interesting instance of the monad abstraction out there. Please add them as you come across each species.<br />
<br />
==Fun==<br />
<br />
* If you are tired of monads, you can easily [http://saxophone.jpberlin.de/MonadTransformer?source=http%3A%2F%2Fwww%2Ehaskell%2Eorg%2Fhaskellwiki%2FCategory%3AMonad&language=English get rid of them].<br />
<br />
==See also==<br />
<br />
* [[What a Monad is not]]<br />
* [[Monads as containers]]<br />
* [[Monads as computation]]<br />
* [[Monad/ST]]<br />
* [http://www.haskellforall.com/2012/06/you-could-have-invented-free-monads.html Why free monads matter] (blog article)<br />
<br />
[[Category:Monad|*]]</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2012-08-01T21:22:46Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
|<br />
| Scott Walck<br />
|-<br />
| vilhelm_s<br />
| Vilhelm Sjöberg<br />
|-<br />
|<br />
| Todun Osunloye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
| jumex<br />
| Trevor Lalish-Menagh<br />
|-<br />
| notthemessiah<br />
| Brian Cohen<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Josh Tilles<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| sclv<br />
| Gershom Bazerman<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
| carter<br />
| Carter Tazio Schonwald<br />
|-<br />
|<br />
| Eli Frey<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| mgsloan<br />
| Michael Sloan<br />
|-<br />
| copumpkin<br />
| Dan Peebles<br />
|-<br />
| ludflu<br />
| Jim Snavely<br />
|-<br />
| realitygrill<br />
| Derrick Lin<br />
|-<br />
|<br />
| Craig Roche<br />
|-<br />
|<br />
| Jack Siler<br />
|-<br />
| djahandarie<br />
| Darius Jahandarie<br />
|-<br />
|<br />
| Stephanie Weirich<br />
|-<br />
| ohbadiah<br />
| Nicholas McAvoy<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2012-07-23T19:37:44Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
|<br />
| Scott Walck<br />
|-<br />
| vilhelm_s<br />
| Vilhelm Sjöberg<br />
|-<br />
|<br />
| Todun Osunloye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
| jumex<br />
| Trevor Lalish-Menagh<br />
|-<br />
| notthemessiah<br />
| Brian Cohen<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Josh Tilles<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| sclv<br />
| Gershom Bazerman<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
| carter<br />
| Carter Tazio Schonwald<br />
|-<br />
|<br />
| Eli Frey<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| mgsloan<br />
| Michael Sloan<br />
|-<br />
| copumpkin<br />
| Dan Peebles<br />
|-<br />
| tgeeky<br />
| Drew Day<br />
|-<br />
| ludflu<br />
| Jim Snavely<br />
|-<br />
| realitygrill<br />
| Derrick Lin<br />
|-<br />
|<br />
| Craig Roche<br />
|-<br />
|<br />
| Jack Siler<br />
|-<br />
| djahandarie<br />
| Darius Jahandarie<br />
|-<br />
|<br />
| Stephanie Weirich<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2012-07-20T00:50:46Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
|<br />
| Scott Walck<br />
|-<br />
| vilhelm_s<br />
| Vilhelm Sjöberg<br />
|-<br />
|<br />
| Todun Osunloye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
| jumex<br />
| Trevor Lalish-Menagh<br />
|-<br />
| notthemessiah<br />
| Brian Cohen<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Josh Tilles<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| sclv<br />
| Gershom Bazerman<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
| carter<br />
| Carter Tazio Schonwald<br />
|-<br />
|<br />
| Eli Frey<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| mgsloan<br />
| Michael Sloan<br />
|-<br />
| copumpkin<br />
| Dan Peebles<br />
|-<br />
| tgeeky<br />
| Drew Day<br />
|-<br />
| ludflu<br />
| Jim Snavely<br />
|-<br />
| realitygrill<br />
| Derrick Lin<br />
|-<br />
|<br />
| Craig Roche<br />
|-<br />
|<br />
| Jack Siler<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2012-07-19T22:08:58Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
|<br />
| Scott Walck<br />
|-<br />
| vilhelm_s<br />
| Vilhelm Sjöberg<br />
|-<br />
|<br />
| Todun Osunloye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
| jumex<br />
| Trevor Lalish-Menagh<br />
|-<br />
| notthemessiah<br />
| Brian Cohen<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Josh Tilles<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| sclv<br />
| Gershom Bazerman<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
| carter<br />
| Carter Tazio Schonwald<br />
|-<br />
|<br />
| Eli Frey<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| mgsloan<br />
| Michael Sloan<br />
|-<br />
| copumpkin<br />
| Dan Peebles<br />
|-<br />
| tgeeky<br />
| Drew Day<br />
|-<br />
| ludflu<br />
| Jim Snavely<br />
|-<br />
| realitygrill<br />
| Derrick Lin<br />
|-<br />
|<br />
| Craig Roche<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2012-07-19T17:54:24Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
|<br />
| Scott Walck<br />
|-<br />
| vilhelm_s<br />
| Vilhelm Sjöberg<br />
|-<br />
|<br />
| Todun Osunloye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
| jumex<br />
| Trevor Lalish-Menagh<br />
|-<br />
| notthemessiah<br />
| Brian Cohen<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Josh Tilles<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| sclv<br />
| Gershom Bazerman<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
| carter<br />
| Carter Tazio Schonwald<br />
|-<br />
|<br />
| Eli Frey<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| mgsloan<br />
| Michael Sloan<br />
|-<br />
| copumpkin<br />
| Dan Peebles<br />
|-<br />
| tgeeky<br />
| Drew Day<br />
|-<br />
| ludflu<br />
| Jim Snavely<br />
|-<br />
| realitygrill<br />
| Derrick Lin<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2012-07-17T18:18:42Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
|<br />
| Scott Walck<br />
|-<br />
| vilhelm_s<br />
| Vilhelm Sjöberg<br />
|-<br />
|<br />
| Todun Osunloye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
| jumex<br />
| Trevor Lalish-Menagh<br />
|-<br />
| notthemessiah<br />
| Brian Cohen<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Josh Tilles<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| sclv<br />
| Gershom Bazerman<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
| carter<br />
| Carter Tazio Schonwald<br />
|-<br />
|<br />
| Eli Frey<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| mgsloan<br />
| Michael Sloan<br />
|-<br />
| copumpkin<br />
| Dan Peebles<br />
|-<br />
| tgeeky<br />
| Drew Day<br />
|-<br />
| ludflu<br />
| Jim Snavely<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.</div>Dmwithttps://wiki.haskell.org/Hac_%CF%86/AttendeesHac φ/Attendees2012-07-16T23:52:15Z<p>Dmwit: /* Attendees */</p>
<hr />
<div>This is a partial list of attendees for [[Hac φ]]. Please refer to the [[Hac φ|main page]] for more information.<br />
<br />
= Attendees =<br />
<br />
Feel free to list yourself here -- though this is ''not'' registration. To register, see [[Hac φ/Register|this page]].<br />
<br />
{| class="wikitable"<br />
! Nickname<br />
! Real Name<br />
! Mobile #<br />
|-<br />
| byorgey<br />
| Brent Yorgey<br />
| (215) 350-4532<br />
|-<br />
| dmwit<br />
| Daniel Wagner<br />
| (650) 353-1788<br />
|-<br />
| ccasin<br />
| Chris Casinghino<br />
| (603) 860-5301<br />
|-<br />
| amindfv<br />
| Tom Murphy<br />
|-<br />
|<br />
| Scott Walck<br />
|-<br />
| vilhelm_s<br />
| Vilhelm Sjöberg<br />
|-<br />
|<br />
| Todun Osunloye<br />
|-<br />
| yrlnry<br />
| Mark Dominus<br />
|-<br />
| sykora<br />
| P.C. Shyamshankar<br />
|-<br />
| jumex<br />
| Trevor Lalish-Menagh<br />
|-<br />
| notthemessiah<br />
| Brian Cohen<br />
|-<br />
| dolio<br />
| Dan Doel<br />
|-<br />
|<br />
| Josh Tilles<br />
|-<br />
| edwardk<br />
| Edward Kmett<br />
|-<br />
| mightybyte<br />
| Doug Beardsley<br />
|-<br />
| sclv<br />
| Gershom Bazerman<br />
|-<br />
| Luke<br />
| Luke Hoersten<br />
|-<br />
| irene-knapp<br />
| Irene Knapp<br />
|-<br />
| carter<br />
| Carter Tazio Schonwald<br />
|-<br />
|<br />
| Eli Frey<br />
|-<br />
| acowley<br />
| Anthony Cowley<br />
|-<br />
| mgsloan<br />
| Michael Sloan<br />
|-<br />
| copumpkin<br />
| Dan Peebles<br />
|-<br />
| tgeeky<br />
| Drew Day<br />
|}<br />
<br />
= Additional Comments =<br />
<br />
Please use this section to leave comments for other attendees, e.g. for organizing accommodation.</div>Dmwit