Difference between revisions of "Xmonad/Mutable state in contrib modules or xmonad.hs"

From HaskellWiki
Jump to navigation Jump to search
(New page: This page describes how to keep track of mutable state in a module in xmonad-contrib or in the configuration. = General options = == Layouts == Layouts can keep track of their state placin...)
 
m (→‎Data.IORef: minor formatting)
Line 5: Line 5:
 
== Data.IORef ==
 
== Data.IORef ==
 
A more general way is to store data using [http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-IORef.html Data.IORef]. To create an IORef, one uses newIORef; the returned value can then be passed to functions for reading from or writing to it.
 
A more general way is to store data using [http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-IORef.html Data.IORef]. To create an IORef, one uses newIORef; the returned value can then be passed to functions for reading from or writing to it.
  +
 
Here is an example for a keybinding that keeps track of how many times it has been pressed:
 
Here is an example for a keybinding that keeps track of how many times it has been pressed:
 
<haskell>
 
<haskell>
Line 25: Line 26:
 
xmonad defaultConfig `additionalKeysP` [("M-S-t", updatingBinding ref)]
 
xmonad defaultConfig `additionalKeysP` [("M-S-t", updatingBinding ref)]
 
</haskell>
 
</haskell>
  +
 
= Only available in darcs =
 
= Only available in darcs =
 
== XMonad.Util.ExtensibleState ==
 
== XMonad.Util.ExtensibleState ==

Revision as of 19:39, 30 January 2011

This page describes how to keep track of mutable state in a module in xmonad-contrib or in the configuration.

General options

Layouts

Layouts can keep track of their state placing the information in the data type that is an instance of LayoutClass. The various methods of this typeclass allow one to update this information by supplying a new value of this type as a return value.

Data.IORef

A more general way is to store data using Data.IORef. To create an IORef, one uses newIORef; the returned value can then be passed to functions for reading from or writing to it.

Here is an example for a keybinding that keeps track of how many times it has been pressed:

import Data.IORef
..
updatingBinding :: IORef Integer -> X ()
updatingBinding ref = do
  val <- io $ readIORef ref
  io $ writeIORef ref (val+1)
  spawn $ "xmessage I have been pressed " ++ show val ++ " times before!"

To use this, it needs to be passed an IORef as a parameter:

import Data.IORef
import XMonad.Util.EZConfig
..
main = do
  ref <- newIORef 0 -- this is the initival value
  xmonad defaultConfig `additionalKeysP` [("M-S-t", updatingBinding ref)]

Only available in darcs

XMonad.Util.ExtensibleState

This module allows you to store data in xmonad's internal state eliminating the need to explicitly pass around the IORef value seen in the previous example.

For information on how to use it, refer to the module's documentation.