https://wiki.haskell.org/api.php?action=feedcontributions&user=Dag&feedformat=atomHaskellWiki - User contributions [en]2024-03-28T23:55:43ZUser contributionsMediaWiki 1.35.5https://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54722Web/Comparison of Happstack, Snap and Yesod2012-11-24T23:46:45Z<p>Dag: /* Features */ yesod-fay</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
This is an overview of features ''as supported directly by code in published packages''. When a feature is listed as "no special support" for a framework, it usually means you could somewhat trivially add the support yourself by integrating existing packages into the framework.<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| records<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| yes, with yesod-pure<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro, fay<br />
| fay<br />
| julius, fay<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Client Sessions<br />
| <hask>SafeCopy a => a</hask><br />
| <hask>HashMap Text Text</hask><br />
| <hask>Map Text ByteString</hask><br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
| no special support (unless you count acid-state's "remote" backend)<br />
| several snaplets<br />
| persistent<br />
|-<br />
! Internal Databases<br />
| acid-state (via documentation and happstack-foundation)<br />
| snaplet-acid-state, snaplet-sqlite-simple<br />
| persistent-sqlite<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54671Web/Comparison of Happstack, Snap and Yesod2012-11-15T16:19:35Z<p>Dag: /* Features */ happstack-fay</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
This is an overview of features ''as supported directly by code in published packages''. When a feature is listed as "no special support" for a framework, it usually means you could somewhat trivially add the support yourself by integrating existing packages into the framework.<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| records<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| yes, with yesod-pure<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro, fay<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Client Sessions<br />
| <hask>SafeCopy a => a</hask><br />
| <hask>HashMap Text Text</hask><br />
| <hask>Map Text ByteString</hask><br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
| no special support (unless you count acid-state's "remote" backend)<br />
| several snaplets<br />
| persistent<br />
|-<br />
! Internal Databases<br />
| acid-state (via documentation and happstack-foundation)<br />
| snaplet-acid-state, snaplet-sqlite-simple<br />
| persistent-sqlite<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54356Web/Comparison of Happstack, Snap and Yesod2012-10-15T11:04:58Z<p>Dag: /* Features */ yesod-pure provides basic routing combinators</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
This is an overview of features ''as supported directly by code in published packages''. When a feature is listed as "no special support" for a framework, it usually means you could somewhat trivially add the support yourself by integrating existing packages into the framework.<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| records<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| yes, with yesod-pure<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Client Sessions<br />
| <hask>SafeCopy a => a</hask><br />
| <hask>HashMap Text Text</hask><br />
| <hask>Map Text ByteString</hask><br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
| no special support (unless you count acid-state's "remote" backend)<br />
| several snaplets<br />
| persistent<br />
|-<br />
! Internal Databases<br />
| acid-state (via documentation and happstack-foundation)<br />
| snaplet-acid-state, snaplet-sqlite-simple<br />
| persistent-sqlite<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54272Web/Comparison of Happstack, Snap and Yesod2012-10-10T14:05:20Z<p>Dag: /* Features */</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
This is an overview of features ''as supported directly by code in published packages''. When a feature is listed as "no special support" for a framework, it usually means you could somewhat trivially add the support yourself by integrating existing packages into the framework.<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| records<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Client Sessions<br />
| <hask>SafeCopy a => a</hask><br />
| <hask>HashMap Text Text</hask><br />
| <hask>Map Text ByteString</hask><br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
| no special support (unless you count acid-state's "remote" backend)<br />
| several snaplets<br />
| persistent<br />
|-<br />
! Internal Databases<br />
| acid-state (via documentation and happstack-foundation)<br />
| snaplet-acid-state, snaplet-sqlite-simple<br />
| persistent-sqlite<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54271Web/Comparison of Happstack, Snap and Yesod2012-10-10T14:04:52Z<p>Dag: /* Features */ clarifying note</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
This is an overview of features ''as supported directly by code in published packages''. When a feature is listed as ''no special support'' for a framework, it usually means you could somewhat trivially add the support yourself by integrating existing packages into the framework.<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| records<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Client Sessions<br />
| <hask>SafeCopy a => a</hask><br />
| <hask>HashMap Text Text</hask><br />
| <hask>Map Text ByteString</hask><br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
| no special support (unless you count acid-state's "remote" backend)<br />
| several snaplets<br />
| persistent<br />
|-<br />
! Internal Databases<br />
| acid-state (via documentation and happstack-foundation)<br />
| snaplet-acid-state, snaplet-sqlite-simple<br />
| persistent-sqlite<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54270Web/Comparison of Happstack, Snap and Yesod2012-10-10T13:59:10Z<p>Dag: /* Features */</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| records<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Client Sessions<br />
| <hask>SafeCopy a => a</hask><br />
| <hask>HashMap Text Text</hask><br />
| <hask>Map Text ByteString</hask><br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
| no special support (unless you count acid-state's "remote" backend)<br />
| several snaplets<br />
| persistent<br />
|-<br />
! Internal Databases<br />
| acid-state (via documentation and happstack-foundation)<br />
| snaplet-acid-state, snaplet-sqlite-simple<br />
| persistent-sqlite<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54269Web/Comparison of Happstack, Snap and Yesod2012-10-10T13:57:35Z<p>Dag: /* Features */ databases</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| records<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Client Sessions<br />
| <hask>SafeCopy a => a</hask><br />
| <hask>HashMap Text Text</hask><br />
| <hask>Map Text ByteString</hask><br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
| no special support<br />
| several snaplets<br />
| persistent<br />
|-<br />
! Internal Databases<br />
| acid-state (via documentation and happstack-foundation)<br />
| snaplet-acid-state, snaplet-sqlite-simple<br />
| persistent-sqlite<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54264Web/Comparison of Happstack, Snap and Yesod2012-10-10T10:02:12Z<p>Dag: /* Features */</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| records<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Client Sessions<br />
| <hask>SafeCopy a => a</hask><br />
| <hask>HashMap Text Text</hask><br />
| <hask>Map Text ByteString</hask><br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54263Web/Comparison of Happstack, Snap and Yesod2012-10-10T09:54:07Z<p>Dag: /* Features */ clientsession</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| data structures<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Client Sessions<br />
| <hask>SafeCopy a => a</hask><br />
| <hask>HashMap Text Text</hask><br />
| <hask>Map Text ByteString</hask><br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54260Web/Comparison of Happstack, Snap and Yesod2012-10-10T09:41:28Z<p>Dag: /* Features */ scaffolding</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Scaffolding<br />
| not maintained<br />
| three templates<br />
| one template, interactive options<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| data structures<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Sessions<br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54238Web/Comparison of Happstack, Snap and Yesod2012-10-09T04:36:19Z<p>Dag: /* Features */</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Extensibility<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| data structures<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|-<br />
! Sessions<br />
|-<br />
! Scaffolding<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54237Web/Comparison of Happstack, Snap and Yesod2012-10-09T03:48:47Z<p>Dag: /* Features */ happstack uses monad transformers</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Pluggable Components<br />
| monad transformers<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| data structures<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|-<br />
! Sessions<br />
|-<br />
! Scaffolding<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54236Web/Comparison of Happstack, Snap and Yesod2012-10-09T03:41:29Z<p>Dag: /* Features */ Configuration</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Pluggable Components<br />
| no single dedicated concept, but highly modular api<br />
| snaplets<br />
| subsites<br />
|-<br />
! Configuration<br />
| data structures<br />
| configurator<br />
| type classes, yaml<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|-<br />
! Sessions<br />
|-<br />
! Scaffolding<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54235Web/Comparison of Happstack, Snap and Yesod2012-10-09T03:33:21Z<p>Dag: /* Features */ Code Reloading, Pluggable Components</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Code Reloading<br />
| plugins<br />
| hint<br />
| yes<br />
|-<br />
! Pluggable Components<br />
| no single dedicated concept, but highly modular api<br />
| snaplets<br />
| subsites<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|-<br />
! Sessions<br />
|-<br />
! Scaffolding<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54233Web/Comparison of Happstack, Snap and Yesod2012-10-08T15:27:07Z<p>Dag: /* Features */ server type</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Server<br />
| lazy IO (being rewritten with pipes)<br />
| enumerator<br />
| conduit<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|-<br />
! Sessions<br />
|-<br />
! Scaffolding<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54232Web/Comparison of Happstack, Snap and Yesod2012-10-08T15:21:43Z<p>Dag: /* Happstack */ repo moved</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://hub.darcs.net/stepcut/happstack the hub.darcs.net repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|-<br />
! Sessions<br />
|-<br />
! Scaffolding<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54231Web/Comparison of Happstack, Snap and Yesod2012-10-08T15:16:55Z<p>Dag: Stub of a feature overview grid</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://patch-tag.com/r/mae/happstack the patch-tag Darcs repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.<br />
<br />
<br />
== Features ==<br />
<br />
{| class="wikitable"<br />
|-<br />
! &nbsp; !! Happstack !! Snap !! Yesod<br />
|-<br />
! Version Control<br />
| [http://hub.darcs.net/stepcut/happstack darcs]<br />
| [https://github.com/snapframework git]<br />
| [https://github.com/yesodweb git]<br />
|-<br />
! Routing Combinators<br />
| [http://www.happstack.com/docs/crashcourse/RouteFilters.html#route_filters yes]<br />
| yes<br />
| ?<br />
|-<br />
! Type-safe Routing<br />
| [http://www.happstack.com/docs/crashcourse/WebRoutes.html#web-routes web-routes] fully supported<br />
| no special support, but [https://github.com/stepcut/snap-web-routes-demo can integrate web-routes manually]<br />
| [http://www.yesodweb.com/book/routing-and-handlers template-haskell DSL]<br />
|-<br />
! Logic-free Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#helloheist heist] supported<br />
| [http://snapframework.com/docs/tutorials/heist heist] fully supported and preferred<br />
| no special support<br />
|-<br />
! Embedded Templating<br />
| [http://www.happstack.com/docs/crashcourse/Templates.html#hello-hsp hsp] and [http://www.happstack.com/docs/crashcourse/Templates.html#helloblaze blaze-html] fully supported<br />
| can use blaze-html in heist splices, but discouraged<br />
| [http://www.yesodweb.com/book/shakespearean-templates hamlet] fully supported<br />
|-<br />
! JavaScript<br />
| jmacro<br />
| fay<br />
| julius<br />
|-<br />
! Form Processing<br />
| reform<br />
| digestive-functors<br />
| yesod-form<br />
|-<br />
! Authentication<br />
|-<br />
! Authorization<br />
|-<br />
! External Databases<br />
|-<br />
! Internal Databases<br />
|-<br />
! Sessions<br />
|-<br />
! Scaffolding<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=54230Web/Comparison of Happstack, Snap and Yesod2012-10-08T14:33:05Z<p>Dag: /* Happstack */ fixed link to happstack.com, added link to hackage-server mirror on hub.darcs.net</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create [http://hub.darcs.net/simon/hackage-server Hackage 2.0].<br />
* [http://happstack.com/ The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
* [http://www.atikteam.com/ AtikTeam] - an online software for project management and teamwork.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://haskell.org/hoogle/ Hoogle] — Uses some of the Yesod stack, mostly Wai/Warp.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://patch-tag.com/r/mae/happstack the patch-tag Darcs repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.</div>Daghttps://wiki.haskell.org/index.php?title=Typeclassopedia&diff=45946Typeclassopedia2012-06-08T08:08:01Z<p>Dag: /* Definition */ category-extras is deprecated</p>
<hr />
<div>''By [[User:Byorgey|Brent Yorgey]], byorgey@cis.upenn.edu''<br />
<br />
''Originally published 12 March 2009 in [http://www.haskell.org/wikiupload/8/85/TMR-Issue13.pdf issue 13] of [http://themonadreader.wordpress.com/ the Monad.Reader]. Ported to the Haskell wiki in November 2011 by [[User:Geheimdienst|Geheimdienst]].''<br />
<br />
''This is now the official version of the Typeclassopedia and supersedes the version published in the Monad.Reader. Please help update and extend it by editing it yourself or by leaving comments, suggestions, and questions on the [[Talk:Typeclassopedia|talk page]].''<br />
<br />
=Abstract=<br />
<br />
The standard Haskell libraries feature a number of type classes with algebraic or category-theoretic underpinnings. Becoming a fluent Haskell hacker requires intimate familiarity with them all, yet acquiring this familiarity often involves combing through a mountain of tutorials, blog posts, mailing list archives, and IRC logs.<br />
<br />
The goal of this document is to serve as a starting point for the student of Haskell wishing to gain a firm grasp of its standard type classes. The essentials of each type class are introduced, with examples, commentary, and extensive references for further reading.<br />
<br />
=Introduction=<br />
<br />
Have you ever had any of the following thoughts?<br />
* What the heck is a monoid, and how is it different from a mon<u>a</u>d?<br />
<br />
* I finally figured out how to use [[Parsec]] with do-notation, and someone told me I should use something called <code>Applicative</code> instead. Um, what?<br />
<br />
* Someone in the [[IRC channel|#haskell]] IRC channel used <code>(***)</code>, and when I asked lambdabot to tell me its type, it printed out scary gobbledygook that didn’t even fit on one line! Then someone used <code>fmap fmap fmap</code> and my brain exploded.<br />
<br />
* When I asked how to do something I thought was really complicated, people started typing things like <code>zip.ap fmap.(id &&& wtf)</code> and the scary thing is that they worked! Anyway, I think those people must actually be robots because there’s no way anyone could come up with that in two seconds off the top of their head.<br />
<br />
If you have, look no further! You, too, can write and understand concise, elegant, idiomatic Haskell code with the best of them.<br />
<br />
There are two keys to an expert Haskell hacker’s wisdom:<br />
# Understand the types.<br />
# Gain a deep intuition for each type class and its relationship to other type classes, backed up by familiarity with many examples.<br />
<br />
It’s impossible to overstate the importance of the first; the patient student of type signatures will uncover many profound secrets. Conversely, anyone ignorant of the types in their code is doomed to eternal uncertainty. “Hmm, it doesn’t compile ... maybe I’ll stick in an<br />
<code>fmap</code> here ... nope, let’s see ... maybe I need another <code>(.)</code> somewhere? ... um ...”<br />
<br />
The second key—gaining deep intuition, backed by examples—is also important, but much more difficult to attain. A primary goal of this document is to set you on the road to gaining such intuition. However—<br />
<br />
:''There is no royal road to Haskell. {{h:title|Well, he probably would have said it if he knew Haskell.|—Euclid}}''<br />
<br />
This document can only be a starting point, since good intuition comes from hard work, [http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/ not from learning the right metaphor]. Anyone who reads and understands all of it will still have an arduous journey ahead—but sometimes a good starting point makes a big difference.<br />
<br />
It should be noted that this is not a Haskell tutorial; it is assumed that the reader is already familiar with the basics of Haskell, including the standard <code>[http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html Prelude]</code>, the type system, data types, and type classes.<br />
<br />
The type classes we will be discussing and their interrelationships:<br />
<br />
[[Image:Typeclassopedia-diagram.png]]<br />
<br />
{{note|<code>Semigroup</code> can be found in the [http://hackage.haskell.org/package/semigroups <code>semigroups</code> package], <code>Apply</code> in the [http://hackage.haskell.org/package/semigroupoids <code>semigroupoids</code> package], and <code>Comonad</code> in the [http://hackage.haskell.org/package/comonad <code>comonad</code> package].}}<br />
<br />
* <span style="border-bottom: 2px solid black">Solid arrows</span> point from the general to the specific; that is, if there is an arrow from <code>Foo</code> to <code>Bar</code> it means that every <code>Bar</code> is (or should be, or can be made into) a <code>Foo</code>.<br />
* <span style="border-bottom: 2px dotted black">Dotted arrows</span> indicate some other sort of relationship.<br />
* <code>Monad</code> and <code>ArrowApply</code> are equivalent.<br />
* <code>Semigroup</code>, <code>Apply</code> and <code>Comonad</code> are greyed out since they are not actually (yet?) in the standard Haskell libraries {{noteref}}.<br />
<br />
One more note before we begin. The original spelling of “type class” is with two words, as evidenced by, for example, the [http://haskell.org/onlinereport/ Haskell 98 Revised Report], early papers on type classes like [http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.103.5639 Type classes in Haskell] and [http://research.microsoft.com/en-us/um/people/simonpj/papers/type-class-design-space/ Type classes: exploring the design space], and [http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.168.4008 Hudak et al.’s history of Haskell]. However, as often happens with two-word phrases that see a lot of use, it has started to show up as one word (“typeclass”) or, rarely, hyphenated (“type-class”). When wearing my prescriptivist hat, I prefer “type class”, but realize (after changing into my descriptivist hat) that there's probably not much I can do about it.<br />
<br />
We now begin with the simplest type class of all: <code>Functor</code>.<br />
<br />
=Functor=<br />
<br />
The <code>Functor</code> class ([http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor haddock]) is the most basic and ubiquitous type class in the Haskell libraries. A simple intuition is that a <code>Functor</code> represents a “container” of some sort, along with the ability to apply a function uniformly to every element in the container. For example, a list is a container of elements, and we can apply a function to every element of a list, using <code>map</code>. As another example, a binary tree is also a container of elements, and it’s not hard to come up with a way to recursively apply a function to every element in a tree.<br />
<br />
Another intuition is that a <code>Functor</code> represents some sort of “computational context”. This intuition is generally more useful, but is more difficult to explain, precisely because it is so general. Some examples later should help to clarify the <code>Functor</code>-as-context point of view.<br />
<br />
In the end, however, a <code>Functor</code> is simply what it is defined to be; doubtless there are many examples of <code>Functor</code> instances that don’t exactly fit either of the above intuitions. The wise student will focus their attention on definitions and examples, without leaning too heavily on any particular metaphor. Intuition will come, in time, on its own.<br />
<br />
==Definition==<br />
<br />
Here is the type class declaration for <code>Functor</code>:<br />
<br />
<haskell><br />
class Functor f where<br />
fmap :: (a -> b) -> f a -> f b<br />
</haskell><br />
<br />
<code>Functor</code> is exported by the <code>Prelude</code>, so no special imports are needed to use it.<br />
<br />
First, the <code>f a</code> and <code>f b</code> in the type signature for <code>fmap</code> tell us that <code>f</code> isn’t just a type; it is a ''type constructor'' which takes another type as a parameter. (A more precise way to say this is that the ''kind'' of <code>f</code> must be <code>* -> *</code>.) For example, <code>Maybe</code> is such a type constructor: <code>Maybe</code> is not a type in and of itself, but requires another type as a parameter, like <code>Maybe Integer</code>. So it would not make sense to say <code>instance Functor Integer</code>, but it could make sense to say <code>instance Functor Maybe</code>.<br />
<br />
Now look at the type of <code>fmap</code>: it takes any function from <code>a</code> to <code>b</code>, and a value of type <code>f a</code>, and outputs a value of type <code>f b</code>. From the container point of view, the intention is that <code>fmap</code> applies a function to each element of a container, without altering the structure of the container. From the context point of view, the intention is that <code>fmap</code> applies a function to a value without altering its context. Let’s look at a few specific examples.<br />
<br />
==Instances==<br />
<br />
{{note|Recall that <code>[]</code> has two meanings in Haskell: it can either stand for the empty list, or, as here, it can represent the list type constructor (pronounced “list-of”). In other words, the type <code>[a]</code> (list-of-<code>a</code>) can also be written <code>[] a</code>.}}<br />
<br />
{{note|You might ask why we need a separate <code>map</code> function. Why not just do away with the current list-only <code>map</code> function, and rename <code>fmap</code> to <code>map</code> instead? Well, that’s a good question. The usual argument is that someone just learning Haskell, when using <code>map</code> incorrectly, would much rather see an error about lists than about <code>Functor</code>s.}}<br />
<br />
As noted before, the list constructor <code>[]</code> is a functor {{noteref}}; we can use the standard list function <code>map</code> to apply a function to each element of a list {{noteref}}. The <code>Maybe</code> type constructor is also a functor, representing a container which might hold a single element. The function <code>fmap g</code> has no effect on <code>Nothing</code> (there are no elements to which <code>g</code> can be applied), and simply applies <code>g</code> to the single element inside a <code>Just</code>. Alternatively, under the context interpretation, the list functor represents a context of nondeterministic choice; that is, a list can be thought of as representing a single value which is nondeterministically chosen from among several possibilities (the elements of the list). Likewise, the <code>Maybe</code> functor represents a context with possible failure. These instances are:<br />
<br />
<haskell><br />
instance Functor [] where<br />
fmap _ [] = []<br />
fmap g (x:xs) = g x : fmap g xs<br />
-- or we could just say fmap = map<br />
<br />
instance Functor Maybe where<br />
fmap _ Nothing = Nothing<br />
fmap g (Just a) = Just (g a)<br />
</haskell><br />
<br />
As an aside, in idiomatic Haskell code you will often see the letter <code>f</code> used to stand for both an arbitrary <code>Functor</code> and an arbitrary function. In this document, <code>f</code> represents only <code>Functor</code>s, and <code>g</code> or <code>h</code> always represent functions, but you should be aware of the potential confusion. In practice, what <code>f</code> stands for should always be clear from the context, by noting whether it is part of a type or part of the code.<br />
<br />
There are other <code>Functor</code> instances in the standard libraries; below are a few. Note that some of these instances are not exported by the <code>Prelude</code>; to access them, you can import <code>Control.Monad.Instances</code>.<br />
<br />
* <code>Either e</code> is an instance of <code>Functor</code>; <code>Either e a</code> represents a container which can contain either a value of type <code>a</code>, or a value of type <code>e</code> (often representing some sort of error condition). It is similar to <code>Maybe</code> in that it represents possible failure, but it can carry some extra information about the failure as well.<br />
<br />
* <code>((,) e)</code> represents a container which holds an “annotation” of type <code>e</code> along with the actual value it holds. It might be clearer to write it as <code>(e,)</code>, by analogy with an operator section like <code>(1+)</code>, but that syntax is not allowed in types (although it is allowed in expressions with the <code>TupleSections</code> extension enabled). However, you can certainly ''think'' of it as <code>(e,)</code>.<br />
<br />
* <code>((->) e)</code> (which can be thought of as <code>(e ->)</code>; see above), the type of functions which take a value of type <code>e</code> as a parameter, is a <code>Functor</code>. As a container, <code>(e -> a)</code> represents a (possibly infinite) set of values of <code>a</code>, indexed by values of <code>e</code>. Alternatively, and more usefully, <code>((->) e)</code> can be thought of as a context in which a value of type <code>e</code> is available to be consulted in a read-only fashion. This is also why <code>((->) e)</code> is sometimes referred to as the ''reader monad''; more on this later.<br />
<br />
* <code>IO</code> is a <code>Functor</code>; a value of type <code>IO a</code> represents a computation producing a value of type <code>a</code> which may have I/O effects. If <code>m</code> computes the value <code>x</code> while producing some I/O effects, then <code>fmap g m</code> will compute the value <code>g x</code> while producing the same I/O effects.<br />
<br />
* Many standard types from the [http://hackage.haskell.org/package/containers/ containers library] (such as <code>Tree</code>, <code>Map</code>, and <code>Sequence</code>) are instances of <code>Functor</code>. A notable exception is <code>Set</code>, which cannot be made a <code>Functor</code> in Haskell (although it is certainly a mathematical functor) since it requires an <code>Ord</code> constraint on its elements; <code>fmap</code> must be applicable to ''any'' types <code>a</code> and <code>b</code>. However, <code>Set</code> (and other similarly restricted data types) can be made an instance of a suitable generalization of <code>Functor</code>, either by [http://article.gmane.org/gmane.comp.lang.haskell.cafe/78052/ making <code>a</code> and <code>b</code> arguments to the <code>Functor</code> type class themselves], or by adding an [http://blog.omega-prime.co.uk/?p=127 associated constraint].<br />
<br />
{{Exercises|<br />
<ol><br />
<li>Implement <code>Functor</code> instances for <code>Either e</code> and <code>((->) e)</code>.</li><br />
<li>Implement <code>Functor</code> instances for <code>((,) e)</code> and for <code>Pair</code>, defined as <br />
<br />
<haskell>data Pair a = Pair a a</haskell><br />
<br />
Explain their similarities and differences.<br />
</li><br />
<li>Implement a <code>Functor</code> instance for the type <code>ITree</code>, defined as<br />
<br />
<haskell><br />
data ITree a = Leaf (Int -> a) <br />
| Node [ITree a]<br />
</haskell><br />
</li><br />
<li>Give an example of a type of kind <code>* -> *</code> which cannot be made an instance of <code>Functor</code> (without using <code>undefined</code>).<br />
</li><br />
<li>Is this statement true or false? <br />
<br />
:''The composition of two <code>Functor</code>s is also a <code>Functor</code>.''<br />
<br />
If false, give a counterexample; if true, prove it by exhibiting some appropriate Haskell code.<br />
</li><br />
</ol><br />
}}<br />
<br />
==Laws==<br />
<br />
As far as the Haskell language itself is concerned, the only requirement to be a <code>Functor</code> is an implementation of <code>fmap</code> with the proper type. Any sensible <code>Functor</code> instance, however, will also satisfy the ''functor laws'', which are part of the definition of a mathematical functor. There are two:<br />
<br />
<haskell><br />
fmap id = id<br />
fmap (g . h) = (fmap g) . (fmap h)<br />
</haskell><br />
<br />
{{note|Technically, these laws make <code>f</code> and <code>fmap</code> together an endofunctor on ''Hask'', the category of Haskell types (ignoring [[Bottom|&perp;]], which is a party pooper). See [http://en.wikibooks.org/wiki/Haskell/Category_theory Wikibook: Category theory].}}<br />
<br />
Together, these laws ensure that <code>fmap g</code> does not change the ''structure'' of a container, only the elements. Equivalently, and more simply, they ensure that <code>fmap g</code> changes a value without altering its context {{noteref}}.<br />
<br />
The first law says that mapping the identity function over every item in a container has no effect. The second says that mapping a composition of two functions over every item in a container is the same as first mapping one function, and then mapping the other.<br />
<br />
As an example, the following code is a “valid” instance of <code>Functor</code> (it typechecks), but it violates the functor laws. Do you see why?<br />
<br />
<haskell><br />
-- Evil Functor instance<br />
instance Functor [] where<br />
fmap _ [] = []<br />
fmap g (x:xs) = g x : g x : fmap g xs<br />
</haskell><br />
<br />
Any Haskeller worth their salt would reject this code as a gruesome abomination.<br />
<br />
Unlike some other type classes we will encounter, a given type has at most one valid instance of <code>Functor</code>. This [http://article.gmane.org/gmane.comp.lang.haskell.libraries/15384 can be proven] via the [http://homepages.inf.ed.ac.uk/wadler/topics/parametricity.html#free ''free theorem''] for the type of <code>fmap</code>. In fact, [http://byorgey.wordpress.com/2010/03/03/deriving-pleasure-from-ghc-6-12-1/ GHC can automatically derive] <code>Functor</code> instances for many data types.<br />
<br />
A similar argument also shows that any <code>Functor</code> instance satisfying the first law (<code>fmap id = id</code>) will automatically satisfy the second law as well. Practically, this means that only the first law needs to be checked (usually by a very straightforward induction) to ensure that a <code>Functor</code> instance is valid.<br />
<br />
{{Exercises|<br />
# Although it is not possible for a <code>Functor</code> instance to satisfy the first <code>Functor</code> law but not the second, the reverse is possible. Give an example of a (bogus) <code>Functor</code> instance which satisfies the second law but not the first.<br />
# Which laws are violated by the evil <code>Functor</code> instance for list shown above: both laws, or the first law alone? Give specific counterexamples.<br />
}}<br />
<br />
==Intuition==<br />
<br />
There are two fundamental ways to think about <code>fmap</code>. The first has already been mentioned: it takes two parameters, a function and a container, and applies the function “inside” the container, producing a new container. Alternately, we can think of <code>fmap</code> as applying a function to a value in a context (without altering the context).<br />
<br />
Just like all other Haskell functions of “more than one parameter”, however, <code>fmap</code> is actually ''curried'': it does not really take two parameters, but takes a single parameter and returns a function. For emphasis, we can write <code>fmap</code>’s type with extra parentheses: <code>fmap :: (a -> b) -> (f a -> f b)</code>. Written in this form, it is apparent that <code>fmap</code> transforms a “normal” function (<code>g :: a -> b</code>) into one which operates over containers/contexts (<code>fmap g :: f a -> f b</code>). This transformation is often referred to as a ''lift''; <code>fmap</code> “lifts” a function from the “normal world” into the “<code>f</code> world”.<br />
<br />
==Further reading==<br />
<br />
A good starting point for reading about the category theory behind the concept of a functor is the excellent [http://en.wikibooks.org/wiki/Haskell/Category_theory Haskell wikibook page on category theory].<br />
<br />
=Applicative=<br />
<br />
A somewhat newer addition to the pantheon of standard Haskell type classes, ''applicative functors'' represent an abstraction lying in between <code>Functor</code> and <code>Monad</code> in expressivity, first described by McBride and Paterson. The title of their classic paper, [http://www.soi.city.ac.uk/~ross/papers/Applicative.html Applicative Programming with Effects], gives a hint at the intended intuition behind the [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html <code>Applicative</code>] type class. It encapsulates certain sorts of “effectful” computations in a functionally pure way, and encourages an “applicative” programming style. Exactly what these things mean will be seen later.<br />
<br />
==Definition==<br />
<br />
Recall that <code>Functor</code> allows us to lift a “normal” function to a function on computational contexts. But <code>fmap</code> doesn’t allow us to apply a function which is itself in a context to a value in a context. <code>Applicative</code> gives us just such a tool, <code>(<*>)</code>. It also provides a method, <code>pure</code>, for embedding values in a default, “effect free” context. Here is the type class declaration for <code>Applicative</code>, as defined in <code>Control.Applicative</code>:<br />
<br />
<haskell><br />
class Functor f => Applicative f where<br />
pure :: a -> f a<br />
(<*>) :: f (a -> b) -> f a -> f b<br />
</haskell><br />
<br />
Note that every <code>Applicative</code> must also be a <code>Functor</code>. In fact, as we will see, <code>fmap</code> can be implemented using the <code>Applicative</code> methods, so every <code>Applicative</code> is a functor whether we like it or not; the <code>Functor</code> constraint forces us to be honest.<br />
<br />
{{note|Recall that <code>($)</code> is just function application: <code>f $ x {{=}} f x</code>.}}<br />
<br />
As always, it’s crucial to understand the type signatures. First, consider <code>(<*>)</code>: the best way of thinking about it comes from noting that the type of <code>(<*>)</code> is similar to the type of <code>($)</code> {{noteref}}, but with everything enclosed in an <code>f</code>. In other words, <code>(<*>)</code> is just function application within a computational context. The type of <code>(<*>)</code> is also very similar to the type of <code>fmap</code>; the only difference is that the first parameter is <code>f (a -> b)</code>, a function in a context, instead of a “normal” function <code>(a -> b)</code>.<br />
<br />
<code>pure</code> takes a value of any type <code>a</code>, and returns a context/container of type <code>f a</code>. The intention is that <code>pure</code> creates some sort of “default” container or “effect free” context. In fact, the behavior of <code>pure</code> is quite constrained by the laws it should satisfy in conjunction with <code>(<*>)</code>. Usually, for a given implementation of <code>(<*>)</code> there is only one possible implementation of <code>pure</code>.<br />
<br />
(Note that previous versions of the Typeclassopedia explained <code>pure</code> in terms of a type class <code>Pointed</code>, which can still be found in the [http://hackage.haskell.org/package/pointed <code>pointed</code> package]. However, the current consensus is that <code>Pointed</code> is not very useful after all. For a more detailed explanation, see [[Why not Pointed?]])<br />
<br />
==Laws==<br />
<br />
{{note|See<br />
[http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html haddock for Applicative] and [http://www.soi.city.ac.uk/~ross/papers/Applicative.html Applicative programming with effects]}}<br />
<br />
There are several laws that <code>Applicative</code> instances should satisfy {{noteref}}, but only one is crucial to developing intuition, because it specifies how <code>Applicative</code> should relate to <code>Functor</code> (the other four mostly specify the exact sense in which <code>pure</code> deserves its name). This law is:<br />
<br />
<haskell><br />
fmap g x = pure g <*> x<br />
</haskell><br />
<br />
It says that mapping a pure function <code>g</code> over a context <code>x</code> is the same as first injecting <code>g</code> into a context with <code>pure</code>, and then applying it to <code>x</code> with <code>(<*>)</code>. In other words, we can decompose <code>fmap</code> into two more atomic operations: injection into a context, and application within a context. The <code>Control.Applicative</code> module also defines <code>(<$>)</code> as a synonym for <code>fmap</code>, so the above law can also be expressed as:<br />
<br />
<code>g <$> x = pure g <*> x</code>.<br />
<br />
==Instances==<br />
<br />
Most of the standard types which are instances of <code>Functor</code> are also instances of <code>Applicative</code>.<br />
<br />
<code>Maybe</code> can easily be made an instance of <code>Applicative</code>; writing such an instance is left as an exercise for the reader.<br />
<br />
The list type constructor <code>[]</code> can actually be made an instance of <code>Applicative</code> in two ways; essentially, it comes down to whether we want to think of lists as ordered collections of elements, or as contexts representing multiple results of a nondeterministic computation (see Wadler’s [http://www.springerlink.com/content/y7450255v2670167/ How to replace failure by a list of successes]).<br />
<br />
Let’s first consider the collection point of view. Since there can only be one instance of a given type class for any particular type, one or both of the list instances of <code>Applicative</code> need to be defined for a <code>newtype</code> wrapper; as it happens, the nondeterministic computation instance is the default, and the collection instance is defined in terms of a <code>newtype</code> called <code>ZipList</code>. This instance is:<br />
<br />
<haskell><br />
newtype ZipList a = ZipList { getZipList :: [a] }<br />
<br />
instance Applicative ZipList where<br />
pure = undefined -- exercise<br />
(ZipList gs) <*> (ZipList xs) = ZipList (zipWith ($) gs xs)<br />
</haskell><br />
<br />
To apply a list of functions to a list of inputs with <code>(<*>)</code>, we just match up the functions and inputs elementwise, and produce a list of the resulting outputs. In other words, we “zip” the lists together with function application, <code>($)</code>; hence the name <code>ZipList</code>. <br />
<br />
The other <code>Applicative</code> instance for lists, based on the nondeterministic computation point of view, is:<br />
<br />
<haskell><br />
instance Applicative [] where<br />
pure x = [x]<br />
gs <*> xs = [ g x | g <- gs, x <- xs ]<br />
</haskell><br />
<br />
Instead of applying functions to inputs pairwise, we apply each function to all the inputs in turn, and collect all the results in a list.<br />
<br />
Now we can write nondeterministic computations in a natural style. To add the numbers <code>3</code> and <code>4</code> deterministically, we can of course write <code>(+) 3 4</code>. But suppose instead of <code>3</code> we have a nondeterministic computation that might result in <code>2</code>, <code>3</code>, or <code>4</code>; then we can write<br />
<br />
<haskell><br />
pure (+) <*> [2,3,4] <*> pure 4<br />
</haskell><br />
<br />
or, more idiomatically,<br />
<br />
<haskell><br />
(+) <$> [2,3,4] <*> pure 4.<br />
</haskell><br />
<br />
There are several other <code>Applicative</code> instances as well:<br />
<br />
* <code>IO</code> is an instance of <code>Applicative</code>, and behaves exactly as you would think: to execute <code>m1 <*> m2</code>, first <code>m1</code> is executed, resulting in a function <code>f</code>, then <code>m2</code> is executed, resulting in a value <code>x</code>, and finally the value <code>f x</code> is returned as the result of executing <code>m1 <*> m2</code>.<br />
<br />
* <code>((,) a)</code> is an <code>Applicative</code>, as long as <code>a</code> is an instance of <code>Monoid</code> ([[#Monoid|section Monoid]]). The <code>a</code> values are accumulated in parallel with the computation.<br />
<br />
* The <code>Applicative</code> module defines the <code>Const</code> type constructor; a value of type <code>Const a b</code> simply contains an <code>a</code>. This is an instance of <code>Applicative</code> for any <code>Monoid a</code>; this instance becomes especially useful in conjunction with things like <code>Foldable</code> ([[#Foldable|section Foldable]]).<br />
<br />
* The <code>WrappedMonad</code> and <code>WrappedArrow</code> newtypes make any instances of <code>Monad</code> ([[#Monad|section Monad]]) or <code>Arrow</code> ([[#Arrow|section Arrow]]) respectively into instances of <code>Applicative</code>; as we will see when we study those type classes, both are strictly more expressive than <code>Applicative</code>, in the sense that the <code>Applicative</code> methods can be implemented in terms of their methods.<br />
<br />
{{Exercises|<br />
# Implement an instance of <code>Applicative</code> for <code>Maybe</code>.<br />
# Determine the correct definition of <code>pure</code> for the <code>ZipList</code> instance of <code>Applicative</code>—there is only one implementation that satisfies the law relating <code>pure</code> and <code>(<*>)</code>.<br />
}}<br />
<br />
==Intuition==<br />
<br />
McBride and Paterson’s paper introduces the notation <math>[[g \; x_1 \; x_2 \; \cdots \; x_n]]\ </math> to denote function application in a computational context. If each <math>x_i\ </math> has type <math>f \; t_i\ </math> for some applicative functor <math>f\ </math>, and <math>g\ </math> has type <math>t_1 \to t_2 \to \dots \to t_n \to t\ </math>, then the entire expression <math>[[g \; x_1 \; \cdots \; x_n]]\ </math> has type <math>f \; t\ </math>. You can think of this as applying a function to multiple “effectful” arguments. In this sense, the double bracket notation is a generalization of <code>fmap</code>, which allows us to apply a function to a single argument in a context.<br />
<br />
Why do we need <code>Applicative</code> to implement this generalization of <code>fmap</code>? Suppose we use <code>fmap</code> to apply <code>g</code> to the first parameter <code>x1</code>. Then we get something of type <code>f (t2 -> ... t)</code>, but now we are stuck: we can’t apply this function-in-a-context to the next argument with <code>fmap</code>. However, this is precisely what <code>(<*>)</code> allows us to do.<br />
<br />
This suggests the proper translation of the idealized notation <math>[[g \; x_1 \; x_2 \; \cdots \; x_n]]\ </math> into Haskell, namely<br />
<haskell><br />
g <$> x1 <*> x2 <*> ... <*> xn,<br />
</haskell><br />
<br />
recalling that <code>Control.Applicative</code> defines <code>(<$>)</code> as convenient infix shorthand for <code>fmap</code>. This is what is meant by an “applicative style”—effectful computations can still be described in terms of function application; the only difference is that we have to use the special operator <code>(<*>)</code> for application instead of simple juxtaposition.<br />
<br />
Note that <code>pure</code> allows embedding “non-effectful” arguments in the middle of an idiomatic application, like<br />
<haskell><br />
g <$> x1 <*> pure x2 <*> x3<br />
</haskell><br />
which has type <code>f d</code>, given<br />
<haskell><br />
g :: a -> b -> c -> d<br />
x1 :: f a<br />
x2 :: b<br />
c3 :: f c<br />
</haskell><br />
<br />
The double brackets are commonly known as “idiom brackets”, because they allow writing “idiomatic” function application, that is, function application that looks normal but has some special, non-standard meaning (determined by the particular instance of <code>Applicative</code> being used). Idiom brackets are not supported by GHC, but they are supported by the [http://personal.cis.strath.ac.uk/~conor/pub/she/ Strathclyde Haskell Enhancement], a preprocessor which (among many other things) translates idiom brackets into standard uses of <code>(<$>)</code> and <code>(<*>)</code>. This can result in much more readable code when making heavy use of <code>Applicative</code>.<br />
<br />
==Further reading==<br />
<br />
There are many other useful combinators in the standard libraries implemented in terms of <code>pure</code> and <code>(<*>)</code>: for example, <code>(*>)</code>, <code>(<*)</code>, <code>(<**>)</code>, <code>(<$)</code>, and so on (see [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html haddock for Applicative]). Judicious use of such secondary combinators can often make code using <code>Applicative</code>s much easier to read.<br />
<br />
[http://www.soi.city.ac.uk/~ross/papers/Applicative.html McBride and Paterson’s original paper] is a treasure-trove of information and examples, as well as some perspectives on the connection between <code>Applicative</code> and category theory. Beginners will find it difficult to make it through the entire paper, but it is extremely well-motivated—even beginners will be able to glean something from reading as far as they are able.<br />
<br />
{{note|Introduced by [http://conal.net/papers/simply-reactive/ an earlier paper] that was since superseded by [http://conal.net/papers/push-pull-frp/ Push-pull functional reactive programming].}}<br />
<br />
Conal Elliott has been one of the biggest proponents of <code>Applicative</code>. For example, the [http://conal.net/papers/functional-images/ Pan library for functional images] and the reactive library for functional reactive programming (FRP) {{noteref}} make key use of it; his blog also contains [http://conal.net/blog/tag/applicative-functor many examples of <code>Applicative</code> in action]. Building on the work of McBride and Paterson, Elliott also built the [[TypeCompose]] library, which embodies the observation (among others) that <code>Applicative</code> types are closed under composition; therefore, <code>Applicative</code> instances can often be automatically derived for complex types built out of simpler ones.<br />
<br />
Although the [http://hackage.haskell.org/package/parsec Parsec parsing library] ([http://legacy.cs.uu.nl/daan/download/papers/parsec-paper.pdf paper]) was originally designed for use as a monad, in its most common use cases an <code>Applicative</code> instance can be used to great effect; [http://www.serpentine.com/blog/2008/02/06/the-basics-of-applicative-functors-put-to-practical-work/ Bryan O’Sullivan’s blog post] is a good starting point. If the extra power provided by <code>Monad</code> isn’t needed, it’s usually a good idea to use <code>Applicative</code> instead.<br />
<br />
A couple other nice examples of <code>Applicative</code> in action include the [http://chrisdone.com/blog/html/2009-02-10-applicative-configfile-hsql.html ConfigFile and HSQL libraries] and the [http://groups.inf.ed.ac.uk/links/formlets/ formlets library].<br />
<br />
=Monad=<br />
<br />
It’s a safe bet that if you’re reading this, you’ve heard of monads—although it’s quite possible you’ve never heard of <code>Applicative</code> before, or <code>Arrow</code>, or even <code>Monoid</code>. Why are monads such a big deal in Haskell? There are several reasons.<br />
<br />
* Haskell does, in fact, single out monads for special attention by making them the framework in which to construct I/O operations.<br />
* Haskell also singles out monads for special attention by providing a special syntactic sugar for monadic expressions: the <code>do</code>-notation.<br />
* <code>Monad</code> has been around longer than other abstract models of computation such as <code>Applicative</code> or <code>Arrow</code>.<br />
* The more monad tutorials there are, the harder people think monads must be, and the more new monad tutorials are written by people who think they finally “get” monads (the [http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/ monad tutorial fallacy]).<br />
<br />
I will let you judge for yourself whether these are good reasons.<br />
<br />
In the end, despite all the hoopla, <code>Monad</code> is just another type class. Let’s take a look at its definition.<br />
<br />
==Definition==<br />
<br />
The type class declaration for [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad <code>Monad</code>] is:<br />
<br />
<haskell><br />
class Monad m where<br />
return :: a -> m a<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
(>>) :: m a -> m b -> m b<br />
m >> n = m >>= \_ -> n<br />
<br />
fail :: String -> m a<br />
</haskell><br />
<br />
The <code>Monad</code> type class is exported by the <code>Prelude</code>, along with a few standard instances. However, many utility functions are found in [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html <code>Control.Monad</code>], and there are also several instances (such as <code>((->) e)</code>) defined in [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad-Instances.html <code>Control.Monad.Instances</code>].<br />
<br />
Let’s examine the methods in the <code>Monad</code> class one by one. The type of <code>return</code> should look familiar; it’s the same as <code>pure</code>. Indeed, <code>return</code> ''is'' <code>pure</code>, but with an unfortunate name. (Unfortunate, since someone coming from an imperative programming background might think that <code>return</code> is like the C or Java keyword of the same name, when in fact the similarities are minimal.) From a mathematical point of view, every monad is an applicative functor, but for historical reasons, the <code>Monad</code> type class declaration unfortunately does not require this.<br />
<br />
We can see that <code>(>>)</code> is a specialized version of <code>(>>=)</code>, with a default implementation given. It is only included in the type class declaration so that specific instances of <code>Monad</code> can override the default implementation of <code>(>>)</code> with a more efficient one, if desired. Also, note that although <code>_ >> n = n</code> would be a type-correct implementation of <code>(>>)</code>, it would not correspond to the intended semantics: the intention is that <code>m >> n</code> ignores the ''result'' of <code>m</code>, but not its ''effects''.<br />
<br />
The <code>fail</code> function is an awful hack that has no place in the <code>Monad</code> class; more on this later.<br />
<br />
The only really interesting thing to look at—and what makes <code>Monad</code> strictly more powerful than <code>Applicative</code>—is <code>(>>=)</code>, which is often called ''bind''. An alternative definition of <code>Monad</code> could look like:<br />
<br />
<haskell><br />
class Applicative m => Monad' m where<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
</haskell><br />
<br />
We could spend a while talking about the intuition behind <code>(>>=)</code>—and we will. But first, let’s look at some examples.<br />
<br />
==Instances==<br />
<br />
Even if you don’t understand the intuition behind the <code>Monad</code> class, you can still create instances of it by just seeing where the types lead you. You may be surprised to find that this actually gets you a long way towards understanding the intuition; at the very least, it will give you some concrete examples to play with as you read more about the <code>Monad</code> class in general. The first few examples are from the standard <code>Prelude</code>; the remaining examples are from the [http://hackage.haskell.org/package/transformers <code>transformers</code> package].<br />
<br />
<ul><br />
<li>The simplest possible instance of <code>Monad</code> is [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Identity.html <code>Identity</code>], which is described in Dan Piponi’s highly recommended blog post on [http://blog.sigfpe.com/2007/04/trivial-monad.html The Trivial Monad]. Despite being “trivial”, it is a great introduction to the <code>Monad</code> type class, and contains some good exercises to get your brain working.<br />
</li><br />
<li>The next simplest instance of <code>Monad</code> is <code>Maybe</code>. We already know how to write <code>return</code>/<code>pure</code> for <code>Maybe</code>. So how do we write <code>(>>=)</code>? Well, let’s think about its type. Specializing for <code>Maybe</code>, we have<br />
<br />
<haskell><br />
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b.<br />
</haskell><br />
<br />
If the first argument to <code>(>>=)</code> is <code>Just x</code>, then we have something of type <code>a</code> (namely, <code>x</code>), to which we can apply the second argument—resulting in a <code>Maybe b</code>, which is exactly what we wanted. What if the first argument to <code>(>>=)</code> is <code>Nothing</code>? In that case, we don’t have anything to which we can apply the <code>a -> Maybe b</code> function, so there’s only one thing we can do: yield <code>Nothing</code>. This instance is:<br />
<br />
<haskell><br />
instance Monad Maybe where<br />
return = Just<br />
(Just x) >>= g = g x<br />
Nothing >>= _ = Nothing<br />
</haskell><br />
<br />
We can already get a bit of intuition as to what is going on here: if we build up a computation by chaining together a bunch of functions with <code>(>>=)</code>, as soon as any one of them fails, the entire computation will fail (because <code>Nothing >>= f</code> is <code>Nothing</code>, no matter what <code>f</code> is). The entire computation succeeds only if all the constituent functions individually succeed. So the <code>Maybe</code> monad models computations which may fail.<br />
</li><br />
<br />
<li>The <code>Monad</code> instance for the list constructor <code>[]</code> is similar to its <code>Applicative</code> instance; see the exercise below.<br />
</li><br />
<br />
<li>Of course, the <code>IO</code> constructor is famously a <code>Monad</code>, but its implementation is somewhat magical, and may in fact differ from compiler to compiler. It is worth emphasizing that the <code>IO</code> monad is the ''only'' monad which is magical. It allows us to build up, in an entirely pure way, values representing possibly effectful computations. The special value <code>main</code>, of type <code>IO ()</code>, is taken by the runtime and actually executed, producing actual effects. Every other monad is functionally pure, and requires no special compiler support. We often speak of monadic values as “effectful computations”, but this is because some monads allow us to write code ''as if'' it has side effects, when in fact the monad is hiding the plumbing which allows these apparent side effects to be implemented in a functionally pure way.<br />
</li><br />
<br />
<li>As mentioned earlier, <code>((->) e)</code> is known as the ''reader monad'', since it describes computations in which a value of type <code>e</code> is available as a read-only environment.<br />
<br />
The [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Reader.html <code>Control.Monad.Reader</code>] module provides the <code>Reader e a</code> type, which is just a convenient <code>newtype</code> wrapper around <code>(e -> a)</code>, along with an appropriate <code>Monad</code> instance and some <code>Reader</code>-specific utility functions such as <code>ask</code> (retrieve the environment), <code>asks</code> (retrieve a function of the environment), and <code>local</code> (run a subcomputation under a different environment).<br />
</li><br />
<br />
<li>The [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Writer-Lazy.html <code>Control.Monad.Writer</code>] module provides the <code>Writer</code> monad, which allows information to be collected as a computation progresses. <code>Writer w a</code> is isomorphic to <code>(a,w)</code>, where the output value <code>a</code> is carried along with an annotation or “log” of type <code>w</code>, which must be an instance of <code>Monoid</code> (see [[#Monoid|section Monoid]]); the special function <code>tell</code> performs logging.<br />
</li><br />
<br />
<li>The [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State-Lazy.html <code>Control.Monad.State</code>] module provides the <code>State s a</code> type, a <code>newtype</code> wrapper around <code>s -> (a,s)</code>. Something of type <code>State s a</code> represents a stateful computation which produces an <code>a</code> but can access and modify the state of type <code>s</code> along the way. The module also provides <code>State</code>-specific utility functions such as <code>get</code> (read the current state), <code>gets</code> (read a function of the current state), <code>put</code> (overwrite the state), and <code>modify</code> (apply a function to the state).<br />
</li><br />
<br />
<li>The [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Cont.html <code>Control.Monad.Cont</code>] module provides the <code>Cont</code> monad, which represents computations in continuation-passing style. It can be used to suspend and resume computations, and to implement non-local transfers of control, co-routines, other complex control structures—all in a functionally pure way. <code>Cont</code> has been called the [http://blog.sigfpe.com/2008/12/mother-of-all-monads.html “mother of all monads”] because of its universal properties.<br />
</li><br />
</ul><br />
<br />
{{Exercises|<br />
<ol><br />
<li>Implement a <code>Monad</code> instance for the list constructor, <code>[]</code>. Follow the types!</li><br />
<li>Implement a <code>Monad</code> instance for <code>((->) e)</code>.</li><br />
<li>Implement <code>Functor</code> and <code>Monad</code> instances for <code>Free f</code>, defined as<br />
<haskell><br />
data Free f a = Var a<br />
| Node (f (Free f a))<br />
</haskell><br />
You may assume that <code>f</code> has a <code>Functor</code> instance. This is known as the ''free monad'' built from the functor <code>f</code>.<br />
</li><br />
</ol><br />
}}<br />
<br />
==Intuition==<br />
<br />
Let’s look more closely at the type of <code>(>>=)</code>. The basic intuition is that it combines two computations into one larger computation. The first argument, <code>m a</code>, is the first computation. However, it would be boring if the second argument were just an <code>m b</code>; then there would be no way for the computations to interact with one another (actually, this is exactly the situation with <code>Applicative</code>). So, the second argument to <code>(>>=)</code> has type <code>a -> m b</code>: a function of this type, given a ''result'' of the first computation, can produce a second computation to be run. In other words, <code>x >>= k</code> is a computation which runs <code>x</code>, and then uses the result(s) of <code>x</code> to ''decide'' what computation to run second, using the output of the second computation as the result of the entire computation.<br />
<br />
{{note|Actually, because Haskell allows general recursion, this is a lie: using a Haskell parsing library one can recursively construct ''infinite'' grammars, and hence <code>Alternative</code> by itself is enough to parse any context-sensitive language with a finite alphabet. Simply make an n-way choice on each symbol you care about, and "encode" the context by having a different nonterminal for every possible pairing of a context and a nonterminal from the original grammar. However, no one in their right mind would want to write a context-sensitive parser this way!}}<br />
Intuitively, it is this ability to use the output from previous computations to decide what computations to run next that makes <code>Monad</code> more powerful than <code>Applicative</code>. The structure of an <code>Applicative</code> computation is fixed, whereas the structure of a <code>Monad</code> computation can change based on intermediate results. This also means that parsers built using an <code>Applicative</code> interface can only parse context-free languages; in order to parse context-sensitive languages a <code>Monad</code> interface is needed.{{noteref}}<br />
<br />
To see the increased power of <code>Monad</code> from a different point of view, let’s see what happens if we try to implement <code>(>>=)</code> in terms of <code>fmap</code>, <code>pure</code>, and <code>(<*>)</code>. We are given a value <code>x</code> of type <code>m a</code>, and a function <code>k</code> of type <code>a -> m b</code>, so the only thing we can do is apply <code>k</code> to <code>x</code>. We can’t apply it directly, of course; we have to use <code>fmap</code> to lift it over the <code>m</code>. But what is the type of <code>fmap k</code>? Well, it’s <code>m a -> m (m b)</code>. So after we apply it to <code>x</code>, we are left with something of type <code>m (m b)</code>—but now we are stuck; what we really want is an <code>m b</code>, but there’s no way to get there from here. We can ''add'' <code>m</code>’s using <code>pure</code>, but we have no way to ''collapse'' multiple <code>m</code>’s into one.<br />
<br />
{{note|1=You might hear some people claim that that the definition in terms of <code>return</code>, <code>fmap</code>, and <code>join</code> is the “math definition” and the definition in terms of <code>return</code> and <code>(>>=)</code> is something specific to Haskell. In fact, both definitions were known in the mathematics community long before Haskell picked up monads.}}<br />
<br />
This ability to collapse multiple <code>m</code>’s is exactly the ability provided by the function <code>join :: m (m a) -> m a</code>, and it should come as no surprise that an alternative definition of <code>Monad</code> can be given in terms of <code>join</code>:<br />
<br />
<haskell><br />
class Applicative m => Monad'' m where<br />
join :: m (m a) -> m a<br />
</haskell><br />
<br />
In fact, the earliest definitions of monads in category theory were in terms of <code>return</code>, <code>fmap</code>, and <code>join</code> (often called <math>\eta</math>, <math>T</math>, and <math>\mu</math> in the mathematical literature). Haskell uses an alternative formulation with <code>(>>=)</code> instead of <code>join</code> since it is more convenient to use {{noteref}}. However, sometimes it can be easier to think about <code>Monad</code> instances in terms of <code>join</code>, since it is a more “atomic” operation. (For example, <code>join</code> for the list monad is just <code>concat</code>.)<br />
<br />
{{Exercises|<br />
# Implement <code>(>>{{=}})</code> in terms of <code>fmap</code> (or <code>liftM</code>) and <code>join</code>.<br />
# Now implement <code>join</code> and <code>fmap</code> (<code>liftM</code>) in terms of <code>(>>{{=}})</code> and <code>return</code>.<br />
}}<br />
<br />
==Utility functions==<br />
<br />
The [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html <code>Control.Monad</code>] module provides a large number of convenient utility functions, all of which can be implemented in terms of the basic <code>Monad</code> operations (<code>return</code> and <code>(>>=)</code> in particular). We have already seen one of them, namely, <code>join</code>. We also mention some other noteworthy ones here; implementing these utility functions oneself is a good exercise. For a more detailed guide to these functions, with commentary and example code, see Henk-Jan van Tuyl’s [http://members.chello.nl/hjgtuyl/tourdemonad.html tour].<br />
<br />
{{note|Still, it is unclear how this "bug" should be fixed. Making <code>Monad</code> require a <code>Functor</code> instance has some drawbacks, as mentioned in this [http://www.haskell.org/pipermail/haskell-prime/2011-January/003312.html 2011 mailing-list discussion]. —Geheimdienst}}<br />
<br />
* <code>liftM :: Monad m => (a -> b) -> m a -> m b</code>. This should be familiar; of course, it is just <code>fmap</code>. The fact that we have both <code>fmap</code> and <code>liftM</code> is an unfortunate consequence of the fact that the <code>Monad</code> type class does not require a <code>Functor</code> instance, even though mathematically speaking, every monad is a functor. However, <code>fmap</code> and <code>liftM</code> are essentially interchangeable, since it is a bug (in a social rather than technical sense) for any type to be an instance of <code>Monad</code> without also being an instance of <code>Functor</code> {{noteref}}.<br />
<br />
* <code>ap :: Monad m => m (a -> b) -> m a -> m b</code> should also be familiar: it is equivalent to <code>(<*>)</code>, justifying the claim that the <code>Monad</code> interface is strictly more powerful than <code>Applicative</code>. We can make any <code>Monad</code> into an instance of <code>Applicative</code> by setting <code>pure = return</code> and <code>(<*>) = ap</code>.<br />
<br />
* <code>sequence :: Monad m => [m a] -> m [a]</code> takes a list of computations and combines them into one computation which collects a list of their results. It is again something of a historical accident that <code>sequence</code> has a <code>Monad</code> constraint, since it can actually be implemented only in terms of <code>Applicative</code>. There is an additional generalization of <code>sequence</code> to structures other than lists, which will be discussed in the [[#Traversable|section on <code>Traversable</code>]].<br />
<br />
* <code>replicateM :: Monad m => Int -> m a -> m [a]</code> is simply a combination of [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:replicate <code>replicate</code>] and <code>sequence</code>.<br />
<br />
* <code>when :: Monad m => Bool -> m () -> m ()</code> conditionally executes a computation, evaluating to its second argument if the test is <code>True</code>, and to <code>return ()</code> if the test is <code>False</code>. A collection of other sorts of monadic conditionals can be found in the [http://hackage.haskell.org/package/IfElse <code>IfElse</code> package].<br />
<br />
* <code>mapM :: Monad m => (a -> m b) -> [a] -> m [b]</code> maps its first argument over the second, and <code>sequence</code>s the results. The <code>forM</code> function is just <code>mapM</code> with its arguments reversed; it is called <code>forM</code> since it models generalized <code>for</code> loops: the list <code>[a]</code> provides the loop indices, and the function <code>a -> m b</code> specifies the “body” of the loop for each index.<br />
<br />
* <code>(=<<) :: Monad m => (a -> m b) -> m a -> m b</code> is just <code>(>>=)</code> with its arguments reversed; sometimes this direction is more convenient since it corresponds more closely to function application.<br />
<br />
* <code>(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c</code> is sort of like function composition, but with an extra <code>m</code> on the result type of each function, and the arguments swapped. We’ll have more to say about this operation later. There is also a flipped variant, <code>(<=<)</code>.<br />
<br />
* The <code>guard</code> function is for use with instances of <code>MonadPlus</code>, which is discussed at the end of the [[#Monoid|<code>Monoid</code> section]].<br />
<br />
Many of these functions also have “underscored” variants, such as <code>sequence_</code> and <code>mapM_</code>; these variants throw away the results of the computations passed to them as arguments, using them only for their side effects.<br />
<br />
Other monadic functions which are occasionally useful include <code>filterM</code>, <code>zipWithM</code>, <code>foldM</code>, and <code>forever</code>. <br />
<br />
==Laws==<br />
<br />
There are several laws that instances of <code>Monad</code> should satisfy (see also the [[Monad laws]] wiki page). The standard presentation is:<br />
<br />
<haskell><br />
return a >>= k = k a<br />
m >>= return = m<br />
m >>= (\x -> k x >>= h) = (m >>= k) >>= h<br />
<br />
fmap f xs = xs >>= return . f = liftM f xs<br />
</haskell><br />
<br />
The first and second laws express the fact that <code>return</code> behaves nicely: if we inject a value <code>a</code> into a monadic context with <code>return</code>, and then bind to <code>k</code>, it is the same as just applying <code>k</code> to <code>a</code> in the first place; if we bind a computation <code>m</code> to <code>return</code>, nothing changes. The third law essentially says that <code>(>>=)</code> is associative, sort of. The last law ensures that <code>fmap</code> and <code>liftM</code> are the same for types which are instances of both <code>Functor</code> and <code>Monad</code>—which, as already noted, should be every instance of <code>Monad</code>.<br />
<br />
{{note|I like to pronounce this operator “fish”, but that’s probably not the canonical pronunciation ...}}<br />
<br />
However, the presentation of the above laws, especially the third, is marred by the asymmetry of <code>(>>=)</code>. It’s hard to look at the laws and see what they’re really saying. I prefer a much more elegant version of the laws, which is formulated in terms of <code>(>=>)</code> {{noteref}}. Recall that <code>(>=>)</code> “composes” two functions of type <code>a -> m b</code> and <code>b -> m c</code>. You can think of something of type <code>a -> m b</code> (roughly) as a function from <code>a</code> to <code>b</code> which may also have some sort of effect in the context corresponding to <code>m</code>. <code>(>=>)</code> lets us compose these “effectful functions”, and we would like to know what properties <code>(>=>)</code> has. The monad laws reformulated in terms of <code>(>=>)</code> are:<br />
<br />
<haskell><br />
return >=> g = g<br />
g >=> return = g<br />
(g >=> h) >=> k = g >=> (h >=> k)<br />
</haskell><br />
<br />
{{note|As fans of category theory will note, these laws say precisely that functions of type <code>a -> m b</code> are the arrows of a category with <code>(>{{=}}>)</code> as composition! Indeed, this is known as the ''Kleisli category'' of the monad <code>m</code>. It will come up again when we discuss <code>Arrow</code>s.}}<br />
<br />
Ah, much better! The laws simply state that <code>return</code> is the identity of <code>(>=>)</code>, and that <code>(>=>)</code> is associative {{noteref}}. Working out the equivalence between these two formulations, given the definition <code>g >=> h = \x -> g x >>= h</code>, is left as an exercise.<br />
<br />
There is also a formulation of the monad laws in terms of <code>fmap</code>, <code>return</code>, and <code>join</code>; for a discussion of this formulation, see the Haskell [http://en.wikibooks.org/wiki/Haskell/Category_theory wikibook page on category theory].<br />
<br />
==<code>do</code> notation==<br />
<br />
Haskell’s special <code>do</code> notation supports an “imperative style” of programming by providing syntactic sugar for chains of monadic expressions. The genesis of the notation lies in realizing that something like <code>a >>= \x -> b >> c >>= \y -> d </code> can be more readably written by putting successive computations on separate lines:<br />
<br />
<haskell><br />
a >>= \x -><br />
b >><br />
c >>= \y -><br />
d<br />
</haskell><br />
<br />
This emphasizes that the overall computation consists of four computations <code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code>, and that <code>x</code> is bound to the result of <code>a</code>, and <code>y</code> is bound to the result of <code>c</code> (<code>b</code>, <code>c</code>, and <code>d</code> are allowed to refer to <code>x</code>, and <code>d</code> is allowed to refer to <code>y</code> as well). From here it is not hard to imagine a nicer notation:<br />
<br />
<haskell><br />
do { x <- a ;<br />
b ;<br />
y <- c ;<br />
d<br />
}<br />
</haskell><br />
<br />
(The curly braces and semicolons may optionally be omitted; the Haskell parser uses layout to determine where they should be inserted.) This discussion should make clear that <code>do</code> notation is just syntactic sugar. In fact, <code>do</code> blocks are recursively translated into monad operations (almost) like this:<br />
<br />
<pre><br />
do e → e<br />
do { e; stmts } → e >> do { stmts }<br />
do { v <- e; stmts } → e >>= \v -> do { stmts }<br />
do { let decls; stmts} → let decls in do { stmts }<br />
</pre><br />
<br />
This is not quite the whole story, since <code>v</code> might be a pattern instead of a variable. For example, one can write<br />
<br />
<haskell><br />
do (x:xs) <- foo<br />
bar x<br />
</haskell><br />
<br />
but what happens if <code>foo</code> produces an empty list? Well, remember that ugly <code>fail</code> function in the <code>Monad</code> type class declaration? That’s what happens. See [http://haskell.org/onlinereport/exps.html#sect3.14 section 3.14 of the Haskell Report] for the full details. See also the discussion of <code>MonadPlus</code> and <code>MonadZero</code> in the [[#Other monoidal classes: Alternative, MonadPlus, ArrowPlus|section on other monoidal classes]].<br />
<br />
A final note on intuition: <code>do</code> notation plays very strongly to the “computational context” point of view rather than the “container” point of view, since the binding notation <code>x <- m</code> is suggestive of “extracting” a single <code>x</code> from <code>m</code> and doing something with it. But <code>m</code> may represent some sort of a container, such as a list or a tree; the meaning of <code>x <- m</code> is entirely dependent on the implementation of <code>(>>=)</code>. For example, if <code>m</code> is a list, <code>x <- m</code> actually means that <code>x</code> will take on each value from the list in turn.<br />
<br />
==Further reading==<br />
<br />
Philip Wadler was the first to propose using monads to structure functional programs. [http://homepages.inf.ed.ac.uk/wadler/topics/monads.html His paper] is still a readable introduction to the subject.<br />
<br />
{{note|1=<br />
[[All About Monads]],<br />
[http://haskell.org/haskellwiki/Monads_as_Containers Monads as containers],<br />
[http://en.wikibooks.org/w/index.php?title=Haskell/Understanding_monads&oldid=933545 Understanding monads],<br />
[[The Monadic Way]],<br />
[http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html You Could Have Invented Monads! (And Maybe You Already Have.)],<br />
[http://www.haskell.org/pipermail/haskell-cafe/2006-November/019190.html there’s a monster in my Haskell!],<br />
[http://kawagner.blogspot.com/2007/02/understanding-monads-for-real.html Understanding Monads. For real.],<br />
[http://www.randomhacks.net/articles/2007/03/12/monads-in-15-minutes Monads in 15 minutes: Backtracking and Maybe],<br />
[http://haskell.org/haskellwiki/Monads_as_computation Monads as computation],<br />
[http://metafoo.co.uk/practical-monads.txt Practical Monads]}}<br />
<br />
There are, of course, numerous monad tutorials of varying quality {{noteref}}.<br />
<br />
A few of the best include Cale Gibbard’s [http://haskell.org/haskellwiki/Monads_as_Containers Monads as containers] and [http://haskell.org/haskellwiki/Monads_as_computation Monads as computation]; Jeff Newbern’s [[All About Monads]], a comprehensive guide with lots of examples; and Dan Piponi’s [http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html You Could Have Invented Monads!], which features great exercises. If you just want to know how to use <code>IO</code>, you could consult the [[Introduction to IO]]. Even this is just a sampling; the [[monad tutorials timeline]] is a more complete list. (All these monad tutorials have prompted parodies like [http://koweycode.blogspot.com/2007/01/think-of-monad.html think of a monad ...] as well as other kinds of backlash like [http://ahamsandwich.wordpress.com/2007/07/26/monads-and-why-monad-tutorials-are-all-awful/ Monads! (and Why Monad Tutorials Are All Awful)] or [http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/ Abstraction, intuition, and the “monad tutorial fallacy”].)<br />
<br />
Other good monad references which are not necessarily tutorials include [http://members.chello.nl/hjgtuyl/tourdemonad.html Henk-Jan van Tuyl’s tour] of the functions in <code>Control.Monad</code>, Dan Piponi’s [http://blog.sigfpe.com/2006/10/monads-field-guide.html field guide], and Tim Newsham’s [http://www.thenewsh.com/~newsham/haskell/monad.html What’s a Monad?]. There are also many blog posts which have been written on various aspects of monads; a collection of links can be found under [[Blog articles/Monads]].<br />
<br />
One of the quirks of the <code>Monad</code> class and the Haskell type system is that it is not possible to straightforwardly declare <code>Monad</code> instances for types which require a class constraint on their data, even if they are monads from a mathematical point of view. For example, <code>Data.Set</code> requires an <code>Ord</code> constraint on its data, so it cannot be easily made an instance of <code>Monad</code>. A solution to this problem was [http://www.randomhacks.net/articles/2007/03/15/data-set-monad-haskell-macros first described by Eric Kidd], and later made into a [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/rmonad library named rmonad] by Ganesh Sittampalam and Peter Gavin.<br />
<br />
There are many good reasons for eschewing <code>do</code> notation; some have gone so far as to [[Do_notation_considered_harmful|consider it harmful]].<br />
<br />
Monads can be generalized in various ways; for an exposition of one possibility, see Robert Atkey’s paper on [http://homepages.inf.ed.ac.uk/ratkey/paramnotions-jfp.pdf parameterized monads], or Dan Piponi’s [http://blog.sigfpe.com/2009/02/beyond-monads.html Beyond Monads].<br />
<br />
For the categorically inclined, monads can be viewed as monoids ([http://blog.sigfpe.com/2008/11/from-monoids-to-monads.html From Monoids to Monads]) and also as closure operators [http://blog.plover.com/math/monad-closure.html Triples and Closure]. Derek Elkins’s article in [http://www.haskell.org/wikiupload/8/85/TMR-Issue13.pdf issue 13 of the Monad.Reader] contains an exposition of the category-theoretic underpinnings of some of the standard <code>Monad</code> instances, such as <code>State</code> and <code>Cont</code>.<br />
<br />
Links to many more research papers related to monads can be found under [[Research papers/Monads and arrows]].<br />
<br />
=Monad transformers=<br />
<br />
One would often like to be able to combine two monads into one: for example, to have stateful, nondeterministic computations (<code>State</code> + <code>[]</code>), or computations which may fail and can consult a read-only environment (<code>Maybe</code> + <code>Reader</code>), and so on. Unfortunately, monads do not compose as nicely as applicative functors (yet another reason to use <code>Applicative</code> if you don’t need the full power that <code>Monad</code> provides), but some monads can be combined in certain ways.<br />
<br />
==Standard monad transformers==<br />
<br />
The [http://hackage.haskell.org/package/transformers transformers] library provides a number of standard ''monad transformers''. Each monad transformer adds a particular capability/feature/effect to any existing monad.<br />
<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Identity.html <code>IdentityT</code>] is the identity transformer, which maps a monad to (something isomorphic to) itself. This may seem useless at first glance, but it is useful for the same reason that the <code>id</code> function is useful -- it can be passed as an argument to things which are parameterized over an arbitrary monad transformer.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-State.html <code>StateT</code>] adds a read-write state.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Reader.html <code>ReaderT</code>] adds a read-only environment.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Writer.html <code>WriterT</code>] adds a write-only log.<br />
* [http://hackage.haskell.org/packages/archive/transformers/0.2.2.0/doc/html/Control-Monad-Trans-RWS.html <code>RWST</code>] conveniently combines <code>ReaderT</code>, <code>WriterT</code>, and <code>StateT</code> into one.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Maybe.html <code>MaybeT</code>] adds the possibility of failure.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Error.html <code>ErrorT</code>] adds the possibility of failure with an arbitrary type to represent errors.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-List.html <code>ListT</code>] adds non-determinism (however, see the discussion of <code>ListT</code> below).<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Cont.html <code>ContT</code>] adds continuation handling.<br />
<br />
For example, <code>StateT s Maybe</code> is an instance of <code>Monad</code>; computations of type <code>StateT s Maybe a</code> may fail, and have access to a mutable state of type <code>s</code>. Monad transformers can be multiply stacked. One thing to keep in mind while using monad transformers is that the order of composition matters. For example, when a <code>StateT s Maybe a</code> computation fails, the state ceases being updated (indeed, it simply disappears); on the other hand, the state of a <code>MaybeT (State s) a</code> computation may continue to be modified even after the computation has failed. This may seem backwards, but it is correct. Monad transformers build composite monads “inside out”; <code>MaybeT (State s) a</code> is isomorphic to <code>s -> (Maybe a, s)</code>. (Lambdabot has an indispensable <code>@unmtl</code> command which you can use to “unpack” a monad transformer stack in this way.)<br />
Intuitively, the monads become "more fundamental" the further down in the stack you get, and the effects of a given monad "have precedence" over the effects of monads further up the stack. Of course, this is just handwaving, and if you are unsure of the proper order for some monads you wish to combine, there is no substitute for using <code>@unmtl</code> or simply trying out the various options.<br />
<br />
==Definition and laws==<br />
<br />
All monad transformers should implement the <code>MonadTrans</code> type class, defined in <code>Control.Monad.Trans.Class</code>:<br />
<br />
<haskell><br />
class MonadTrans t where<br />
lift :: Monad m => m a -> t m a<br />
</haskell><br />
<br />
It allows arbitrary computations in the base monad <code>m</code> to be “lifted” into computations in the transformed monad <code>t m</code>. (Note that type application associates to the left, just like function application, so <code>t m a = (t m) a</code>.)<br />
<br />
<code>lift</code> must satisfy the laws<br />
<haskell><br />
lift . return = return<br />
lift (m >>= f) = lift m >>= (lift . f)<br />
</haskell><br />
which intuitively state that <code>lift</code> transforms <code>m a</code> computations into <code>t m a</code> computations in a "sensible" way, which sends the <code>return</code> and <code>(>>=)</code> of <code>m</code> to the <code>return</code> and <code>(>>=)</code> of <code>t m</code>.<br />
<br />
{{Exercises|<br />
# What is the kind of <code>t</code> in the declaration of <code>MonadTrans</code>?<br />
}}<br />
<br />
==Transformer type classes and "capability" style==<br />
<br />
{{note|The only problem with this scheme is the quadratic number of instances required as the number of standard monad transformers grows—but as the current set of standard monad transformers seems adequate for most common use cases, this may not be that big of a deal.}}<br />
<br />
There are also type classes (provided by the [http://hackage.haskell.org/package/mtl <code>mtl</code> package]) for the operations of each transformer. For example, the <code>MonadState</code> type class provides the state-specific methods <code>get</code> and <code>put</code>, allowing you to conveniently use these methods not only with <code>State</code>, but with any monad which is an instance of <code>MonadState</code>—including <code>MaybeT (State s)</code>, <code>StateT s (ReaderT r IO)</code>, and so on. Similar type classes exist for <code>Reader</code>, <code>Writer</code>, <code>Cont</code>, <code>IO</code>, and others {{noteref}}.<br />
<br />
These type classes serve two purposes. First, they get rid of (most of) the need for explicitly using <code>lift</code>, giving a type-directed way to automatically determine the right number of calls to <code>lift</code>. Simply writing <code>put</code> will be automatically translated into <code>lift . put</code>, <code>lift . lift . put</code>, or something similar depending on what concrete monad stack you are using.<br />
<br />
Second, they give you more flexibility to switch between different concrete monad stacks. For example, if you are writing a state-based algorithm, don't write<br />
<haskell><br />
foo :: State Int Char<br />
foo = modify (*2) >> return 'x'<br />
</haskell><br />
but rather<br />
<haskell><br />
foo :: MonadState Int m => m Char<br />
foo = modify (*2) >> return 'x'<br />
</haskell><br />
Now, if somewhere down the line you realize you need to introduce the possibility of failure, you might switch from <code>State Int</code> to <code>MaybeT (State Int)</code>. The type of the first version of <code>foo</code> would need to be modified to reflect this change, but the second version of <code>foo</code> can still be used as-is.<br />
<br />
However, this sort of "capability-based" style (<i>e.g.</i> specifying that <code>foo</code> works for any monad with the "state capability") quickly runs into problems when you try to naively scale it up: for example, what if you need to maintain two independent states? A very nice framework for solving this and related problems is described by Schrijvers and Olivera ([http://users.ugent.be/~tschrijv/Research/papers/icfp2011.pdf Monads, zippers and views: virtualizing the monad stack, ICFP 2011]) and is implemented in the [http://hackage.haskell.org/package/Monatron <code>Monatron</code> package].<br />
<br />
==Composing monads==<br />
<br />
Is the composition of two monads always a monad? As hinted previously, the answer is no. For example, ''XXX insert example here''.<br />
<br />
Since <code>Applicative</code> functors are closed under composition, the problem must lie with <code>join</code>. Indeed, suppose <code>m</code> and <code>n</code> are arbitrary monads; to make a monad out of their composition we would need to be able to implement<br />
<haskell><br />
join :: m (n (m (n a))) -> m (n a)<br />
</haskell><br />
but it is not clear how this could be done in general. The <code>join</code> method for <code>m</code> is no help, because the two occurrences of <code>m</code> are not next to each other (and likewise for <code>n</code>).<br />
<br />
However, one situation in which it can be done is if <code>n</code> ''distributes'' over <code>m</code>, that is, if there is a function<br />
<haskell><br />
distrib :: n (m a) -> m (n a)<br />
</haskell><br />
satisfying certain laws. See Jones and Duponcheel ([http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2605 Composing Monads]).<br />
<br />
{{Exercises|<br />
* Implement <code>join :: M (N (M (N a))) -> M (N a)</code>, given <code>distrib :: N (M a) -> M (N a)</code> and assuming <code>M</code> and <code>N</code> are instances of <code>Monad</code>.<br />
}}<br />
<br />
==Further reading==<br />
<br />
Much of the monad transformer library (originally [http://hackage.haskell.org/package/mtl <code>mtl</code>], now split between <code>mtl</code> and [http://hackage.haskell.org/package/transformers <code>transformers</code>]), including the <code>Reader</code>, <code>Writer</code>, <code>State</code>, and other monads, as well as the monad transformer framework itself, was inspired by Mark Jones’s classic paper [http://web.cecs.pdx.edu/~mpj/pubs/springschool.html Functional Programming with Overloading and Higher-Order Polymorphism]. It’s still very much worth a read—and highly readable—after almost fifteen years.<br />
<br />
There are two excellent references on monad transformers. Martin Grabmüller’s [http://www.grabmueller.de/martin/www/pub/Transformers.en.html Monad Transformers Step by Step] is a thorough description, with running examples, of how to use monad transformers to elegantly build up computations with various effects. [http://cale.yi.org/index.php/How_To_Use_Monad_Transformers Cale Gibbard’s article] on how to use monad transformers is more practical, describing how to structure code using monad transformers to make writing it as painless as possible. Another good starting place for learning about monad transformers is a [http://blog.sigfpe.com/2006/05/grok-haskell-monad-transformers.html blog post by Dan Piponi].<br />
<br />
The <code>ListT</code> transformer from the <code>transformers</code> package comes with the caveat that <code>ListT m</code> is only a monad when <code>m</code> is ''commutative'', that is, when <code>ma >>= \a -> mb >>= \b -> foo</code> is equivalent to <code>mb >>= \b -> ma >>= \a -> foo</code> (i.e. the order of <code>m</code>'s effects does not matter). For one explanation why, see Dan Piponi's blog post [http://blog.sigfpe.com/2006/11/why-isnt-listt-monad.html "Why isn't <code><nowiki>ListT []</nowiki></code> a monad"]. For more examples, as well as a design for a version of <code>ListT</code> which does not have this problem, see [http://haskell.org/haskellwiki/ListT_done_right <code>ListT</code> done right].<br />
<br />
There is an alternative way to compose monads, using coproducts, as described by [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.8.3581 Lüth and Ghani]. This method is interesting but has not (yet?) seen widespread use.<br />
<br />
=MonadFix=<br />
<br />
''Note: <code>MonadFix</code> is included here for completeness (and because it is interesting) but seems not to be used much. Skipping this section on a first read-through is perfectly OK (and perhaps even recommended).''<br />
<br />
==<code>do rec</code> notation==<br />
<br />
The <code>MonadFix</code> class describes monads which support the special fixpoint operation <code>mfix :: (a -> m a) -> m a</code>, which allows the output of monadic computations to be defined via (effectful) recursion. This is [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#recursive-do-notation supported in GHC] by a special “recursive do” notation, enabled by the <code>-XDoRec</code> flag. Within a <code>do</code> block, one may have a nested <code>rec</code> block, like so:<br />
<haskell><br />
do { x <- foo<br />
; rec { y <- baz<br />
; z <- bar<br />
; bob<br />
}<br />
; w <- frob<br />
}<br />
</haskell><br />
Normally (if we had <code>do</code> in place of <code>rec</code> in the above example), <code>y</code> would be in scope in <code>bar</code> and <code>bob</code> but not in <code>baz</code>, and <code>z</code> would be in scope only in <code>bob</code>. With the <code>rec</code>, however, <code>y</code> and <code>z</code> are both in scope in all three of <code>baz</code>, <code>bar</code>, and <code>bob</code>. A <code>rec</code> block is analogous to a <code>let</code> block such as<br />
<haskell><br />
let { y = baz<br />
; z = bar<br />
}<br />
in bob<br />
</haskell><br />
because, in Haskell, every variable bound in a <code>let</code>-block is in scope throughout the entire block. (From this point of view, Haskell's normal <code>do</code> blocks are analogous to Scheme's <code>let*</code> construct.)<br />
<br />
What could such a feature be used for? One of the motivating examples given in the original paper describing <code>MonadFix</code> (see below) is encoding circuit descriptions. A line in a <code>do</code>-block such as <br />
<haskell><br />
x <- gate y z<br />
</haskell><br />
describes a gate whose input wires are labeled <code>y</code> and <code>z</code> and whose output wire is labeled <code>x</code>. Many (most?) useful circuits, however, involve some sort of feedback loop, making them impossible to write in a normal <code>do</code>-block (since some wire would have to be mentioned as an input ''before'' being listed as an output). Using a <code>rec</code> block solves this problem.<br />
<br />
==Examples and intuition==<br />
<br />
Of course, not every monad supports such recursive binding. However, as mentioned above, it suffices to have an implementation of <code>mfix :: (a -> m a) -> m a</code>, satisfying a few laws. Let's try implementing <code>mfix</code> for the <code>Maybe</code> monad. That is, we want to implement a function<br />
<haskell><br />
maybeFix :: (a -> Maybe a) -> Maybe a<br />
</haskell><br />
{{note|Actually, <code>fix</code> is implemented slightly differently for efficiency reasons; but the given definition is equivalent and simpler for the present purpose.}}<br />
Let's think for a moment about the implementation {{noteref}} of the non-monadic <code>fix :: (a -> a) -> a</code>:<br />
<haskell><br />
fix f = f (fix f)<br />
</haskell><br />
Inspired by <code>fix</code>, our first attempt at implementing <code>maybeFix</code> might be something like<br />
<haskell><br />
maybeFix :: (a -> Maybe a) -> Maybe a<br />
maybeFix f = maybeFix f >>= f<br />
</haskell><br />
This has the right type. However, something seems wrong: there is nothing in particular here about <code>Maybe</code>; <code>maybeFix</code> actually has the more general type <code>Monad m => (a -> m a) -> m a</code>. But didn't we just say that not all monads support <code>mfix</code>?<br />
<br />
The answer is that although this implementation of <code>maybeFix</code> has the right type, it does ''not'' have the intended semantics. If we think about how <code>(>>=)</code> works for the <code>Maybe</code> monad (by pattern-matching on its first argument to see whether it is <code>Nothing</code> or <code>Just</code>) we can see that this definition of <code>maybeFix</code> is completely useless: it will just recurse infinitely, trying to decide whether it is going to return <code>Nothing</code> or <code>Just</code>, without ever even so much as a glance in the direction of <code>f</code>.<br />
<br />
The trick is to simply ''assume'' that <code>maybeFix</code> will return <code>Just</code>, and get on with life!<br />
<haskell><br />
maybeFix :: (a -> Maybe a) -> Maybe a<br />
maybeFix f = ma<br />
where ma = f (fromJust ma)<br />
</haskell><br />
This says that the result of <code>maybeFix</code> is <code>ma</code>, and assuming that <code>ma = Just x</code>, it is defined (recursively) to be equal to <code>f x</code>.<br />
<br />
Why is this OK? Isn't <code>fromJust</code> almost as bad as <code>unsafePerformIO</code>? Well, usually, yes. This is just about the only situation in which it is justified! The interesting thing to note is that <code>maybeFix</code> ''will never crash'' -- although it may, of course, fail to terminate. The only way we could get a crash is if we try to evaluate <code>fromJust ma</code> when we know that <code>ma = Nothing</code>. But how could we know <code>ma = Nothing</code>? Since <code>ma</code> is defined as <code>f (fromJust ma)</code>, it must be that this expression has already been evaluated to <code>Nothing</code> -- in which case there is no reason for us to be evaluating <code>fromJust ma</code> in the first place! <br />
<br />
To see this from another point of view, we can consider three possibilities. First, if <code>f</code> outputs <code>Nothing</code> without looking at its argument, then <code>maybeFix f</code> clearly returns <code>Nothing</code>. Second, if <code>f</code> always outputs <code>Just x</code>, where <code>x</code> depends on its argument, then the recursion can proceed usefully: <code>fromJust ma</code> will be able to evaluate to <code>x</code>, thus feeding <code>f</code>'s output back to it as input. Third, if <code>f</code> tries to use its argument to decide whether to output <code>Just</code> or <code>Nothing</code>, then <code>maybeFix f</code> will not terminate: evaluating <code>f</code>'s argument requires evaluating <code>ma</code> to see whether it is <code>Just</code>, which requires evaluating <code>f (fromJust ma)</code>, which requires evaluating <code>ma</code>, ... and so on.<br />
<br />
There are also instances of <code>MonadFix</code> for lists (which works analogously to the instance for <code>Maybe</code>), for <code>ST</code>, and for <code>IO</code>. The [http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/System-IO.html#fixIO instance for <code>IO</code>] is particularly amusing: it creates a new <code>IORef</code> (with a dummy value), immediately reads its contents using <code>unsafeInterleaveIO</code> (which delays the actual reading lazily until the value is needed), uses the contents of the <code>IORef</code> to compute a new value, which it then writes back into the <code>IORef</code>. It almost seems, spookily, that <code>mfix</code> is sending a value back in time to itself through the <code>IORef</code> -- though of course what is really going on is that the reading is delayed just long enough (via <code>unsafeInterleaveIO</code>) to get the process bootstrapped.<br />
<br />
{{Exercises|<br />
* Implement a <code>MonadFix</code> instance for <code>[]</code>.<br />
}}<br />
<br />
==Further reading==<br />
<br />
For more information (such as the precise desugaring rules for <code>rec</code> blocks), see Levent Erkök and John Launchbury's 2002 Haskell workshop paper, [http://sites.google.com/site/leventerkok/recdo.pdf?attredirects=0 A Recursive do for Haskell], or for full details, Levent Erkök’s thesis, [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.15.1543&rep=rep1&type=pdf Value Recursion in Monadic Computations]. (Note, while reading, that <code>do rec</code> used to be called <code>mdo</code>, and <code>MonadFix</code> used to be called <code>MonadRec</code>.)<br />
<br />
=Semigroup=<br />
<br />
A semigroup is a set <math>S\ </math> together with a binary operation <math>\oplus\ </math> which<br />
combines elements from <math>S\ </math>. The <math>\oplus\ </math> operator is required to be associative<br />
(that is, <math>(a \oplus b) \oplus c = a \oplus (b \oplus c)\ </math>, for any<br />
<math>a,b,c\ </math> which are elements of <math>S\ </math>).<br />
<br />
For example, the natural numbers under addition form a semigroup: the sum of any two natural numbers is a natural number, and <math>(a+b)+c = a+(b+c)\ </math> for any natural numbers <math>a\ </math>, <math>b\ </math>, and <math>c\,\ </math>. The integers under multiplication also form a semigroup, as do the integers (or rationals, or reals) under <math>\max\ </math> or <math>\min\ </math>, Boolean values under conjunction and disjunction, lists under concatenation, functions from a set to itself under composition ... Semigroups show up all over the place, once you know to look for them.<br />
<br />
Under construction, more coming soon...<br />
<br />
=Monoid=<br />
<br />
Many semigroups have a special element <math>e</math> for which the binary operation <math>\oplus</math> is the identity, that is, <math>e \oplus x = x \oplus e = x</math> for every element <math>x</math>. Such a semigroup-with-identity-element is called a ''monoid''.<br />
<br />
==Definition==<br />
<br />
The definition of the <code>Monoid</code> type class (defined in<br />
<code>Data.Monoid</code>; [http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html haddock]) is:<br />
<br />
<haskell><br />
class Monoid a where<br />
mempty :: a<br />
mappend :: a -> a -> a<br />
<br />
mconcat :: [a] -> a<br />
mconcat = foldr mappend mempty<br />
</haskell><br />
<br />
The <code>mempty</code> value specifies the identity element of the monoid, and <code>mappend</code><br />
is the binary operation. The default definition for <code>mconcat</code><br />
“reduces” a list of elements by combining them all with <code>mappend</code>,<br />
using a right fold. It is only in the <code>Monoid</code> class so that specific<br />
instances have the option of providing an alternative, more efficient<br />
implementation; usually, you can safely ignore <code>mconcat</code> when creating<br />
a <code>Monoid</code> instance, since its default definition will work just fine.<br />
<br />
The <code>Monoid</code> methods are rather unfortunately named; they are inspired<br />
by the list instance of <code>Monoid</code>, where indeed <code>mempty = []</code> and <code>mappend = (++)</code>, but this is misleading since many<br />
monoids have little to do with appending (see these [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/50590 Comments from OCaml Hacker Brian Hurt] on the haskell-cafe mailing list).<br />
<br />
==Laws==<br />
<br />
Of course, every <code>Monoid</code> instance should actually be a monoid in the<br />
mathematical sense, which implies these laws:<br />
<br />
<haskell><br />
mempty `mappend` x = x<br />
x `mappend` mempty = x<br />
(x `mappend` y) `mappend` z = x `mappend` (y `mappend` z)<br />
</haskell><br />
<br />
==Instances==<br />
<br />
There are quite a few interesting <code>Monoid</code> instances defined in <code>Data.Monoid</code>.<br />
<br />
<ul><br />
<li><code>[a]</code> is a <code>Monoid</code>, with <code>mempty = []</code> and <code>mappend = (++)</code>. It is not hard to check that <code>(x ++ y) ++ z = x ++ (y ++ z)</code> for any lists <code>x</code>, <code>y</code>, and <code>z</code>, and that the empty list is the identity: <code>[] ++ x = x ++ [] = x</code>.</li><br />
<br />
<li>As noted previously, we can make a monoid out of any numeric type under either addition or multiplication. However, since we can’t have two instances for the same type, <code>Data.Monoid</code> provides two <code>newtype</code> wrappers, <code>Sum</code> and <code>Product</code>, with appropriate <code>Monoid</code> instances.<br />
<br />
<haskell><br />
> getSum (mconcat . map Sum $ [1..5])<br />
15<br />
> getProduct (mconcat . map Product $ [1..5])<br />
120<br />
</haskell><br />
<br />
This example code is silly, of course; we could just write<br />
<code>sum [1..5]</code> and <code>product [1..5]</code>. Nevertheless, these instances are useful in more generalized settings, as we will see in the [[Foldable|section <code>Foldable</code>]].</li><br />
<br />
<li><code>Any</code> and <code>All</code> are <code>newtype</code> wrappers providing <code>Monoid</code> instances for <code>Bool</code> (under disjunction and conjunction, respectively).</li><br />
<br />
<li> There are three instances for <code>Maybe</code>: a basic instance which lifts a <code>Monoid</code> instance for <code>a</code> to an instance for <code>Maybe a</code>, and two <code>newtype</code> wrappers <code>First</code> and <code>Last</code> for which <code>mappend</code> selects the first (respectively last) non-<code>Nothing</code> item.</li><br />
<br />
<li><code>Endo a</code> is a newtype wrapper for functions <code>a -> a</code>, which form a monoid under composition.</li><br />
<br />
<li>There are several ways to “lift” <code>Monoid</code> instances to instances with additional structure. We have already seen that an instance for <code>a</code> can be lifted to an instance for <code>Maybe a</code>. There are also tuple instances: if <code>a</code> and <code>b</code> are instances of <code>Monoid</code>, then so is <code>(a,b)</code>, using the monoid operations for <code>a</code> and <code>b</code> in the obvious pairwise manner. Finally, if <code>a</code> is a <code>Monoid</code>, then so is the function type <code>e -> a</code> for any <code>e</code>; in particular, <code>g `mappend` h</code> is the function which applies both <code>g</code> and <code>h</code> to its argument and then combines the results using the underlying <code>Monoid</code> instance for <code>a</code>. This can be quite useful and elegant (see [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/52416 example]).</li><br />
<br />
<li>The type <code>Ordering = LT || EQ || GT</code> is a <code>Monoid</code>, defined in such a way that <code>mconcat (zipWith compare xs ys)</code> computes the lexicographic ordering of <code>xs</code> and <code>ys</code> (if <code>xs</code> and <code>ys</code> have the same length). In particular, <code>mempty = EQ</code>, and <code>mappend</code> evaluates to its leftmost non-<code>EQ</code> argument (or <code>EQ</code> if both arguments are <code>EQ</code>). This can be used together with the function instance of <code>Monoid</code> to do some clever things ([http://www.reddit.com/r/programming/comments/7cf4r/monoids_in_my_programming_language/c06adnx example]).</li><br />
<br />
<li>There are also <code>Monoid</code> instances for several standard data structures in the containers library ([http://hackage.haskell.org/packages/archive/containers/0.2.0.0/doc/html/index.html haddock]), including <code>Map</code>, <code>Set</code>, and <code>Sequence</code>.</li><br />
</ul><br />
<br />
<code>Monoid</code> is also used to enable several other type class instances.<br />
As noted previously, we can use <code>Monoid</code> to make <code>((,) e)</code> an instance of <code>Applicative</code>:<br />
<br />
<haskell><br />
instance Monoid e => Applicative ((,) e) where<br />
pure x = (mempty, x)<br />
(u, f) <*> (v, x) = (u `mappend` v, f x)<br />
</haskell><br />
<br />
<code>Monoid</code> can be similarly used to make <code>((,) e)</code> an instance of <code>Monad</code> as well; this is known as the ''writer monad''. As we’ve already seen, <code>Writer</code> and <code>WriterT</code> are a newtype wrapper and transformer for this monad, respectively.<br />
<br />
<code>Monoid</code> also plays a key role in the <code>Foldable</code> type class (see section [[#Foldable|Foldable]]).<br />
<br />
==Other monoidal classes: Alternative, MonadPlus, ArrowPlus==<br />
<br />
The <code>Alternative</code> type class ([http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#g:2 haddock])<br />
is for <code>Applicative</code> functors which also have<br />
a monoid structure:<br />
<br />
<haskell><br />
class Applicative f => Alternative f where<br />
empty :: f a<br />
(<|>) :: f a -> f a -> f a<br />
</haskell><br />
<br />
Of course, instances of <code>Alternative</code> should satisfy the monoid laws.<br />
<br />
Likewise, <code>MonadPlus</code> ([http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html#t:MonadPlus haddock])<br />
is for <code>Monad</code>s with a monoid structure:<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 />
<br />
The <code>MonadPlus</code> documentation states that it is intended to model<br />
monads which also support “choice and failure”; in addition to the<br />
monoid laws, instances of <code>MonadPlus</code> are expected to satisfy<br />
<br />
<haskell><br />
mzero >>= f = mzero<br />
v >> mzero = mzero<br />
</haskell><br />
<br />
which explains the sense in which <code>mzero</code> denotes failure. Since<br />
<code>mzero</code> should be the identity for <code>mplus</code>, the computation <code>m1 `mplus` m2</code> succeeds (evaluates to something other than <code>mzero</code>) if<br />
either <code>m1</code> or <code>m2</code> does; so <code>mplus</code> represents choice. The <code>guard</code><br />
function can also be used with instances of <code>MonadPlus</code>; it requires a<br />
condition to be satisfied and fails (using <code>mzero</code>) if it is not. A<br />
simple example of a <code>MonadPlus</code> instance is <code>[]</code>, which is exactly the<br />
same as the <code>Monoid</code> instance for <code>[]</code>: the empty list represents<br />
failure, and list concatenation represents choice. In general,<br />
however, a <code>MonadPlus</code> instance for a type need not be the same as its<br />
<code>Monoid</code> instance; <code>Maybe</code> is an example of such a type. A great<br />
introduction to the <code>MonadPlus</code> type class, with interesting examples<br />
of its use, is Doug Auclair’s ''MonadPlus: What a Super Monad!'' in [http://www.haskell.org/wikiupload/6/6a/TMR-Issue11.pdf the Monad.Reader issue 11].<br />
<br />
There used to be a type class called <code>MonadZero</code> containing only<br />
<code>mzero</code>, representing monads with failure. The <code>do</code>-notation requires<br />
some notion of failure to deal with failing pattern matches.<br />
Unfortunately, <code>MonadZero</code> was scrapped in favor of adding the <code>fail</code><br />
method to the <code>Monad</code> class. If we are lucky, someday <code>MonadZero</code> will<br />
be restored, and <code>fail</code> will be banished to the bit bucket where it<br />
belongs (see [[MonadPlus reform proposal]]). The idea is that any<br />
<code>do</code>-block which uses pattern matching (and hence may fail) would require<br />
a <code>MonadZero</code> constraint; otherwise, only a <code>Monad</code> constraint would be<br />
required.<br />
<br />
Finally, <code>ArrowZero</code> and <code>ArrowPlus</code> ([http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#t:ArrowZero haddock])<br />
represent <code>Arrow</code>s ([[#Arrow|see below]]) with a<br />
monoid structure:<br />
<br />
<haskell><br />
class Arrow (~>) => ArrowZero (~>) where<br />
zeroArrow :: b ~> c<br />
<br />
class ArrowZero (~>) => ArrowPlus (~>) where<br />
(<+>) :: (b ~> c) -> (b ~> c) -> (b ~> c)<br />
</haskell><br />
<br />
==Further reading==<br />
<br />
Monoids have gotten a fair bit of attention recently, ultimately due<br />
to<br />
[http://enfranchisedmind.com/blog/posts/random-thoughts-on-haskell/ a blog post by Brian Hurt], in which he<br />
complained about the fact that the names of many Haskell type classes<br />
(<code>Monoid</code> in particular) are taken from abstract mathematics. This<br />
resulted in [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/50590 a long haskell-cafe thread]<br />
arguing the point and discussing monoids in general.<br />
<br />
{{note|May its name live forever.}}<br />
<br />
However, this was quickly followed by several blog posts about<br />
<code>Monoid</code> {{noteref}}. First, Dan Piponi<br />
wrote a great introductory post, [http://blog.sigfpe.com/2009/01/haskell-monoids-and-their-uses.html Haskell Monoids and their Uses]. This was quickly followed by<br />
Heinrich Apfelmus’s [http://apfelmus.nfshost.com/monoid-fingertree.html Monoids and Finger Trees], an accessible exposition of<br />
Hinze and Paterson’s [http://www.soi.city.ac.uk/%7Eross/papers/FingerTree.html classic paper on 2-3 finger trees], which makes very clever<br />
use of <code>Monoid</code> to implement an elegant and generic data structure.<br />
Dan Piponi then wrote two fascinating articles about using <code>Monoids</code><br />
(and finger trees): [http://blog.sigfpe.com/2009/01/fast-incremental-regular-expression.html Fast Incremental Regular Expressions] and [http://blog.sigfpe.com/2009/01/beyond-regular-expressions-more.html Beyond Regular Expressions]<br />
<br />
In a similar vein, David Place’s article on improving <code>Data.Map</code> in<br />
order to compute incremental folds (see [http://www.haskell.org/sitewiki/images/6/6a/TMR-Issue11.pdf the Monad Reader issue 11])<br />
is also a<br />
good example of using <code>Monoid</code> to generalize a data structure.<br />
<br />
Some other interesting examples of <code>Monoid</code> use include [http://www.reddit.com/r/programming/comments/7cf4r/monoids_in_my_programming_language/c06adnx building elegant list sorting combinators],<br />
[http://byorgey.wordpress.com/2008/04/17/collecting-unstructured-information-with-the-monoid-of-partial-knowledge/ collecting unstructured information],<br />
and a brilliant series of posts by Chung-Chieh Shan and Dylan Thurston<br />
using <code>Monoid</code>s to [http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers1/ elegantly solve a difficult combinatorial puzzle] (followed by<br />
[http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers2/ part 2],<br />
[http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers3/ part 3],<br />
[http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers4/ part 4]).<br />
<br />
As unlikely as it sounds, monads can actually be viewed as a sort of<br />
monoid, with <code>join</code> playing the role of the binary operation and<br />
<code>return</code> the role of the identity; see [http://blog.sigfpe.com/2008/11/from-monoids-to-monads.html Dan Piponi’s blog post].<br />
<br />
=Foldable=<br />
<br />
The <code>Foldable</code> class, defined in the <code>Data.Foldable</code><br />
module ([http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Foldable.html haddock]), abstracts over containers which can be<br />
“folded” into a summary value. This allows such folding operations<br />
to be written in a container-agnostic way.<br />
<br />
==Definition==<br />
<br />
The definition of the <code>Foldable</code> type class is:<br />
<br />
<haskell><br />
class Foldable t where<br />
fold :: Monoid m => t m -> m<br />
foldMap :: Monoid m => (a -> m) -> t a -> m<br />
<br />
foldr :: (a -> b -> b) -> b -> t a -> b<br />
foldl :: (a -> b -> a) -> a -> t b -> a<br />
foldr1 :: (a -> a -> a) -> t a -> a<br />
foldl1 :: (a -> a -> a) -> t a -> a<br />
</haskell><br />
<br />
This may look complicated, but in fact, to make a <code>Foldable</code> instance<br />
you only need to implement one method: your choice of <code>foldMap</code> or<br />
<code>foldr</code>. All the other methods have default implementations in terms<br />
of these, and are presumably included in the class in case more<br />
efficient implementations can be provided.<br />
<br />
==Instances and examples==<br />
<br />
The type of <code>foldMap</code> should make it clear what it is supposed to do:<br />
given a way to convert the data in a container into a <code>Monoid</code> (a<br />
function <code>a -> m</code>) and a container of <code>a</code>’s (<code>t a</code>), <code>foldMap</code><br />
provides a way to iterate over the entire contents of the container,<br />
converting all the <code>a</code>’s to <code>m</code>’s and combining all the <code>m</code>’s with<br />
<code>mappend</code>. The following code shows two examples: a simple<br />
implementation of <code>foldMap</code> for lists, and a binary tree example<br />
provided by the <code>Foldable</code> documentation.<br />
<br />
<haskell><br />
instance Foldable [] where<br />
foldMap g = mconcat . map g<br />
<br />
data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)<br />
<br />
instance Foldable Tree where<br />
foldMap f Empty = mempty<br />
foldMap f (Leaf x) = f x<br />
foldMap f (Node l k r) = foldMap f l ++ f k ++ foldMap f r<br />
where (++) = mappend<br />
</haskell><br />
<br />
The <code>foldr</code> function has a type similar to the <code>foldr</code> found in the <code>Prelude</code>, but<br />
more general, since the <code>foldr</code> in the <code>Prelude</code> works only on lists.<br />
<br />
The <code>Foldable</code> module also provides instances for <code>Maybe</code> and <code>Array</code>;<br />
additionally, many of the data structures found in the standard [http://hackage.haskell.org/package/containers containers library] (for example, <code>Map</code>, <code>Set</code>, <code>Tree</code>,<br />
and <code>Sequence</code>) provide their own <code>Foldable</code> instances.<br />
<br />
==Derived folds==<br />
<br />
Given an instance of <code>Foldable</code>, we can write generic,<br />
container-agnostic functions such as:<br />
<br />
<haskell><br />
-- Compute the size of any container.<br />
containerSize :: Foldable f => f a -> Int<br />
containerSize = getSum . foldMap (const (Sum 1))<br />
<br />
-- Compute a list of elements of a container satisfying a predicate.<br />
filterF :: Foldable f => (a -> Bool) -> f a -> [a]<br />
filterF p = foldMap (\a -> if p a then [a] else [])<br />
<br />
-- Get a list of all the Strings in a container which include the<br />
-- letter a.<br />
aStrings :: Foldable f => f String -> [String]<br />
aStrings = filterF (elem 'a')<br />
</haskell><br />
<br />
The <code>Foldable</code> module also provides a large number of predefined<br />
folds, many of which are generalized versions of <code>Prelude</code> functions of the<br />
same name that only work on lists: <code>concat</code>, <code>concatMap</code>, <code>and</code>,<br />
<code>or</code>, <code>any</code>, <code>all</code>, <code>sum</code>, <code>product</code>, <code>maximum</code>(<code>By</code>),<br />
<code>minimum</code>(<code>By</code>), <code>elem</code>, <code>notElem</code>, and <code>find</code>. The reader may enjoy<br />
coming up with elegant implementations of these functions using <code>fold</code><br />
or <code>foldMap</code> and appropriate <code>Monoid</code> instances.<br />
<br />
There are also generic functions that work with <code>Applicative</code> or<br />
<code>Monad</code> instances to generate some sort of computation from each<br />
element in a container, and then perform all the side effects from<br />
those computations, discarding the results: <code>traverse_</code>, <code>sequenceA_</code>,<br />
and others. The results must be discarded because the <code>Foldable</code><br />
class is too weak to specify what to do with them: we cannot, in<br />
general, make an arbitrary <code>Applicative</code> or <code>Monad</code> instance into a<br />
<code>Monoid</code>. If we do have an <code>Applicative</code> or <code>Monad</code> with a monoid<br />
structure—that is, an <code>Alternative</code> or a <code>MonadPlus</code>—then we can<br />
use the <code>asum</code> or <code>msum</code> functions, which can combine the results as<br />
well. Consult the [http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Foldable.html <code>Foldable</code> documentation] for<br />
more details on any of these functions.<br />
<br />
Note that the <code>Foldable</code> operations always forget the structure of<br />
the container being folded. If we start with a container of type <code>t a</code> for some <code>Foldable t</code>, then <code>t</code> will never appear in the output<br />
type of any operations defined in the <code>Foldable</code> module. Many times<br />
this is exactly what we want, but sometimes we would like to be able<br />
to generically traverse a container while preserving its<br />
structure—and this is exactly what the <code>Traversable</code> class provides,<br />
which will be discussed in the next section.<br />
<br />
==Further reading==<br />
<br />
The <code>Foldable</code> class had its genesis in [http://www.soi.city.ac.uk/~ross/papers/Applicative.html McBride and Paterson’s paper]<br />
introducing <code>Applicative</code>, although it has<br />
been fleshed out quite a bit from the form in the paper.<br />
<br />
An interesting use of <code>Foldable</code> (as well as <code>Traversable</code>) can be<br />
found in Janis Voigtländer’s paper [http://doi.acm.org/10.1145/1480881.1480904 Bidirectionalization for free!].<br />
<br />
=Traversable=<br />
<br />
==Definition==<br />
<br />
The <code>Traversable</code> type class, defined in the <code>Data.Traversable</code><br />
module ([http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Traversable.html haddock]), is:<br />
<br />
<haskell><br />
class (Functor t, Foldable t) => Traversable t where<br />
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)<br />
sequenceA :: Applicative f => t (f a) -> f (t a)<br />
mapM :: Monad m => (a -> m b) -> t a -> m (t b)<br />
sequence :: Monad m => t (m a) -> m (t a)<br />
</haskell><br />
<br />
As you can see, every <code>Traversable</code> is also a foldable functor. Like<br />
<code>Foldable</code>, there is a lot in this type class, but making instances is<br />
actually rather easy: one need only implement <code>traverse</code> or<br />
<code>sequenceA</code>; the other methods all have default implementations in<br />
terms of these functions. A good exercise is to figure out what the default<br />
implementations should be: given either <code>traverse</code> or <code>sequenceA</code>, how<br />
would you define the other three methods? (Hint for <code>mapM</code>:<br />
<code>Control.Applicative</code> exports the <code>WrapMonad</code> newtype, which makes any<br />
<code>Monad</code> into an <code>Applicative</code>. The <code>sequence</code> function can be implemented in terms<br />
of <code>mapM</code>.)<br />
<br />
==Intuition==<br />
<br />
The key method of the <code>Traversable</code> class, and the source of its<br />
unique power, is <code>sequenceA</code>. Consider its type:<br />
<haskell><br />
sequenceA :: Applicative f => t (f a) -> f (t a)<br />
</haskell><br />
This answers the fundamental question: when can we commute two<br />
functors? For example, can we turn a tree of lists into a list of<br />
trees? (Answer: yes, in two ways. Figuring out what they are, and<br />
why, is left as an exercise. A much more challenging question is<br />
whether a list of trees can be turned into a tree of lists.)<br />
<br />
The ability to compose two monads depends crucially on this ability to<br />
commute functors. Intuitively, if we want to build a composed monad<br />
<code>M a = m (n a)</code> out of monads <code>m</code> and <code>n</code>, then to be able to<br />
implement <code>join :: M (M a) -> M a</code>, that is,<br />
<code>join :: m (n (m (n a))) -> m (n a)</code>, we have to be able to commute<br />
the <code>n</code> past the <code>m</code> to get <code>m (m (n (n a)))</code>, and then we can use the<br />
<code>join</code>s for <code>m</code> and <code>n</code> to produce something of type <code>m (n a)</code>. See<br />
[http://web.cecs.pdx.edu/~mpj/pubs/springschool.html Mark Jones’s paper] for more details.<br />
<br />
==Instances and examples==<br />
<br />
What’s an example of a <code>Traversable</code> instance?<br />
The following code shows an example instance for the same<br />
<code>Tree</code> type used as an example in the previous <code>Foldable</code> section. It<br />
is instructive to compare this instance with a <code>Functor</code> instance for<br />
<code>Tree</code>, which is also shown.<br />
<br />
<haskell><br />
data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)<br />
<br />
instance Traversable Tree where<br />
traverse g Empty = pure Empty<br />
traverse g (Leaf x) = Leaf <$> g x<br />
traverse g (Node l x r) = Node <$> traverse g l<br />
<*> g x<br />
<*> traverse g r<br />
<br />
instance Functor Tree where<br />
fmap g Empty = Empty<br />
fmap g (Leaf x) = Leaf $ g x<br />
fmap g (Node l x r) = Node (fmap g l)<br />
(g x)<br />
(fmap g r)<br />
</haskell><br />
<br />
It should be clear that the <code>Traversable</code> and <code>Functor</code> instances for<br />
<code>Tree</code> are almost identical; the only difference is that the <code>Functor</code><br />
instance involves normal function application, whereas the<br />
applications in the <code>Traversable</code> instance take place within an<br />
<code>Applicative</code> context, using <code>(<$>)</code> and <code>(<*>)</code>. In fact, this will<br />
be<br />
true for any type.<br />
<br />
Any <code>Traversable</code> functor is also <code>Foldable</code>, and a <code>Functor</code>. We can see<br />
this not only from the class declaration, but by the fact that we can<br />
implement the methods of both classes given only the <code>Traversable</code><br />
methods. A good exercise is to implement <code>fmap</code> and <code>foldMap</code> using<br />
only the <code>Traversable</code> methods; the implementations are surprisingly<br />
elegant. The <code>Traversable</code> module provides these<br />
implementations as <code>fmapDefault</code> and <code>foldMapDefault</code>.<br />
<br />
The standard libraries provide a number of <code>Traversable</code> instances,<br />
including instances for <code>[]</code>, <code>Maybe</code>, <code>Map</code>, <code>Tree</code>, and <code>Sequence</code>.<br />
Notably, <code>Set</code> is not <code>Traversable</code>, although it is <code>Foldable</code>.<br />
<br />
==Further reading==<br />
<br />
The <code>Traversable</code> class also had its genesis in [http://www.soi.city.ac.uk/~ross/papers/Applicative.html McBride and Paterson’s <code>Applicative</code> paper],<br />
and is described in more detail in Gibbons and Oliveira, [http://www.comlab.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf The Essence of the Iterator Pattern],<br />
which also contains a wealth of references to related work.<br />
<br />
=Category=<br />
<br />
<code>Category</code> is another fairly new addition to the Haskell standard<br />
libraries; you may or may not have it installed depending on the<br />
version of your <code>base</code> package. It generalizes the notion of<br />
function composition to general “morphisms”.<br />
<br />
The definition of the <code>Category</code> type class (from<br />
<code>Control.Category</code>—[http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Category.html haddock]) is shown below. For ease of reading, note that I have used an<br />
infix type constructor <code>(~>)</code>, much like the infix function type<br />
constructor <code>(->)</code>. This syntax is not part of Haskell 98.<br />
The second definition shown is the one used in the standard libraries.<br />
For the remainder of this document, I will use the infix type<br />
constructor <code>(~>)</code> for <code>Category</code> as well as <code>Arrow</code>.<br />
<br />
<haskell><br />
class Category (~>) where<br />
id :: a ~> a<br />
(.) :: (b ~> c) -> (a ~> b) -> (a ~> c)<br />
<br />
-- The same thing, with a normal (prefix) type constructor<br />
class Category cat where<br />
id :: cat a a<br />
(.) :: cat b c -> cat a b -> cat a c<br />
</haskell><br />
<br />
Note that an instance of <code>Category</code> should be a type constructor which<br />
takes two type arguments, that is, something of kind <code>* -> * -> *</code>. It<br />
is instructive to imagine the type constructor variable <code>cat</code> replaced<br />
by the function constructor <code>(->)</code>: indeed, in this case we recover<br />
precisely the familiar identity function <code>id</code> and function composition<br />
operator <code>(.)</code> defined in the standard <code>Prelude</code>.<br />
<br />
Of course, the <code>Category</code> module provides exactly such an instance of<br />
<code>Category</code> for <code>(->)</code>. But it also provides one other instance, shown<br />
below, which should be familiar from the<br />
previous discussion of the <code>Monad</code> laws. <code>Kleisli m a b</code>, as defined<br />
in the <code>Control.Arrow</code> module, is just a <code>newtype</code> wrapper around <code>a -> m b</code>.<br />
<br />
<haskell><br />
newtype Kleisli m a b = Kleisli { runKleisli :: a -> m b }<br />
<br />
instance Monad m => Category (Kleisli m) where<br />
id = Kleisli return<br />
Kleisli g . Kleisli h = Kleisli (h >=> g)<br />
</haskell><br />
<br />
The only law that <code>Category</code> instances should satisfy is that <code>id</code> and<br />
<code>(.)</code> should form a monoid—that is, <code>id</code> should be the identity of<br />
<code>(.)</code>, and <code>(.)</code> should be associative.<br />
<br />
Finally, the <code>Category</code> module exports two additional operators:<br />
<code>(<<<)</code>, which is just a synonym for <code>(.)</code>, and <code>(>>>)</code>, which is<br />
<code>(.)</code> with its arguments reversed. (In previous versions of the<br />
libraries, these operators were defined as part of the <code>Arrow</code> class.)<br />
<br />
==Further reading==<br />
<br />
The name <code>Category</code> is a bit misleading, since the <code>Category</code> class<br />
cannot represent arbitrary categories, but only categories whose<br />
objects are objects of <code>Hask</code>, the category of Haskell types. For a<br />
more general treatment of categories within Haskell, see the<br />
[http://hackage.haskell.org/package/category-extras category-extras package]. For more about<br />
category theory in general, see the excellent [http://en.wikibooks.org/wiki/Haskell/Category_theory Haskell wikibook page],<br />
[http://books.google.com/books/about/Category_theory.html?id=-MCJ6x2lC7oC Steve Awodey’s new book],<br />
Benjamin Pierce’s<br />
[http://books.google.com/books/about/Basic_category_theory_for_computer_scien.html?id=ezdeaHfpYPwC Basic category theory for computer scientists], or<br />
[http://folli.loria.fr/cds/1999/esslli99/courses/barr-wells.html Barr and Wells’s category theory lecture notes]. [http://dekudekuplex.wordpress.com/2009/01/19/motivating-learning-category-theory-for-non-mathematicians/ Benjamin Russell’s blog post]<br />
is another good source of motivation and<br />
category theory links. You certainly don’t need to know any category<br />
theory to be a successful and productive Haskell programmer, but it<br />
does lend itself to much deeper appreciation of Haskell’s underlying<br />
theory.<br />
<br />
=Arrow=<br />
<br />
The <code>Arrow</code> class represents another abstraction of computation, in a<br />
similar vein to <code>Monad</code> and <code>Applicative</code>. However, unlike <code>Monad</code><br />
and <code>Applicative</code>, whose types only reflect their output, the type of<br />
an <code>Arrow</code> computation reflects both its input and output. Arrows<br />
generalize functions: if <code>(~>)</code> is an instance of <code>Arrow</code>, a value of<br />
type <code>b ~> c</code> can be thought of as a computation which takes values of<br />
type <code>b</code> as input, and produces values of type <code>c</code> as output. In the<br />
<code>(->)</code> instance of <code>Arrow</code> this is just a pure function; in general, however,<br />
an arrow may represent some sort of “effectful” computation.<br />
<br />
==Definition==<br />
<br />
The definition of the <code>Arrow</code> type class, from<br />
<code>Control.Arrow</code> ([http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html haddock]), is:<br />
<br />
<haskell><br />
class Category (~>) => Arrow (~>) where<br />
arr :: (b -> c) -> (b ~> c)<br />
first :: (b ~> c) -> ((b, d) ~> (c, d))<br />
second :: (b ~> c) -> ((d, b) ~> (d, c))<br />
(***) :: (b ~> c) -> (b' ~> c') -> ((b, b') ~> (c, c'))<br />
(&&&) :: (b ~> c) -> (b ~> c') -> (b ~> (c, c'))<br />
</haskell><br />
<br />
{{note|In versions of the <code>base</code><br />
package prior to version 4, there is no <code>Category</code> class, and the<br />
<code>Arrow</code> class includes the arrow composition operator <code>(>>>)</code>. It<br />
also includes <code>pure</code> as a synonym for <code>arr</code>, but this was removed<br />
since it conflicts with the <code>pure</code> from <code>Applicative</code>.}}<br />
<br />
The first thing to note is the <code>Category</code> class constraint, which<br />
means that we get identity arrows and arrow composition for free:<br />
given two arrows <code>g :: b ~> c</code> and <code>h :: c ~> d</code>, we can form their<br />
composition <code>g >>> h :: b ~> d</code> {{noteref}}.<br />
<br />
As should be a familiar pattern by now, the only methods which must be<br />
defined when writing a new instance of <code>Arrow</code> are <code>arr</code> and <code>first</code>;<br />
the other methods have default definitions in terms of these, but are<br />
included in the <code>Arrow</code> class so that they can be overridden with more<br />
efficient implementations if desired.<br />
<br />
==Intuition==<br />
<br />
Let’s look at each of the arrow methods in turn. [http://www.haskell.org/arrows/ Ross Paterson’s web page on arrows] has nice diagrams which can help<br />
build intuition.<br />
<br />
* The <code>arr</code> function takes any function <code>b -> c</code> and turns it into a generalized arrow <code>b ~> c</code>. The <code>arr</code> method justifies the claim that arrows generalize functions, since it says that we can treat any function as an arrow. It is intended that the arrow <code>arr g</code> is “pure” in the sense that it only computes <code>g</code> and has no “effects” (whatever that might mean for any particular arrow type).<br />
<br />
* The <code>first</code> method turns any arrow from <code>b</code> to <code>c</code> into an arrow from <code>(b,d)</code> to <code>(c,d)</code>. The idea is that <code>first g</code> uses <code>g</code> to process the first element of a tuple, and lets the second element pass through unchanged. For the function instance of <code>Arrow</code>, of course, <code>first g (x,y) = (g x, y)</code>.<br />
<br />
* The <code>second</code> function is similar to <code>first</code>, but with the elements of the tuples swapped. Indeed, it can be defined in terms of <code>first</code> using an auxiliary function <code>swap</code>, defined by <code>swap (x,y) = (y,x)</code>.<br />
<br />
* The <code>(***)</code> operator is “parallel composition” of arrows: it takes two arrows and makes them into one arrow on tuples, which has the behavior of the first arrow on the first element of a tuple, and the behavior of the second arrow on the second element. The mnemonic is that <code>g *** h</code> is the ''product'' (hence <code>*</code>) of <code>g</code> and <code>h</code>. For the function instance of <code>Arrow</code>, we define <code>(g *** h) (x,y) = (g x, h y)</code>. The default implementation of <code>(***)</code> is in terms of <code>first</code>, <code>second</code>, and sequential arrow composition <code>(>>>)</code>. The reader may also wish to think about how to implement <code>first</code> and <code>second</code> in terms of <code>(***)</code>.<br />
<br />
* The <code>(&&&)</code> operator is “fanout composition” of arrows: it takes two arrows <code>g</code> and <code>h</code> and makes them into a new arrow <code>g &&& h</code> which supplies its input as the input to both <code>g</code> and <code>h</code>, returning their results as a tuple. The mnemonic is that <code>g &&& h</code> performs both <code>g</code> ''and'' <code>h</code> (hence <code>&</code>) on its input. For functions, we define <code>(g &&& h) x = (g x, h x)</code>.<br />
<br />
==Instances==<br />
<br />
The <code>Arrow</code> library itself only provides two <code>Arrow</code> instances, both<br />
of which we have already seen: <code>(->)</code>, the normal function<br />
constructor, and <code>Kleisli m</code>, which makes functions of<br />
type <code>a -> m b</code> into <code>Arrow</code>s for any <code>Monad m</code>. These instances are:<br />
<br />
<haskell><br />
instance Arrow (->) where<br />
arr g = g<br />
first g (x,y) = (g x, y)<br />
<br />
newtype Kleisli m a b = Kleisli { runKleisli :: a -> m b }<br />
<br />
instance Monad m => Arrow (Kleisli m) where<br />
arr f = Kleisli (return . f)<br />
first (Kleisli f) = Kleisli (\ ~(b,d) -> do c <- f b<br />
return (c,d) )<br />
</haskell><br />
<br />
==Laws==<br />
<br />
{{note|See [http://dx.doi.org/10.1016/S0167-6423(99)00023-4 John Hughes: Generalising monads to arrows]; [http://homepages.inf.ed.ac.uk/wadler/papers/arrows/arrows.pdf Sam Lindley, Philip Wadler, Jeremy Yallop: The arrow calculus]; [http://www.soi.city.ac.uk/~ross/papers/fop.html Ross Paterson: Programming with Arrows].}}<br />
<br />
There are quite a few laws that instances of <code>Arrow</code> should<br />
satisfy {{noteref}}:<br />
<br />
<haskell><br />
arr id = id<br />
arr (h . g) = arr g >>> arr h<br />
first (arr g) = arr (g *** id)<br />
first (g >>> h) = first g >>> first h<br />
first g >>> arr (id *** h) = arr (id *** h) >>> first g<br />
first g >>> arr fst = arr fst >>> g<br />
first (first g) >>> arr assoc = arr assoc >>> first g<br />
<br />
assoc ((x,y),z) = (x,(y,z))<br />
</haskell><br />
<br />
Note that this version of the laws is slightly different than the laws given in the<br />
first two above references, since several of the laws have now been<br />
subsumed by the <code>Category</code> laws (in particular, the requirements that<br />
<code>id</code> is the identity arrow and that <code>(>>>)</code> is associative). The laws<br />
shown here follow those in Paterson’s Programming with Arrows, which uses the<br />
<code>Category</code> class.<br />
<br />
{{note|Unless category-theory-induced insomnolence is your cup of tea.}}<br />
<br />
The reader is advised not to lose too much sleep over the <code>Arrow</code><br />
laws {{noteref}}, since it is not essential to understand them in order to<br />
program with arrows. There are also laws that <code>ArrowChoice</code>,<br />
<code>ArrowApply</code>, and <code>ArrowLoop</code> instances should satisfy; the interested<br />
reader should consult [http://www.soi.city.ac.uk/~ross/papers/fop.html Paterson: Programming with Arrows].<br />
<br />
==ArrowChoice==<br />
<br />
Computations built using the <code>Arrow</code> class, like those built using<br />
the <code>Applicative</code> class, are rather inflexible: the structure of the computation<br />
is fixed at the outset, and there is no ability to choose between<br />
alternate execution paths based on intermediate results.<br />
The <code>ArrowChoice</code> class provides exactly such an ability:<br />
<br />
<haskell><br />
class Arrow (~>) => ArrowChoice (~>) where<br />
left :: (b ~> c) -> (Either b d ~> Either c d)<br />
right :: (b ~> c) -> (Either d b ~> Either d c)<br />
(+++) :: (b ~> c) -> (b' ~> c') -> (Either b b' ~> Either c c')<br />
(|||) :: (b ~> d) -> (c ~> d) -> (Either b c ~> d)<br />
</haskell><br />
<br />
A comparison of <code>ArrowChoice</code> to <code>Arrow</code> will reveal a striking<br />
parallel between <code>left</code>, <code>right</code>, <code>(+++)</code>, <code>(|||)</code> and <code>first</code>,<br />
<code>second</code>, <code>(***)</code>, <code>(&&&)</code>, respectively. Indeed, they are dual:<br />
<code>first</code>, <code>second</code>, <code>(***)</code>, and <code>(&&&)</code> all operate on product types<br />
(tuples), and <code>left</code>, <code>right</code>, <code>(+++)</code>, and <code>(|||)</code> are the<br />
corresponding operations on sum types. In general, these operations<br />
create arrows whose inputs are tagged with <code>Left</code> or <code>Right</code>, and can<br />
choose how to act based on these tags.<br />
<br />
* If <code>g</code> is an arrow from <code>b</code> to <code>c</code>, then <code>left g</code> is an arrow from <code>Either b d</code> to <code>Either c d</code>. On inputs tagged with <code>Left</code>, the <code>left g</code> arrow has the behavior of <code>g</code>; on inputs tagged with <code>Right</code>, it behaves as the identity.<br />
<br />
* The <code>right</code> function, of course, is the mirror image of <code>left</code>. The arrow <code>right g</code> has the behavior of <code>g</code> on inputs tagged with <code>Right</code>.<br />
<br />
* The <code>(+++)</code> operator performs “multiplexing”: <code>g +++ h</code> behaves as <code>g</code> on inputs tagged with <code>Left</code>, and as <code>h</code> on inputs tagged with <code>Right</code>. The tags are preserved. The <code>(+++)</code> operator is the ''sum'' (hence <code>+</code>) of two arrows, just as <code>(***)</code> is the product.<br />
<br />
* The <code>(|||)</code> operator is “merge” or “fanin”: the arrow <code>g ||| h</code> behaves as <code>g</code> on inputs tagged with <code>Left</code>, and <code>h</code> on inputs tagged with <code>Right</code>, but the tags are discarded (hence, <code>g</code> and <code>h</code> must have the same output type). The mnemonic is that <code>g ||| h</code> performs either <code>g</code> ''or'' <code>h</code> on its input.<br />
<br />
The <code>ArrowChoice</code> class allows computations to choose among a finite number of execution paths, based on intermediate results. The possible<br />
execution paths must be known in advance, and explicitly assembled with <code>(+++)</code> or <code>(|||)</code>. However, sometimes more flexibility is<br />
needed: we would like to be able to ''compute'' an arrow from intermediate results, and use this computed arrow to continue the computation. This is the power given to us by <code>ArrowApply</code>.<br />
<br />
==ArrowApply==<br />
<br />
The <code>ArrowApply</code> type class is:<br />
<br />
<haskell><br />
class Arrow (~>) => ArrowApply (~>) where<br />
app :: (b ~> c, b) ~> c<br />
</haskell><br />
<br />
If we have computed an arrow as the output of some previous<br />
computation, then <code>app</code> allows us to apply that arrow to an input,<br />
producing its output as the output of <code>app</code>. As an exercise, the<br />
reader may wish to use <code>app</code> to implement an alternative “curried”<br />
version, <code>app2 :: b ~> ((b ~> c) ~> c)</code>.<br />
<br />
This notion of being able to ''compute'' a new computation<br />
may sound familiar:<br />
this is exactly what the monadic bind operator <code>(>>=)</code> does. It<br />
should not particularly come as a surprise that <code>ArrowApply</code> and<br />
<code>Monad</code> are exactly equivalent in expressive power. In particular,<br />
<code>Kleisli m</code> can be made an instance of <code>ArrowApply</code>, and any instance<br />
of <code>ArrowApply</code> can be made a <code>Monad</code> (via the <code>newtype</code> wrapper<br />
<code>ArrowMonad</code>). As an exercise, the reader may wish to try<br />
implementing these instances:<br />
<br />
<haskell><br />
instance Monad m => ArrowApply (Kleisli m) where<br />
app = -- exercise<br />
<br />
newtype ArrowApply a => ArrowMonad a b = ArrowMonad (a () b)<br />
<br />
instance ArrowApply a => Monad (ArrowMonad a) where<br />
return = -- exercise<br />
(ArrowMonad a) >>= k = -- exercise<br />
</haskell><br />
<br />
==ArrowLoop==<br />
<br />
The <code>ArrowLoop</code> type class is:<br />
<br />
<haskell><br />
class Arrow a => ArrowLoop a where<br />
loop :: a (b, d) (c, d) -> a b c<br />
<br />
trace :: ((b,d) -> (c,d)) -> b -> c<br />
trace f b = let (c,d) = f (b,d) in c<br />
</haskell><br />
<br />
It describes arrows that can use recursion to compute results, and is<br />
used to desugar the <code>rec</code> construct in arrow notation (described<br />
below).<br />
<br />
Taken by itself, the type of the <code>loop</code> method does not seem to tell<br />
us much. Its intention, however, is a generalization of the <code>trace</code><br />
function which is also shown. The <code>d</code> component of the first arrow’s<br />
output is fed back in as its own input. In other words, the arrow<br />
<code>loop g</code> is obtained by recursively “fixing” the second component of<br />
the input to <code>g</code>.<br />
<br />
It can be a bit difficult to grok what the <code>trace</code> function is doing.<br />
How can <code>d</code> appear on the left and right sides of the <code>let</code>? Well,<br />
this is Haskell’s laziness at work. There is not space here for a<br />
full explanation; the interested reader is encouraged to study the<br />
standard <code>fix</code> function, and to read [http://www.soi.city.ac.uk/~ross/papers/fop.html Paterson’s arrow tutorial].<br />
<br />
==Arrow notation==<br />
<br />
Programming directly with the arrow combinators can be painful,<br />
especially when writing complex computations which need to retain<br />
simultaneous reference to a number of intermediate results. With<br />
nothing but the arrow combinators, such intermediate results must be<br />
kept in nested tuples, and it is up to the programmer to remember<br />
which intermediate results are in which components, and to swap,<br />
reassociate, and generally mangle tuples as necessary. This problem<br />
is solved by the special arrow notation supported by GHC, similar to<br />
<code>do</code> notation for monads, that allows names to be assigned to<br />
intermediate results while building up arrow computations. An example<br />
arrow implemented using arrow notation, taken from<br />
Paterson, is:<br />
<br />
<haskell><br />
class ArrowLoop (~>) => ArrowCircuit (~>) where<br />
delay :: b -> (b ~> b)<br />
<br />
counter :: ArrowCircuit (~>) => Bool ~> Int<br />
counter = proc reset -> do<br />
rec output <- idA -< if reset then 0 else next<br />
next <- delay 0 -< output + 1<br />
idA -< output<br />
</haskell><br />
<br />
This arrow is intended to<br />
represent a recursively defined counter circuit with a reset line.<br />
<br />
There is not space here for a full explanation of arrow notation; the<br />
interested reader should consult [http://www.soi.city.ac.uk/~ross/papers/notation.html Paterson’s paper introducing the<br />
notation], or his later [http://www.soi.city.ac.uk/~ross/papers/fop.html<br />
tutorial which presents a simplified version].<br />
<br />
==Further reading==<br />
<br />
An excellent starting place for the student of arrows is the [http://www.haskell.org/arrows/ arrows web page], which contains an<br />
introduction and many references. Some key papers on arrows include<br />
Hughes’s original paper introducing arrows, [http://dx.doi.org/10.1016/S0167-6423(99)00023-4 Generalising monads to arrows], and [http://www.soi.city.ac.uk/~ross/papers/notation.html Paterson’s paper on arrow notation].<br />
<br />
Both Hughes and Paterson later wrote accessible tutorials intended for a broader<br />
audience: [http://www.soi.city.ac.uk/~ross/papers/fop.html Paterson: Programming with Arrows] and [http://www.cse.chalmers.se/~rjmh/afp-arrows.pdf Hughes: Programming with Arrows].<br />
<br />
Although Hughes’s goal in defining the <code>Arrow</code> class was to<br />
generalize <code>Monad</code>s, and it has been said that <code>Arrow</code> lies “between<br />
<code>Applicative</code> and <code>Monad</code>” in power, they are not directly<br />
comparable. The precise relationship remained in some confusion until<br />
[http://homepages.inf.ed.ac.uk/wadler/papers/arrows-and-idioms/arrows-and-idioms.pdf analyzed by Lindley, Wadler, and Yallop], who<br />
also invented a new calculus of arrows, based on the lambda calculus,<br />
which considerably simplifies the presentation of the arrow laws<br />
(see [http://homepages.inf.ed.ac.uk/wadler/papers/arrows/arrows.pdf The arrow calculus]).<br />
<br />
Some examples of <code>Arrow</code>s include [http://www.haskell.org/yampa/ Yampa], the<br />
[http://www.fh-wedel.de/~si/HXmlToolbox/ Haskell XML Toolkit], and the functional GUI library [[Grapefruit]].<br />
<br />
Some extensions to arrows have been explored; for example, the<br />
[http://www.cs.ru.nl/A.vanWeelden/bi-arrows/ <code>BiArrow</code>s of Alimarine et al.], for two-way instead of one-way<br />
computation.<br />
<br />
The Haskell wiki has [[Research papers/Monads and Arrows|links to many additional research papers relating to <code>Arrow</code>s]].<br />
<br />
=Comonad=<br />
<br />
The final type class we will examine is <code>Comonad</code>. The <code>Comonad</code> class<br />
is the categorical dual of <code>Monad</code>; that is, <code>Comonad</code> is like <code>Monad</code><br />
but with all the function arrows flipped. It is not actually in the<br />
standard Haskell libraries, but it has seen some interesting uses<br />
recently, so we include it here for completeness.<br />
<br />
==Definition==<br />
<br />
The <code>Comonad</code> type class, defined in the <code>Control.Comonad</code> module of<br />
the [http://hackage.haskell.org/package/comonad comonad library], is:<br />
<br />
<haskell><br />
class Functor f => Copointed f where<br />
extract :: f a -> a<br />
<br />
class Copointed w => Comonad w where<br />
duplicate :: w a -> w (w a)<br />
extend :: (w a -> b) -> w a -> w b<br />
</haskell><br />
<br />
As you can see, <code>extract</code> is the dual of <code>return</code>, <code>duplicate</code> is the<br />
dual of <code>join</code>, and <code>extend</code> is the dual of <code>(>>=)</code> (although its<br />
arguments are in a different order). The definition<br />
of <code>Comonad</code> is a bit redundant (after all, the <code>Monad</code> class does not<br />
need <code>join</code>), but this is so that a <code>Comonad</code> can be defined by <code>fmap</code>,<br />
<code>extract</code>, and ''either'' <code>duplicate</code> or <code>extend</code>. Each has a<br />
default implementation in terms of the other.<br />
<br />
A prototypical example of a <code>Comonad</code> instance is:<br />
<br />
<haskell><br />
-- Infinite lazy streams<br />
data Stream a = Cons a (Stream a)<br />
<br />
instance Functor Stream where<br />
fmap g (Cons x xs) = Cons (g x) (fmap g xs)<br />
<br />
instance Copointed Stream where<br />
extract (Cons x _) = x<br />
<br />
-- 'duplicate' is like the list function 'tails'<br />
-- 'extend' computes a new Stream from an old, where the element<br />
-- at position n is computed as a function of everything from<br />
-- position n onwards in the old Stream<br />
instance Comonad Stream where<br />
duplicate s@(Cons x xs) = Cons s (duplicate xs)<br />
extend g s@(Cons x xs) = Cons (g s) (extend g xs)<br />
-- = fmap g (duplicate s)<br />
</haskell><br />
<br />
==Further reading==<br />
<br />
Dan Piponi explains in a blog post what [http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html cellular automata have to do with comonads]. In another blog post, Conal Elliott has examined [http://conal.net/blog/posts/functional-interactive-behavior/ a comonadic formulation of functional reactive programming]. Sterling Clover’s blog post [http://fmapfixreturn.wordpress.com/2008/07/09/comonads-in-everyday-life/ Comonads in everyday life] explains the relationship between comonads and zippers, and how comonads can be used to design a menu system for a web site.<br />
<br />
Uustalu and Vene have a number of papers exploring ideas related to comonads and functional programming:<br />
* [http://dx.doi.org/10.1016/j.entcs.2008.05.029 Comonadic Notions of Computation]<br />
* [http://www.ioc.ee/~tarmo/papers/sfp01-book.pdf The dual of substitution is redecoration] (Also available as [http://www.cs.ut.ee/~varmo/papers/sfp01-book.ps.gz ps.gz].)<br />
* [http://dx.doi.org/10.1016/j.ic.2005.08.005 Recursive coalgebras from comonads]<br />
* [http://www.fing.edu.uy/~pardo/papers/njc01.ps.gz Recursion schemes from comonads]<br />
* [http://cs.ioc.ee/~tarmo/papers/essence.pdf The Essence of Dataflow Programming].<br />
<br />
=Acknowledgements=<br />
<br />
A special thanks to all of those who taught me about standard Haskell<br />
type classes and helped me develop good intuition for them,<br />
particularly Jules Bean (quicksilver), Derek Elkins (ddarius), Conal<br />
Elliott (conal), Cale Gibbard (Cale), David House, Dan Piponi<br />
(sigfpe), and Kevin Reid (kpreid).<br />
<br />
I also thank the many people who provided a mountain of helpful<br />
feedback and suggestions on a first draft of the Typeclassopedia: David Amos,<br />
Kevin Ballard, Reid Barton, Doug Beardsley, Joachim Breitner, Andrew<br />
Cave, David Christiansen, Gregory Collins, Mark Jason Dominus, Conal<br />
Elliott, Yitz Gale, George Giorgidze, Steven Grady, Travis Hartwell,<br />
Steve Hicks, Philip Hölzenspies, Edward Kmett, Eric Kow, Serge Le<br />
Huitouze, Felipe Lessa, Stefan Ljungstrand, Eric Macaulay, Rob MacAulay, Simon Meier,<br />
Eric Mertens, Tim Newsham, Russell O’Connor, Conrad Parker, Walt<br />
Rorie-Baety, Colin Ross, Tom Schrijvers, Aditya Siram, C. Smith,<br />
Martijn van Steenbergen, Joe Thornber, Jared Updike, Rob Vollmert,<br />
Andrew Wagner, Louis Wasserman, and Ashley Yakeley, as well as a few<br />
only known to me by their IRC nicks: b_jonas, maltem, tehgeekmeister,<br />
and ziman. I have undoubtedly omitted a few inadvertently, which in<br />
no way diminishes my gratitude.<br />
<br />
Finally, I would like to thank Wouter Swierstra for his fantastic work<br />
editing the Monad.Reader, and my wife Joyia for her patience during<br />
the process of writing the Typeclassopedia.<br />
<br />
=About the author=<br />
<br />
Brent Yorgey ([http://byorgey.wordpress.com/ blog], [http://www.cis.upenn.edu/~byorgey/ homepage]) is (as of November 2011) a fourth-year Ph.D. student in the [http://www.cis.upenn.edu/~plclub/ programming languages group] at the [http://www.upenn.edu University of Pennsylvania]. He enjoys teaching, creating EDSLs, playing Bach fugues, musing upon category theory, and cooking tasty lambda-treats for the denizens of #haskell.<br />
<br />
=Colophon=<br />
<br />
The Typeclassopedia was written by Brent Yorgey and initally published in March 2009. Painstakingly converted to wiki syntax by [[User:Geheimdienst]] in November 2011, after asking Brent’s permission.<br />
<br />
If something like this tex to wiki syntax conversion ever needs to be done again, here are some vim commands that helped:<br />
<br />
* <nowiki>%s/\\section{\([^}]*\)}/=\1=/gc</nowiki><br />
* <nowiki>%s/\\subsection{\([^}]*\)}/==\1==/gc</nowiki><br />
* <nowiki>%s/^ *\\item /\r* /gc</nowiki><br />
* <nowiki>%s/---/—/gc</nowiki><br />
* <nowiki>%s/\$\([^$]*\)\$/<math>\1\\ <\/math>/gc</nowiki> ''Appending “\ ” forces images to be rendered. Otherwise, Mediawiki would go back and forth between one font for short <nowiki><math></nowiki> tags, and another more Tex-like font for longer tags (containing more than a few characters)""<br />
* <nowiki>%s/|\([^|]*\)|/<code>\1<\/code>/gc</nowiki><br />
* <nowiki>%s/\\dots/.../gc</nowiki><br />
* <nowiki>%s/^\\label{.*$//gc</nowiki><br />
* <nowiki>%s/\\emph{\([^}]*\)}/''\1''/gc</nowiki><br />
* <nowiki>%s/\\term{\([^}]*\)}/''\1''/gc</nowiki><br />
<br />
The biggest issue was taking the academic-paper-style citations and turning them into hyperlinks with an appropriate title and an appropriate target. In most cases there was an obvious thing to do (e.g. online PDFs of the cited papers or Citeseer entries). Sometimes, however, it’s less clear and you might want to check the<br />
[[Media:Typeclassopedia.pdf|original Typeclassopedia PDF]]<br />
with the<br />
[http://code.haskell.org/~byorgey/TMR/Issue13/typeclassopedia.bib original bibliography file].<br />
<br />
To get all the citations into the main text, I first tried processing the source with Tex or Lyx. This didn’t work due to missing unfindable packages, syntax errors, and my general ineptitude with Tex.<br />
<br />
I then went for the next best solution, which seemed to be extracting all instances of “\cite{something}” from the source and ''in that order'' pulling the referenced entries from the .bib file. This way you can go through the source file and sorted-references file in parallel, copying over what you need, without searching back and forth in the .bib file. I used:<br />
<br />
* <nowiki>egrep -o "\cite\{[^\}]*\}" ~/typeclassopedia.lhs | cut -c 6- | tr "," "\n" | tr -d "}" > /tmp/citations</nowiki><br />
* <nowiki>for i in $(cat /tmp/citations); do grep -A99 "$i" ~/typeclassopedia.bib|egrep -B99 '^\}$' -m1 ; done > ~/typeclasso-refs-sorted</nowiki><br />
<br />
[[Category:Applicative Functor]]<br />
[[Category:Arrow]]<br />
[[Category:Functor]]<br />
[[Category:Monad]]<br />
[[Category:Standard classes]]<br />
[[Category:Standard libraries]]<br />
[[Category:Standard packages]]<br />
[[Category:Standard types]]</div>Daghttps://wiki.haskell.org/index.php?title=Typeclassopedia&diff=45931Typeclassopedia2012-06-08T00:47:06Z<p>Dag: /* Further reading */ update link for "All About Monads"</p>
<hr />
<div>''By [[User:Byorgey|Brent Yorgey]], byorgey@cis.upenn.edu''<br />
<br />
''Originally published 12 March 2009 in [http://www.haskell.org/wikiupload/8/85/TMR-Issue13.pdf issue 13] of [http://themonadreader.wordpress.com/ the Monad.Reader]. Ported to the Haskell wiki in November 2011 by [[User:Geheimdienst|Geheimdienst]].''<br />
<br />
''This is now the official version of the Typeclassopedia and supersedes the version published in the Monad.Reader. Please help update and extend it by editing it yourself or by leaving comments, suggestions, and questions on the [[Talk:Typeclassopedia|talk page]].''<br />
<br />
=Abstract=<br />
<br />
The standard Haskell libraries feature a number of type classes with algebraic or category-theoretic underpinnings. Becoming a fluent Haskell hacker requires intimate familiarity with them all, yet acquiring this familiarity often involves combing through a mountain of tutorials, blog posts, mailing list archives, and IRC logs.<br />
<br />
The goal of this document is to serve as a starting point for the student of Haskell wishing to gain a firm grasp of its standard type classes. The essentials of each type class are introduced, with examples, commentary, and extensive references for further reading.<br />
<br />
=Introduction=<br />
<br />
Have you ever had any of the following thoughts?<br />
* What the heck is a monoid, and how is it different from a mon<u>a</u>d?<br />
<br />
* I finally figured out how to use [[Parsec]] with do-notation, and someone told me I should use something called <code>Applicative</code> instead. Um, what?<br />
<br />
* Someone in the [[IRC channel|#haskell]] IRC channel used <code>(***)</code>, and when I asked lambdabot to tell me its type, it printed out scary gobbledygook that didn’t even fit on one line! Then someone used <code>fmap fmap fmap</code> and my brain exploded.<br />
<br />
* When I asked how to do something I thought was really complicated, people started typing things like <code>zip.ap fmap.(id &&& wtf)</code> and the scary thing is that they worked! Anyway, I think those people must actually be robots because there’s no way anyone could come up with that in two seconds off the top of their head.<br />
<br />
If you have, look no further! You, too, can write and understand concise, elegant, idiomatic Haskell code with the best of them.<br />
<br />
There are two keys to an expert Haskell hacker’s wisdom:<br />
# Understand the types.<br />
# Gain a deep intuition for each type class and its relationship to other type classes, backed up by familiarity with many examples.<br />
<br />
It’s impossible to overstate the importance of the first; the patient student of type signatures will uncover many profound secrets. Conversely, anyone ignorant of the types in their code is doomed to eternal uncertainty. “Hmm, it doesn’t compile ... maybe I’ll stick in an<br />
<code>fmap</code> here ... nope, let’s see ... maybe I need another <code>(.)</code> somewhere? ... um ...”<br />
<br />
The second key—gaining deep intuition, backed by examples—is also important, but much more difficult to attain. A primary goal of this document is to set you on the road to gaining such intuition. However—<br />
<br />
:''There is no royal road to Haskell. {{h:title|Well, he probably would have said it if he knew Haskell.|—Euclid}}''<br />
<br />
This document can only be a starting point, since good intuition comes from hard work, [http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/ not from learning the right metaphor]. Anyone who reads and understands all of it will still have an arduous journey ahead—but sometimes a good starting point makes a big difference.<br />
<br />
It should be noted that this is not a Haskell tutorial; it is assumed that the reader is already familiar with the basics of Haskell, including the standard <code>[http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html Prelude]</code>, the type system, data types, and type classes.<br />
<br />
The type classes we will be discussing and their interrelationships:<br />
<br />
[[Image:Typeclassopedia-diagram.png]]<br />
<br />
{{note|<code>Semigroup</code> can be found in the [http://hackage.haskell.org/package/semigroups <code>semigroups</code> package], <code>Apply</code> in the [http://hackage.haskell.org/package/semigroupoids <code>semigroupoids</code> package], and <code>Comonad</code> in the [http://hackage.haskell.org/package/comonad <code>comonad</code> package].}}<br />
<br />
* <span style="border-bottom: 2px solid black">Solid arrows</span> point from the general to the specific; that is, if there is an arrow from <code>Foo</code> to <code>Bar</code> it means that every <code>Bar</code> is (or should be, or can be made into) a <code>Foo</code>.<br />
* <span style="border-bottom: 2px dotted black">Dotted arrows</span> indicate some other sort of relationship.<br />
* <code>Monad</code> and <code>ArrowApply</code> are equivalent.<br />
* <code>Semigroup</code>, <code>Apply</code> and <code>Comonad</code> are greyed out since they are not actually (yet?) in the standard Haskell libraries {{noteref}}.<br />
<br />
One more note before we begin. The original spelling of “type class” is with two words, as evidenced by, for example, the [http://haskell.org/onlinereport/ Haskell 98 Revised Report], early papers on type classes like [http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.103.5639 Type classes in Haskell] and [http://research.microsoft.com/en-us/um/people/simonpj/papers/type-class-design-space/ Type classes: exploring the design space], and [http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.168.4008 Hudak et al.’s history of Haskell]. However, as often happens with two-word phrases that see a lot of use, it has started to show up as one word (“typeclass”) or, rarely, hyphenated (“type-class”). When wearing my prescriptivist hat, I prefer “type class”, but realize (after changing into my descriptivist hat) that there's probably not much I can do about it.<br />
<br />
We now begin with the simplest type class of all: <code>Functor</code>.<br />
<br />
=Functor=<br />
<br />
The <code>Functor</code> class ([http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor haddock]) is the most basic and ubiquitous type class in the Haskell libraries. A simple intuition is that a <code>Functor</code> represents a “container” of some sort, along with the ability to apply a function uniformly to every element in the container. For example, a list is a container of elements, and we can apply a function to every element of a list, using <code>map</code>. As another example, a binary tree is also a container of elements, and it’s not hard to come up with a way to recursively apply a function to every element in a tree.<br />
<br />
Another intuition is that a <code>Functor</code> represents some sort of “computational context”. This intuition is generally more useful, but is more difficult to explain, precisely because it is so general. Some examples later should help to clarify the <code>Functor</code>-as-context point of view.<br />
<br />
In the end, however, a <code>Functor</code> is simply what it is defined to be; doubtless there are many examples of <code>Functor</code> instances that don’t exactly fit either of the above intuitions. The wise student will focus their attention on definitions and examples, without leaning too heavily on any particular metaphor. Intuition will come, in time, on its own.<br />
<br />
==Definition==<br />
<br />
Here is the type class declaration for <code>Functor</code>:<br />
<br />
<haskell><br />
class Functor f where<br />
fmap :: (a -> b) -> f a -> f b<br />
</haskell><br />
<br />
<code>Functor</code> is exported by the <code>Prelude</code>, so no special imports are needed to use it.<br />
<br />
First, the <code>f a</code> and <code>f b</code> in the type signature for <code>fmap</code> tell us that <code>f</code> isn’t just a type; it is a ''type constructor'' which takes another type as a parameter. (A more precise way to say this is that the ''kind'' of <code>f</code> must be <code>* -> *</code>.) For example, <code>Maybe</code> is such a type constructor: <code>Maybe</code> is not a type in and of itself, but requires another type as a parameter, like <code>Maybe Integer</code>. So it would not make sense to say <code>instance Functor Integer</code>, but it could make sense to say <code>instance Functor Maybe</code>.<br />
<br />
Now look at the type of <code>fmap</code>: it takes any function from <code>a</code> to <code>b</code>, and a value of type <code>f a</code>, and outputs a value of type <code>f b</code>. From the container point of view, the intention is that <code>fmap</code> applies a function to each element of a container, without altering the structure of the container. From the context point of view, the intention is that <code>fmap</code> applies a function to a value without altering its context. Let’s look at a few specific examples.<br />
<br />
==Instances==<br />
<br />
{{note|Recall that <code>[]</code> has two meanings in Haskell: it can either stand for the empty list, or, as here, it can represent the list type constructor (pronounced “list-of”). In other words, the type <code>[a]</code> (list-of-<code>a</code>) can also be written <code>[] a</code>.}}<br />
<br />
{{note|You might ask why we need a separate <code>map</code> function. Why not just do away with the current list-only <code>map</code> function, and rename <code>fmap</code> to <code>map</code> instead? Well, that’s a good question. The usual argument is that someone just learning Haskell, when using <code>map</code> incorrectly, would much rather see an error about lists than about <code>Functor</code>s.}}<br />
<br />
As noted before, the list constructor <code>[]</code> is a functor {{noteref}}; we can use the standard list function <code>map</code> to apply a function to each element of a list {{noteref}}. The <code>Maybe</code> type constructor is also a functor, representing a container which might hold a single element. The function <code>fmap g</code> has no effect on <code>Nothing</code> (there are no elements to which <code>g</code> can be applied), and simply applies <code>g</code> to the single element inside a <code>Just</code>. Alternatively, under the context interpretation, the list functor represents a context of nondeterministic choice; that is, a list can be thought of as representing a single value which is nondeterministically chosen from among several possibilities (the elements of the list). Likewise, the <code>Maybe</code> functor represents a context with possible failure. These instances are:<br />
<br />
<haskell><br />
instance Functor [] where<br />
fmap _ [] = []<br />
fmap g (x:xs) = g x : fmap g xs<br />
-- or we could just say fmap = map<br />
<br />
instance Functor Maybe where<br />
fmap _ Nothing = Nothing<br />
fmap g (Just a) = Just (g a)<br />
</haskell><br />
<br />
As an aside, in idiomatic Haskell code you will often see the letter <code>f</code> used to stand for both an arbitrary <code>Functor</code> and an arbitrary function. In this document, <code>f</code> represents only <code>Functor</code>s, and <code>g</code> or <code>h</code> always represent functions, but you should be aware of the potential confusion. In practice, what <code>f</code> stands for should always be clear from the context, by noting whether it is part of a type or part of the code.<br />
<br />
There are other <code>Functor</code> instances in the standard libraries; below are a few. Note that some of these instances are not exported by the <code>Prelude</code>; to access them, you can import <code>Control.Monad.Instances</code>.<br />
<br />
* <code>Either e</code> is an instance of <code>Functor</code>; <code>Either e a</code> represents a container which can contain either a value of type <code>a</code>, or a value of type <code>e</code> (often representing some sort of error condition). It is similar to <code>Maybe</code> in that it represents possible failure, but it can carry some extra information about the failure as well.<br />
<br />
* <code>((,) e)</code> represents a container which holds an “annotation” of type <code>e</code> along with the actual value it holds. It might be clearer to write it as <code>(e,)</code>, by analogy with an operator section like <code>(1+)</code>, but that syntax is not allowed in types (although it is allowed in expressions with the <code>TupleSections</code> extension enabled). However, you can certainly ''think'' of it as <code>(e,)</code>.<br />
<br />
* <code>((->) e)</code> (which can be thought of as <code>(e ->)</code>; see above), the type of functions which take a value of type <code>e</code> as a parameter, is a <code>Functor</code>. As a container, <code>(e -> a)</code> represents a (possibly infinite) set of values of <code>a</code>, indexed by values of <code>e</code>. Alternatively, and more usefully, <code>((->) e)</code> can be thought of as a context in which a value of type <code>e</code> is available to be consulted in a read-only fashion. This is also why <code>((->) e)</code> is sometimes referred to as the ''reader monad''; more on this later.<br />
<br />
* <code>IO</code> is a <code>Functor</code>; a value of type <code>IO a</code> represents a computation producing a value of type <code>a</code> which may have I/O effects. If <code>m</code> computes the value <code>x</code> while producing some I/O effects, then <code>fmap g m</code> will compute the value <code>g x</code> while producing the same I/O effects.<br />
<br />
* Many standard types from the [http://hackage.haskell.org/package/containers/ containers library] (such as <code>Tree</code>, <code>Map</code>, and <code>Sequence</code>) are instances of <code>Functor</code>. A notable exception is <code>Set</code>, which cannot be made a <code>Functor</code> in Haskell (although it is certainly a mathematical functor) since it requires an <code>Ord</code> constraint on its elements; <code>fmap</code> must be applicable to ''any'' types <code>a</code> and <code>b</code>. However, <code>Set</code> (and other similarly restricted data types) can be made an instance of a suitable generalization of <code>Functor</code>, either by [http://article.gmane.org/gmane.comp.lang.haskell.cafe/78052/ making <code>a</code> and <code>b</code> arguments to the <code>Functor</code> type class themselves], or by adding an [http://blog.omega-prime.co.uk/?p=127 associated constraint].<br />
<br />
{{Exercises|<br />
<ol><br />
<li>Implement <code>Functor</code> instances for <code>Either e</code> and <code>((->) e)</code>.</li><br />
<li>Implement <code>Functor</code> instances for <code>((,) e)</code> and for <code>Pair</code>, defined as <br />
<br />
<haskell>data Pair a = Pair a a</haskell><br />
<br />
Explain their similarities and differences.<br />
</li><br />
<li>Implement a <code>Functor</code> instance for the type <code>ITree</code>, defined as<br />
<br />
<haskell><br />
data ITree a = Leaf (Int -> a) <br />
| Node [ITree a]<br />
</haskell><br />
</li><br />
<li>Give an example of a type of kind <code>* -> *</code> which cannot be made an instance of <code>Functor</code> (without using <code>undefined</code>).<br />
</li><br />
<li>Is this statement true or false? <br />
<br />
:''The composition of two <code>Functor</code>s is also a <code>Functor</code>.''<br />
<br />
If false, give a counterexample; if true, prove it by exhibiting some appropriate Haskell code.<br />
</li><br />
</ol><br />
}}<br />
<br />
==Laws==<br />
<br />
As far as the Haskell language itself is concerned, the only requirement to be a <code>Functor</code> is an implementation of <code>fmap</code> with the proper type. Any sensible <code>Functor</code> instance, however, will also satisfy the ''functor laws'', which are part of the definition of a mathematical functor. There are two:<br />
<br />
<haskell><br />
fmap id = id<br />
fmap (g . h) = (fmap g) . (fmap h)<br />
</haskell><br />
<br />
{{note|Technically, these laws make <code>f</code> and <code>fmap</code> together an endofunctor on ''Hask'', the category of Haskell types (ignoring [[Bottom|&perp;]], which is a party pooper). See [http://en.wikibooks.org/wiki/Haskell/Category_theory Wikibook: Category theory].}}<br />
<br />
Together, these laws ensure that <code>fmap g</code> does not change the ''structure'' of a container, only the elements. Equivalently, and more simply, they ensure that <code>fmap g</code> changes a value without altering its context {{noteref}}.<br />
<br />
The first law says that mapping the identity function over every item in a container has no effect. The second says that mapping a composition of two functions over every item in a container is the same as first mapping one function, and then mapping the other.<br />
<br />
As an example, the following code is a “valid” instance of <code>Functor</code> (it typechecks), but it violates the functor laws. Do you see why?<br />
<br />
<haskell><br />
-- Evil Functor instance<br />
instance Functor [] where<br />
fmap _ [] = []<br />
fmap g (x:xs) = g x : g x : fmap g xs<br />
</haskell><br />
<br />
Any Haskeller worth their salt would reject this code as a gruesome abomination.<br />
<br />
Unlike some other type classes we will encounter, a given type has at most one valid instance of <code>Functor</code>. This [http://article.gmane.org/gmane.comp.lang.haskell.libraries/15384 can be proven] via the [http://homepages.inf.ed.ac.uk/wadler/topics/parametricity.html#free ''free theorem''] for the type of <code>fmap</code>. In fact, [http://byorgey.wordpress.com/2010/03/03/deriving-pleasure-from-ghc-6-12-1/ GHC can automatically derive] <code>Functor</code> instances for many data types.<br />
<br />
A similar argument also shows that any <code>Functor</code> instance satisfying the first law (<code>fmap id = id</code>) will automatically satisfy the second law as well. Practically, this means that only the first law needs to be checked (usually by a very straightforward induction) to ensure that a <code>Functor</code> instance is valid.<br />
<br />
{{Exercises|<br />
# Although it is not possible for a <code>Functor</code> instance to satisfy the first <code>Functor</code> law but not the second, the reverse is possible. Give an example of a (bogus) <code>Functor</code> instance which satisfies the second law but not the first.<br />
# Which laws are violated by the evil <code>Functor</code> instance for list shown above: both laws, or the first law alone? Give specific counterexamples.<br />
}}<br />
<br />
==Intuition==<br />
<br />
There are two fundamental ways to think about <code>fmap</code>. The first has already been mentioned: it takes two parameters, a function and a container, and applies the function “inside” the container, producing a new container. Alternately, we can think of <code>fmap</code> as applying a function to a value in a context (without altering the context).<br />
<br />
Just like all other Haskell functions of “more than one parameter”, however, <code>fmap</code> is actually ''curried'': it does not really take two parameters, but takes a single parameter and returns a function. For emphasis, we can write <code>fmap</code>’s type with extra parentheses: <code>fmap :: (a -> b) -> (f a -> f b)</code>. Written in this form, it is apparent that <code>fmap</code> transforms a “normal” function (<code>g :: a -> b</code>) into one which operates over containers/contexts (<code>fmap g :: f a -> f b</code>). This transformation is often referred to as a ''lift''; <code>fmap</code> “lifts” a function from the “normal world” into the “<code>f</code> world”.<br />
<br />
==Further reading==<br />
<br />
A good starting point for reading about the category theory behind the concept of a functor is the excellent [http://en.wikibooks.org/wiki/Haskell/Category_theory Haskell wikibook page on category theory].<br />
<br />
=Applicative=<br />
<br />
A somewhat newer addition to the pantheon of standard Haskell type classes, ''applicative functors'' represent an abstraction lying in between <code>Functor</code> and <code>Monad</code> in expressivity, first described by McBride and Paterson. The title of their classic paper, [http://www.soi.city.ac.uk/~ross/papers/Applicative.html Applicative Programming with Effects], gives a hint at the intended intuition behind the [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html <code>Applicative</code>] type class. It encapsulates certain sorts of “effectful” computations in a functionally pure way, and encourages an “applicative” programming style. Exactly what these things mean will be seen later.<br />
<br />
==Definition==<br />
<br />
Recall that <code>Functor</code> allows us to lift a “normal” function to a function on computational contexts. But <code>fmap</code> doesn’t allow us to apply a function which is itself in a context to a value in a context. <code>Applicative</code> gives us just such a tool, <code>(<*>)</code>. It also provides a method, <code>pure</code>, for embedding values in a default, “effect free” context. Here is the type class declaration for <code>Applicative</code>, as defined in <code>Control.Applicative</code>:<br />
<br />
<haskell><br />
class Functor f => Applicative f where<br />
pure :: a -> f a<br />
(<*>) :: f (a -> b) -> f a -> f b<br />
</haskell><br />
<br />
Note that every <code>Applicative</code> must also be a <code>Functor</code>. In fact, as we will see, <code>fmap</code> can be implemented using the <code>Applicative</code> methods, so every <code>Applicative</code> is a functor whether we like it or not; the <code>Functor</code> constraint forces us to be honest.<br />
<br />
{{note|Recall that <code>($)</code> is just function application: <code>f $ x {{=}} f x</code>.}}<br />
<br />
As always, it’s crucial to understand the type signatures. First, consider <code>(<*>)</code>: the best way of thinking about it comes from noting that the type of <code>(<*>)</code> is similar to the type of <code>($)</code> {{noteref}}, but with everything enclosed in an <code>f</code>. In other words, <code>(<*>)</code> is just function application within a computational context. The type of <code>(<*>)</code> is also very similar to the type of <code>fmap</code>; the only difference is that the first parameter is <code>f (a -> b)</code>, a function in a context, instead of a “normal” function <code>(a -> b)</code>.<br />
<br />
<code>pure</code> takes a value of any type <code>a</code>, and returns a context/container of type <code>f a</code>. The intention is that <code>pure</code> creates some sort of “default” container or “effect free” context. In fact, the behavior of <code>pure</code> is quite constrained by the laws it should satisfy in conjunction with <code>(<*>)</code>. Usually, for a given implementation of <code>(<*>)</code> there is only one possible implementation of <code>pure</code>.<br />
<br />
(Note that previous versions of the Typeclassopedia explained <code>pure</code> in terms of a type class <code>Pointed</code>, which can still be found in the [http://hackage.haskell.org/package/pointed <code>pointed</code> package]. However, the current consensus is that <code>Pointed</code> is not very useful after all. For a more detailed explanation, see [[Why not Pointed?]])<br />
<br />
==Laws==<br />
<br />
{{note|See<br />
[http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html haddock for Applicative] and [http://www.soi.city.ac.uk/~ross/papers/Applicative.html Applicative programming with effects]}}<br />
<br />
There are several laws that <code>Applicative</code> instances should satisfy {{noteref}}, but only one is crucial to developing intuition, because it specifies how <code>Applicative</code> should relate to <code>Functor</code> (the other four mostly specify the exact sense in which <code>pure</code> deserves its name). This law is:<br />
<br />
<haskell><br />
fmap g x = pure g <*> x<br />
</haskell><br />
<br />
It says that mapping a pure function <code>g</code> over a context <code>x</code> is the same as first injecting <code>g</code> into a context with <code>pure</code>, and then applying it to <code>x</code> with <code>(<*>)</code>. In other words, we can decompose <code>fmap</code> into two more atomic operations: injection into a context, and application within a context. The <code>Control.Applicative</code> module also defines <code>(<$>)</code> as a synonym for <code>fmap</code>, so the above law can also be expressed as:<br />
<br />
<code>g <$> x = pure g <*> x</code>.<br />
<br />
==Instances==<br />
<br />
Most of the standard types which are instances of <code>Functor</code> are also instances of <code>Applicative</code>.<br />
<br />
<code>Maybe</code> can easily be made an instance of <code>Applicative</code>; writing such an instance is left as an exercise for the reader.<br />
<br />
The list type constructor <code>[]</code> can actually be made an instance of <code>Applicative</code> in two ways; essentially, it comes down to whether we want to think of lists as ordered collections of elements, or as contexts representing multiple results of a nondeterministic computation (see Wadler’s [http://www.springerlink.com/content/y7450255v2670167/ How to replace failure by a list of successes]).<br />
<br />
Let’s first consider the collection point of view. Since there can only be one instance of a given type class for any particular type, one or both of the list instances of <code>Applicative</code> need to be defined for a <code>newtype</code> wrapper; as it happens, the nondeterministic computation instance is the default, and the collection instance is defined in terms of a <code>newtype</code> called <code>ZipList</code>. This instance is:<br />
<br />
<haskell><br />
newtype ZipList a = ZipList { getZipList :: [a] }<br />
<br />
instance Applicative ZipList where<br />
pure = undefined -- exercise<br />
(ZipList gs) <*> (ZipList xs) = ZipList (zipWith ($) gs xs)<br />
</haskell><br />
<br />
To apply a list of functions to a list of inputs with <code>(<*>)</code>, we just match up the functions and inputs elementwise, and produce a list of the resulting outputs. In other words, we “zip” the lists together with function application, <code>($)</code>; hence the name <code>ZipList</code>. <br />
<br />
The other <code>Applicative</code> instance for lists, based on the nondeterministic computation point of view, is:<br />
<br />
<haskell><br />
instance Applicative [] where<br />
pure x = [x]<br />
gs <*> xs = [ g x | g <- gs, x <- xs ]<br />
</haskell><br />
<br />
Instead of applying functions to inputs pairwise, we apply each function to all the inputs in turn, and collect all the results in a list.<br />
<br />
Now we can write nondeterministic computations in a natural style. To add the numbers <code>3</code> and <code>4</code> deterministically, we can of course write <code>(+) 3 4</code>. But suppose instead of <code>3</code> we have a nondeterministic computation that might result in <code>2</code>, <code>3</code>, or <code>4</code>; then we can write<br />
<br />
<haskell><br />
pure (+) <*> [2,3,4] <*> pure 4<br />
</haskell><br />
<br />
or, more idiomatically,<br />
<br />
<haskell><br />
(+) <$> [2,3,4] <*> pure 4.<br />
</haskell><br />
<br />
There are several other <code>Applicative</code> instances as well:<br />
<br />
* <code>IO</code> is an instance of <code>Applicative</code>, and behaves exactly as you would think: to execute <code>m1 <*> m2</code>, first <code>m1</code> is executed, resulting in a function <code>f</code>, then <code>m2</code> is executed, resulting in a value <code>x</code>, and finally the value <code>f x</code> is returned as the result of executing <code>m1 <*> m2</code>.<br />
<br />
* <code>((,) a)</code> is an <code>Applicative</code>, as long as <code>a</code> is an instance of <code>Monoid</code> ([[#Monoid|section Monoid]]). The <code>a</code> values are accumulated in parallel with the computation.<br />
<br />
* The <code>Applicative</code> module defines the <code>Const</code> type constructor; a value of type <code>Const a b</code> simply contains an <code>a</code>. This is an instance of <code>Applicative</code> for any <code>Monoid a</code>; this instance becomes especially useful in conjunction with things like <code>Foldable</code> ([[#Foldable|section Foldable]]).<br />
<br />
* The <code>WrappedMonad</code> and <code>WrappedArrow</code> newtypes make any instances of <code>Monad</code> ([[#Monad|section Monad]]) or <code>Arrow</code> ([[#Arrow|section Arrow]]) respectively into instances of <code>Applicative</code>; as we will see when we study those type classes, both are strictly more expressive than <code>Applicative</code>, in the sense that the <code>Applicative</code> methods can be implemented in terms of their methods.<br />
<br />
{{Exercises|<br />
# Implement an instance of <code>Applicative</code> for <code>Maybe</code>.<br />
# Determine the correct definition of <code>pure</code> for the <code>ZipList</code> instance of <code>Applicative</code>—there is only one implementation that satisfies the law relating <code>pure</code> and <code>(<*>)</code>.<br />
}}<br />
<br />
==Intuition==<br />
<br />
McBride and Paterson’s paper introduces the notation <math>[[g \; x_1 \; x_2 \; \cdots \; x_n]]\ </math> to denote function application in a computational context. If each <math>x_i\ </math> has type <math>f \; t_i\ </math> for some applicative functor <math>f\ </math>, and <math>g\ </math> has type <math>t_1 \to t_2 \to \dots \to t_n \to t\ </math>, then the entire expression <math>[[g \; x_1 \; \cdots \; x_n]]\ </math> has type <math>f \; t\ </math>. You can think of this as applying a function to multiple “effectful” arguments. In this sense, the double bracket notation is a generalization of <code>fmap</code>, which allows us to apply a function to a single argument in a context.<br />
<br />
Why do we need <code>Applicative</code> to implement this generalization of <code>fmap</code>? Suppose we use <code>fmap</code> to apply <code>g</code> to the first parameter <code>x1</code>. Then we get something of type <code>f (t2 -> ... t)</code>, but now we are stuck: we can’t apply this function-in-a-context to the next argument with <code>fmap</code>. However, this is precisely what <code>(<*>)</code> allows us to do.<br />
<br />
This suggests the proper translation of the idealized notation <math>[[g \; x_1 \; x_2 \; \cdots \; x_n]]\ </math> into Haskell, namely<br />
<haskell><br />
g <$> x1 <*> x2 <*> ... <*> xn,<br />
</haskell><br />
<br />
recalling that <code>Control.Applicative</code> defines <code>(<$>)</code> as convenient infix shorthand for <code>fmap</code>. This is what is meant by an “applicative style”—effectful computations can still be described in terms of function application; the only difference is that we have to use the special operator <code>(<*>)</code> for application instead of simple juxtaposition.<br />
<br />
Note that <code>pure</code> allows embedding “non-effectful” arguments in the middle of an idiomatic application, like<br />
<haskell><br />
g <$> x1 <*> pure x2 <*> x3<br />
</haskell><br />
which has type <code>f d</code>, given<br />
<haskell><br />
g :: a -> b -> c -> d<br />
x1 :: f a<br />
x2 :: b<br />
c3 :: f c<br />
</haskell><br />
<br />
The double brackets are commonly known as “idiom brackets”, because they allow writing “idiomatic” function application, that is, function application that looks normal but has some special, non-standard meaning (determined by the particular instance of <code>Applicative</code> being used). Idiom brackets are not supported by GHC, but they are supported by the [http://personal.cis.strath.ac.uk/~conor/pub/she/ Strathclyde Haskell Enhancement], a preprocessor which (among many other things) translates idiom brackets into standard uses of <code>(<$>)</code> and <code>(<*>)</code>. This can result in much more readable code when making heavy use of <code>Applicative</code>.<br />
<br />
==Further reading==<br />
<br />
There are many other useful combinators in the standard libraries implemented in terms of <code>pure</code> and <code>(<*>)</code>: for example, <code>(*>)</code>, <code>(<*)</code>, <code>(<**>)</code>, <code>(<$)</code>, and so on (see [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html haddock for Applicative]). Judicious use of such secondary combinators can often make code using <code>Applicative</code>s much easier to read.<br />
<br />
[http://www.soi.city.ac.uk/~ross/papers/Applicative.html McBride and Paterson’s original paper] is a treasure-trove of information and examples, as well as some perspectives on the connection between <code>Applicative</code> and category theory. Beginners will find it difficult to make it through the entire paper, but it is extremely well-motivated—even beginners will be able to glean something from reading as far as they are able.<br />
<br />
{{note|Introduced by [http://conal.net/papers/simply-reactive/ an earlier paper] that was since superseded by [http://conal.net/papers/push-pull-frp/ Push-pull functional reactive programming].}}<br />
<br />
Conal Elliott has been one of the biggest proponents of <code>Applicative</code>. For example, the [http://conal.net/papers/functional-images/ Pan library for functional images] and the reactive library for functional reactive programming (FRP) {{noteref}} make key use of it; his blog also contains [http://conal.net/blog/tag/applicative-functor many examples of <code>Applicative</code> in action]. Building on the work of McBride and Paterson, Elliott also built the [[TypeCompose]] library, which embodies the observation (among others) that <code>Applicative</code> types are closed under composition; therefore, <code>Applicative</code> instances can often be automatically derived for complex types built out of simpler ones.<br />
<br />
Although the [http://hackage.haskell.org/package/parsec Parsec parsing library] ([http://legacy.cs.uu.nl/daan/download/papers/parsec-paper.pdf paper]) was originally designed for use as a monad, in its most common use cases an <code>Applicative</code> instance can be used to great effect; [http://www.serpentine.com/blog/2008/02/06/the-basics-of-applicative-functors-put-to-practical-work/ Bryan O’Sullivan’s blog post] is a good starting point. If the extra power provided by <code>Monad</code> isn’t needed, it’s usually a good idea to use <code>Applicative</code> instead.<br />
<br />
A couple other nice examples of <code>Applicative</code> in action include the [http://chrisdone.com/blog/html/2009-02-10-applicative-configfile-hsql.html ConfigFile and HSQL libraries] and the [http://groups.inf.ed.ac.uk/links/formlets/ formlets library].<br />
<br />
=Monad=<br />
<br />
It’s a safe bet that if you’re reading this, you’ve heard of monads—although it’s quite possible you’ve never heard of <code>Applicative</code> before, or <code>Arrow</code>, or even <code>Monoid</code>. Why are monads such a big deal in Haskell? There are several reasons.<br />
<br />
* Haskell does, in fact, single out monads for special attention by making them the framework in which to construct I/O operations.<br />
* Haskell also singles out monads for special attention by providing a special syntactic sugar for monadic expressions: the <code>do</code>-notation.<br />
* <code>Monad</code> has been around longer than other abstract models of computation such as <code>Applicative</code> or <code>Arrow</code>.<br />
* The more monad tutorials there are, the harder people think monads must be, and the more new monad tutorials are written by people who think they finally “get” monads (the [http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/ monad tutorial fallacy]).<br />
<br />
I will let you judge for yourself whether these are good reasons.<br />
<br />
In the end, despite all the hoopla, <code>Monad</code> is just another type class. Let’s take a look at its definition.<br />
<br />
==Definition==<br />
<br />
The type class declaration for [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad <code>Monad</code>] is:<br />
<br />
<haskell><br />
class Monad m where<br />
return :: a -> m a<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
(>>) :: m a -> m b -> m b<br />
m >> n = m >>= \_ -> n<br />
<br />
fail :: String -> m a<br />
</haskell><br />
<br />
The <code>Monad</code> type class is exported by the <code>Prelude</code>, along with a few standard instances. However, many utility functions are found in [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html <code>Control.Monad</code>], and there are also several instances (such as <code>((->) e)</code>) defined in [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad-Instances.html <code>Control.Monad.Instances</code>].<br />
<br />
Let’s examine the methods in the <code>Monad</code> class one by one. The type of <code>return</code> should look familiar; it’s the same as <code>pure</code>. Indeed, <code>return</code> ''is'' <code>pure</code>, but with an unfortunate name. (Unfortunate, since someone coming from an imperative programming background might think that <code>return</code> is like the C or Java keyword of the same name, when in fact the similarities are minimal.) From a mathematical point of view, every monad is an applicative functor, but for historical reasons, the <code>Monad</code> type class declaration unfortunately does not require this.<br />
<br />
We can see that <code>(>>)</code> is a specialized version of <code>(>>=)</code>, with a default implementation given. It is only included in the type class declaration so that specific instances of <code>Monad</code> can override the default implementation of <code>(>>)</code> with a more efficient one, if desired. Also, note that although <code>_ >> n = n</code> would be a type-correct implementation of <code>(>>)</code>, it would not correspond to the intended semantics: the intention is that <code>m >> n</code> ignores the ''result'' of <code>m</code>, but not its ''effects''.<br />
<br />
The <code>fail</code> function is an awful hack that has no place in the <code>Monad</code> class; more on this later.<br />
<br />
The only really interesting thing to look at—and what makes <code>Monad</code> strictly more powerful than <code>Applicative</code>—is <code>(>>=)</code>, which is often called ''bind''. An alternative definition of <code>Monad</code> could look like:<br />
<br />
<haskell><br />
class Applicative m => Monad' m where<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
</haskell><br />
<br />
We could spend a while talking about the intuition behind <code>(>>=)</code>—and we will. But first, let’s look at some examples.<br />
<br />
==Instances==<br />
<br />
Even if you don’t understand the intuition behind the <code>Monad</code> class, you can still create instances of it by just seeing where the types lead you. You may be surprised to find that this actually gets you a long way towards understanding the intuition; at the very least, it will give you some concrete examples to play with as you read more about the <code>Monad</code> class in general. The first few examples are from the standard <code>Prelude</code>; the remaining examples are from the [http://hackage.haskell.org/package/transformers <code>transformers</code> package].<br />
<br />
<ul><br />
<li>The simplest possible instance of <code>Monad</code> is [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Identity.html <code>Identity</code>], which is described in Dan Piponi’s highly recommended blog post on [http://blog.sigfpe.com/2007/04/trivial-monad.html The Trivial Monad]. Despite being “trivial”, it is a great introduction to the <code>Monad</code> type class, and contains some good exercises to get your brain working.<br />
</li><br />
<li>The next simplest instance of <code>Monad</code> is <code>Maybe</code>. We already know how to write <code>return</code>/<code>pure</code> for <code>Maybe</code>. So how do we write <code>(>>=)</code>? Well, let’s think about its type. Specializing for <code>Maybe</code>, we have<br />
<br />
<haskell><br />
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b.<br />
</haskell><br />
<br />
If the first argument to <code>(>>=)</code> is <code>Just x</code>, then we have something of type <code>a</code> (namely, <code>x</code>), to which we can apply the second argument—resulting in a <code>Maybe b</code>, which is exactly what we wanted. What if the first argument to <code>(>>=)</code> is <code>Nothing</code>? In that case, we don’t have anything to which we can apply the <code>a -> Maybe b</code> function, so there’s only one thing we can do: yield <code>Nothing</code>. This instance is:<br />
<br />
<haskell><br />
instance Monad Maybe where<br />
return = Just<br />
(Just x) >>= g = g x<br />
Nothing >>= _ = Nothing<br />
</haskell><br />
<br />
We can already get a bit of intuition as to what is going on here: if we build up a computation by chaining together a bunch of functions with <code>(>>=)</code>, as soon as any one of them fails, the entire computation will fail (because <code>Nothing >>= f</code> is <code>Nothing</code>, no matter what <code>f</code> is). The entire computation succeeds only if all the constituent functions individually succeed. So the <code>Maybe</code> monad models computations which may fail.<br />
</li><br />
<br />
<li>The <code>Monad</code> instance for the list constructor <code>[]</code> is similar to its <code>Applicative</code> instance; see the exercise below.<br />
</li><br />
<br />
<li>Of course, the <code>IO</code> constructor is famously a <code>Monad</code>, but its implementation is somewhat magical, and may in fact differ from compiler to compiler. It is worth emphasizing that the <code>IO</code> monad is the ''only'' monad which is magical. It allows us to build up, in an entirely pure way, values representing possibly effectful computations. The special value <code>main</code>, of type <code>IO ()</code>, is taken by the runtime and actually executed, producing actual effects. Every other monad is functionally pure, and requires no special compiler support. We often speak of monadic values as “effectful computations”, but this is because some monads allow us to write code ''as if'' it has side effects, when in fact the monad is hiding the plumbing which allows these apparent side effects to be implemented in a functionally pure way.<br />
</li><br />
<br />
<li>As mentioned earlier, <code>((->) e)</code> is known as the ''reader monad'', since it describes computations in which a value of type <code>e</code> is available as a read-only environment.<br />
<br />
The [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Reader.html <code>Control.Monad.Reader</code>] module provides the <code>Reader e a</code> type, which is just a convenient <code>newtype</code> wrapper around <code>(e -> a)</code>, along with an appropriate <code>Monad</code> instance and some <code>Reader</code>-specific utility functions such as <code>ask</code> (retrieve the environment), <code>asks</code> (retrieve a function of the environment), and <code>local</code> (run a subcomputation under a different environment).<br />
</li><br />
<br />
<li>The [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Writer-Lazy.html <code>Control.Monad.Writer</code>] module provides the <code>Writer</code> monad, which allows information to be collected as a computation progresses. <code>Writer w a</code> is isomorphic to <code>(a,w)</code>, where the output value <code>a</code> is carried along with an annotation or “log” of type <code>w</code>, which must be an instance of <code>Monoid</code> (see [[#Monoid|section Monoid]]); the special function <code>tell</code> performs logging.<br />
</li><br />
<br />
<li>The [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State-Lazy.html <code>Control.Monad.State</code>] module provides the <code>State s a</code> type, a <code>newtype</code> wrapper around <code>s -> (a,s)</code>. Something of type <code>State s a</code> represents a stateful computation which produces an <code>a</code> but can access and modify the state of type <code>s</code> along the way. The module also provides <code>State</code>-specific utility functions such as <code>get</code> (read the current state), <code>gets</code> (read a function of the current state), <code>put</code> (overwrite the state), and <code>modify</code> (apply a function to the state).<br />
</li><br />
<br />
<li>The [http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-Cont.html <code>Control.Monad.Cont</code>] module provides the <code>Cont</code> monad, which represents computations in continuation-passing style. It can be used to suspend and resume computations, and to implement non-local transfers of control, co-routines, other complex control structures—all in a functionally pure way. <code>Cont</code> has been called the [http://blog.sigfpe.com/2008/12/mother-of-all-monads.html “mother of all monads”] because of its universal properties.<br />
</li><br />
</ul><br />
<br />
{{Exercises|<br />
<ol><br />
<li>Implement a <code>Monad</code> instance for the list constructor, <code>[]</code>. Follow the types!</li><br />
<li>Implement a <code>Monad</code> instance for <code>((->) e)</code>.</li><br />
<li>Implement <code>Functor</code> and <code>Monad</code> instances for <code>Free f</code>, defined as<br />
<haskell><br />
data Free f a = Var a<br />
| Node (f (Free f a))<br />
</haskell><br />
You may assume that <code>f</code> has a <code>Functor</code> instance. This is known as the ''free monad'' built from the functor <code>f</code>.<br />
</li><br />
</ol><br />
}}<br />
<br />
==Intuition==<br />
<br />
Let’s look more closely at the type of <code>(>>=)</code>. The basic intuition is that it combines two computations into one larger computation. The first argument, <code>m a</code>, is the first computation. However, it would be boring if the second argument were just an <code>m b</code>; then there would be no way for the computations to interact with one another (actually, this is exactly the situation with <code>Applicative</code>). So, the second argument to <code>(>>=)</code> has type <code>a -> m b</code>: a function of this type, given a ''result'' of the first computation, can produce a second computation to be run. In other words, <code>x >>= k</code> is a computation which runs <code>x</code>, and then uses the result(s) of <code>x</code> to ''decide'' what computation to run second, using the output of the second computation as the result of the entire computation.<br />
<br />
{{note|Actually, because Haskell allows general recursion, this is a lie: using a Haskell parsing library one can recursively construct ''infinite'' grammars, and hence <code>Alternative</code> by itself is enough to parse any context-sensitive language with a finite alphabet. Simply make an n-way choice on each symbol you care about, and "encode" the context by having a different nonterminal for every possible pairing of a context and a nonterminal from the original grammar. However, no one in their right mind would want to write a context-sensitive parser this way!}}<br />
Intuitively, it is this ability to use the output from previous computations to decide what computations to run next that makes <code>Monad</code> more powerful than <code>Applicative</code>. The structure of an <code>Applicative</code> computation is fixed, whereas the structure of a <code>Monad</code> computation can change based on intermediate results. This also means that parsers built using an <code>Applicative</code> interface can only parse context-free languages; in order to parse context-sensitive languages a <code>Monad</code> interface is needed.{{noteref}}<br />
<br />
To see the increased power of <code>Monad</code> from a different point of view, let’s see what happens if we try to implement <code>(>>=)</code> in terms of <code>fmap</code>, <code>pure</code>, and <code>(<*>)</code>. We are given a value <code>x</code> of type <code>m a</code>, and a function <code>k</code> of type <code>a -> m b</code>, so the only thing we can do is apply <code>k</code> to <code>x</code>. We can’t apply it directly, of course; we have to use <code>fmap</code> to lift it over the <code>m</code>. But what is the type of <code>fmap k</code>? Well, it’s <code>m a -> m (m b)</code>. So after we apply it to <code>x</code>, we are left with something of type <code>m (m b)</code>—but now we are stuck; what we really want is an <code>m b</code>, but there’s no way to get there from here. We can ''add'' <code>m</code>’s using <code>pure</code>, but we have no way to ''collapse'' multiple <code>m</code>’s into one.<br />
<br />
{{note|1=You might hear some people claim that that the definition in terms of <code>return</code>, <code>fmap</code>, and <code>join</code> is the “math definition” and the definition in terms of <code>return</code> and <code>(>>=)</code> is something specific to Haskell. In fact, both definitions were known in the mathematics community long before Haskell picked up monads.}}<br />
<br />
This ability to collapse multiple <code>m</code>’s is exactly the ability provided by the function <code>join :: m (m a) -> m a</code>, and it should come as no surprise that an alternative definition of <code>Monad</code> can be given in terms of <code>join</code>:<br />
<br />
<haskell><br />
class Applicative m => Monad'' m where<br />
join :: m (m a) -> m a<br />
</haskell><br />
<br />
In fact, the earliest definitions of monads in category theory were in terms of <code>return</code>, <code>fmap</code>, and <code>join</code> (often called <math>\eta</math>, <math>T</math>, and <math>\mu</math> in the mathematical literature). Haskell uses an alternative formulation with <code>(>>=)</code> instead of <code>join</code> since it is more convenient to use {{noteref}}. However, sometimes it can be easier to think about <code>Monad</code> instances in terms of <code>join</code>, since it is a more “atomic” operation. (For example, <code>join</code> for the list monad is just <code>concat</code>.)<br />
<br />
{{Exercises|<br />
# Implement <code>(>>{{=}})</code> in terms of <code>fmap</code> (or <code>liftM</code>) and <code>join</code>.<br />
# Now implement <code>join</code> and <code>fmap</code> (<code>liftM</code>) in terms of <code>(>>{{=}})</code> and <code>return</code>.<br />
}}<br />
<br />
==Utility functions==<br />
<br />
The [http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html <code>Control.Monad</code>] module provides a large number of convenient utility functions, all of which can be implemented in terms of the basic <code>Monad</code> operations (<code>return</code> and <code>(>>=)</code> in particular). We have already seen one of them, namely, <code>join</code>. We also mention some other noteworthy ones here; implementing these utility functions oneself is a good exercise. For a more detailed guide to these functions, with commentary and example code, see Henk-Jan van Tuyl’s [http://members.chello.nl/hjgtuyl/tourdemonad.html tour].<br />
<br />
{{note|Still, it is unclear how this "bug" should be fixed. Making <code>Monad</code> require a <code>Functor</code> instance has some drawbacks, as mentioned in this [http://www.haskell.org/pipermail/haskell-prime/2011-January/003312.html 2011 mailing-list discussion]. —Geheimdienst}}<br />
<br />
* <code>liftM :: Monad m => (a -> b) -> m a -> m b</code>. This should be familiar; of course, it is just <code>fmap</code>. The fact that we have both <code>fmap</code> and <code>liftM</code> is an unfortunate consequence of the fact that the <code>Monad</code> type class does not require a <code>Functor</code> instance, even though mathematically speaking, every monad is a functor. However, <code>fmap</code> and <code>liftM</code> are essentially interchangeable, since it is a bug (in a social rather than technical sense) for any type to be an instance of <code>Monad</code> without also being an instance of <code>Functor</code> {{noteref}}.<br />
<br />
* <code>ap :: Monad m => m (a -> b) -> m a -> m b</code> should also be familiar: it is equivalent to <code>(<*>)</code>, justifying the claim that the <code>Monad</code> interface is strictly more powerful than <code>Applicative</code>. We can make any <code>Monad</code> into an instance of <code>Applicative</code> by setting <code>pure = return</code> and <code>(<*>) = ap</code>.<br />
<br />
* <code>sequence :: Monad m => [m a] -> m [a]</code> takes a list of computations and combines them into one computation which collects a list of their results. It is again something of a historical accident that <code>sequence</code> has a <code>Monad</code> constraint, since it can actually be implemented only in terms of <code>Applicative</code>. There is an additional generalization of <code>sequence</code> to structures other than lists, which will be discussed in the [[#Traversable|section on <code>Traversable</code>]].<br />
<br />
* <code>replicateM :: Monad m => Int -> m a -> m [a]</code> is simply a combination of [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:replicate <code>replicate</code>] and <code>sequence</code>.<br />
<br />
* <code>when :: Monad m => Bool -> m () -> m ()</code> conditionally executes a computation, evaluating to its second argument if the test is <code>True</code>, and to <code>return ()</code> if the test is <code>False</code>. A collection of other sorts of monadic conditionals can be found in the [http://hackage.haskell.org/package/IfElse <code>IfElse</code> package].<br />
<br />
* <code>mapM :: Monad m => (a -> m b) -> [a] -> m [b]</code> maps its first argument over the second, and <code>sequence</code>s the results. The <code>forM</code> function is just <code>mapM</code> with its arguments reversed; it is called <code>forM</code> since it models generalized <code>for</code> loops: the list <code>[a]</code> provides the loop indices, and the function <code>a -> m b</code> specifies the “body” of the loop for each index.<br />
<br />
* <code>(=<<) :: Monad m => (a -> m b) -> m a -> m b</code> is just <code>(>>=)</code> with its arguments reversed; sometimes this direction is more convenient since it corresponds more closely to function application.<br />
<br />
* <code>(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c</code> is sort of like function composition, but with an extra <code>m</code> on the result type of each function, and the arguments swapped. We’ll have more to say about this operation later. There is also a flipped variant, <code>(<=<)</code>.<br />
<br />
* The <code>guard</code> function is for use with instances of <code>MonadPlus</code>, which is discussed at the end of the [[#Monoid|<code>Monoid</code> section]].<br />
<br />
Many of these functions also have “underscored” variants, such as <code>sequence_</code> and <code>mapM_</code>; these variants throw away the results of the computations passed to them as arguments, using them only for their side effects.<br />
<br />
Other monadic functions which are occasionally useful include <code>filterM</code>, <code>zipWithM</code>, <code>foldM</code>, and <code>forever</code>. <br />
<br />
==Laws==<br />
<br />
There are several laws that instances of <code>Monad</code> should satisfy (see also the [[Monad laws]] wiki page). The standard presentation is:<br />
<br />
<haskell><br />
return a >>= k = k a<br />
m >>= return = m<br />
m >>= (\x -> k x >>= h) = (m >>= k) >>= h<br />
<br />
fmap f xs = xs >>= return . f = liftM f xs<br />
</haskell><br />
<br />
The first and second laws express the fact that <code>return</code> behaves nicely: if we inject a value <code>a</code> into a monadic context with <code>return</code>, and then bind to <code>k</code>, it is the same as just applying <code>k</code> to <code>a</code> in the first place; if we bind a computation <code>m</code> to <code>return</code>, nothing changes. The third law essentially says that <code>(>>=)</code> is associative, sort of. The last law ensures that <code>fmap</code> and <code>liftM</code> are the same for types which are instances of both <code>Functor</code> and <code>Monad</code>—which, as already noted, should be every instance of <code>Monad</code>.<br />
<br />
{{note|I like to pronounce this operator “fish”, but that’s probably not the canonical pronunciation ...}}<br />
<br />
However, the presentation of the above laws, especially the third, is marred by the asymmetry of <code>(>>=)</code>. It’s hard to look at the laws and see what they’re really saying. I prefer a much more elegant version of the laws, which is formulated in terms of <code>(>=>)</code> {{noteref}}. Recall that <code>(>=>)</code> “composes” two functions of type <code>a -> m b</code> and <code>b -> m c</code>. You can think of something of type <code>a -> m b</code> (roughly) as a function from <code>a</code> to <code>b</code> which may also have some sort of effect in the context corresponding to <code>m</code>. <code>(>=>)</code> lets us compose these “effectful functions”, and we would like to know what properties <code>(>=>)</code> has. The monad laws reformulated in terms of <code>(>=>)</code> are:<br />
<br />
<haskell><br />
return >=> g = g<br />
g >=> return = g<br />
(g >=> h) >=> k = g >=> (h >=> k)<br />
</haskell><br />
<br />
{{note|As fans of category theory will note, these laws say precisely that functions of type <code>a -> m b</code> are the arrows of a category with <code>(>{{=}}>)</code> as composition! Indeed, this is known as the ''Kleisli category'' of the monad <code>m</code>. It will come up again when we discuss <code>Arrow</code>s.}}<br />
<br />
Ah, much better! The laws simply state that <code>return</code> is the identity of <code>(>=>)</code>, and that <code>(>=>)</code> is associative {{noteref}}. Working out the equivalence between these two formulations, given the definition <code>g >=> h = \x -> g x >>= h</code>, is left as an exercise.<br />
<br />
There is also a formulation of the monad laws in terms of <code>fmap</code>, <code>return</code>, and <code>join</code>; for a discussion of this formulation, see the Haskell [http://en.wikibooks.org/wiki/Haskell/Category_theory wikibook page on category theory].<br />
<br />
==<code>do</code> notation==<br />
<br />
Haskell’s special <code>do</code> notation supports an “imperative style” of programming by providing syntactic sugar for chains of monadic expressions. The genesis of the notation lies in realizing that something like <code>a >>= \x -> b >> c >>= \y -> d </code> can be more readably written by putting successive computations on separate lines:<br />
<br />
<haskell><br />
a >>= \x -><br />
b >><br />
c >>= \y -><br />
d<br />
</haskell><br />
<br />
This emphasizes that the overall computation consists of four computations <code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code>, and that <code>x</code> is bound to the result of <code>a</code>, and <code>y</code> is bound to the result of <code>c</code> (<code>b</code>, <code>c</code>, and <code>d</code> are allowed to refer to <code>x</code>, and <code>d</code> is allowed to refer to <code>y</code> as well). From here it is not hard to imagine a nicer notation:<br />
<br />
<haskell><br />
do { x <- a ;<br />
b ;<br />
y <- c ;<br />
d<br />
}<br />
</haskell><br />
<br />
(The curly braces and semicolons may optionally be omitted; the Haskell parser uses layout to determine where they should be inserted.) This discussion should make clear that <code>do</code> notation is just syntactic sugar. In fact, <code>do</code> blocks are recursively translated into monad operations (almost) like this:<br />
<br />
<pre><br />
do e → e<br />
do { e; stmts } → e >> do { stmts }<br />
do { v <- e; stmts } → e >>= \v -> do { stmts }<br />
do { let decls; stmts} → let decls in do { stmts }<br />
</pre><br />
<br />
This is not quite the whole story, since <code>v</code> might be a pattern instead of a variable. For example, one can write<br />
<br />
<haskell><br />
do (x:xs) <- foo<br />
bar x<br />
</haskell><br />
<br />
but what happens if <code>foo</code> produces an empty list? Well, remember that ugly <code>fail</code> function in the <code>Monad</code> type class declaration? That’s what happens. See [http://haskell.org/onlinereport/exps.html#sect3.14 section 3.14 of the Haskell Report] for the full details. See also the discussion of <code>MonadPlus</code> and <code>MonadZero</code> in the [[#Other monoidal classes: Alternative, MonadPlus, ArrowPlus|section on other monoidal classes]].<br />
<br />
A final note on intuition: <code>do</code> notation plays very strongly to the “computational context” point of view rather than the “container” point of view, since the binding notation <code>x <- m</code> is suggestive of “extracting” a single <code>x</code> from <code>m</code> and doing something with it. But <code>m</code> may represent some sort of a container, such as a list or a tree; the meaning of <code>x <- m</code> is entirely dependent on the implementation of <code>(>>=)</code>. For example, if <code>m</code> is a list, <code>x <- m</code> actually means that <code>x</code> will take on each value from the list in turn.<br />
<br />
==Further reading==<br />
<br />
Philip Wadler was the first to propose using monads to structure functional programs. [http://homepages.inf.ed.ac.uk/wadler/topics/monads.html His paper] is still a readable introduction to the subject.<br />
<br />
{{note|1=<br />
[[All About Monads]],<br />
[http://haskell.org/haskellwiki/Monads_as_Containers Monads as containers],<br />
[http://en.wikibooks.org/w/index.php?title=Haskell/Understanding_monads&oldid=933545 Understanding monads],<br />
[[The Monadic Way]],<br />
[http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html You Could Have Invented Monads! (And Maybe You Already Have.)],<br />
[http://www.haskell.org/pipermail/haskell-cafe/2006-November/019190.html there’s a monster in my Haskell!],<br />
[http://kawagner.blogspot.com/2007/02/understanding-monads-for-real.html Understanding Monads. For real.],<br />
[http://www.randomhacks.net/articles/2007/03/12/monads-in-15-minutes Monads in 15 minutes: Backtracking and Maybe],<br />
[http://haskell.org/haskellwiki/Monads_as_computation Monads as computation],<br />
[http://metafoo.co.uk/practical-monads.txt Practical Monads]}}<br />
<br />
There are, of course, numerous monad tutorials of varying quality {{noteref}}.<br />
<br />
A few of the best include Cale Gibbard’s [http://haskell.org/haskellwiki/Monads_as_Containers Monads as containers] and [http://haskell.org/haskellwiki/Monads_as_computation Monads as computation]; Jeff Newbern’s [[All About Monads]], a comprehensive guide with lots of examples; and Dan Piponi’s [http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html You Could Have Invented Monads!], which features great exercises. If you just want to know how to use <code>IO</code>, you could consult the [[Introduction to IO]]. Even this is just a sampling; the [[monad tutorials timeline]] is a more complete list. (All these monad tutorials have prompted parodies like [http://koweycode.blogspot.com/2007/01/think-of-monad.html think of a monad ...] as well as other kinds of backlash like [http://ahamsandwich.wordpress.com/2007/07/26/monads-and-why-monad-tutorials-are-all-awful/ Monads! (and Why Monad Tutorials Are All Awful)] or [http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/ Abstraction, intuition, and the “monad tutorial fallacy”].)<br />
<br />
Other good monad references which are not necessarily tutorials include [http://members.chello.nl/hjgtuyl/tourdemonad.html Henk-Jan van Tuyl’s tour] of the functions in <code>Control.Monad</code>, Dan Piponi’s [http://blog.sigfpe.com/2006/10/monads-field-guide.html field guide], and Tim Newsham’s [http://www.thenewsh.com/~newsham/haskell/monad.html What’s a Monad?]. There are also many blog posts which have been written on various aspects of monads; a collection of links can be found under [[Blog articles/Monads]].<br />
<br />
One of the quirks of the <code>Monad</code> class and the Haskell type system is that it is not possible to straightforwardly declare <code>Monad</code> instances for types which require a class constraint on their data, even if they are monads from a mathematical point of view. For example, <code>Data.Set</code> requires an <code>Ord</code> constraint on its data, so it cannot be easily made an instance of <code>Monad</code>. A solution to this problem was [http://www.randomhacks.net/articles/2007/03/15/data-set-monad-haskell-macros first described by Eric Kidd], and later made into a [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/rmonad library named rmonad] by Ganesh Sittampalam and Peter Gavin.<br />
<br />
There are many good reasons for eschewing <code>do</code> notation; some have gone so far as to [[Do_notation_considered_harmful|consider it harmful]].<br />
<br />
Monads can be generalized in various ways; for an exposition of one possibility, see Robert Atkey’s paper on [http://homepages.inf.ed.ac.uk/ratkey/paramnotions-jfp.pdf parameterized monads], or Dan Piponi’s [http://blog.sigfpe.com/2009/02/beyond-monads.html Beyond Monads].<br />
<br />
For the categorically inclined, monads can be viewed as monoids ([http://blog.sigfpe.com/2008/11/from-monoids-to-monads.html From Monoids to Monads]) and also as closure operators [http://blog.plover.com/math/monad-closure.html Triples and Closure]. Derek Elkins’s article in [http://www.haskell.org/wikiupload/8/85/TMR-Issue13.pdf issue 13 of the Monad.Reader] contains an exposition of the category-theoretic underpinnings of some of the standard <code>Monad</code> instances, such as <code>State</code> and <code>Cont</code>.<br />
<br />
Links to many more research papers related to monads can be found under [[Research papers/Monads and arrows]].<br />
<br />
=Monad transformers=<br />
<br />
One would often like to be able to combine two monads into one: for example, to have stateful, nondeterministic computations (<code>State</code> + <code>[]</code>), or computations which may fail and can consult a read-only environment (<code>Maybe</code> + <code>Reader</code>), and so on. Unfortunately, monads do not compose as nicely as applicative functors (yet another reason to use <code>Applicative</code> if you don’t need the full power that <code>Monad</code> provides), but some monads can be combined in certain ways.<br />
<br />
==Standard monad transformers==<br />
<br />
The [http://hackage.haskell.org/package/transformers transformers] library provides a number of standard ''monad transformers''. Each monad transformer adds a particular capability/feature/effect to any existing monad.<br />
<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Identity.html <code>IdentityT</code>] is the identity transformer, which maps a monad to (something isomorphic to) itself. This may seem useless at first glance, but it is useful for the same reason that the <code>id</code> function is useful -- it can be passed as an argument to things which are parameterized over an arbitrary monad transformer.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-State.html <code>StateT</code>] adds a read-write state.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Reader.html <code>ReaderT</code>] adds a read-only environment.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Writer.html <code>WriterT</code>] adds a write-only log.<br />
* [http://hackage.haskell.org/packages/archive/transformers/0.2.2.0/doc/html/Control-Monad-Trans-RWS.html <code>RWST</code>] conveniently combines <code>ReaderT</code>, <code>WriterT</code>, and <code>StateT</code> into one.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Maybe.html <code>MaybeT</code>] adds the possibility of failure.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Error.html <code>ErrorT</code>] adds the possibility of failure with an arbitrary type to represent errors.<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-List.html <code>ListT</code>] adds non-determinism (however, see the discussion of <code>ListT</code> below).<br />
* [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Control-Monad-Trans-Cont.html <code>ContT</code>] adds continuation handling.<br />
<br />
For example, <code>StateT s Maybe</code> is an instance of <code>Monad</code>; computations of type <code>StateT s Maybe a</code> may fail, and have access to a mutable state of type <code>s</code>. Monad transformers can be multiply stacked. One thing to keep in mind while using monad transformers is that the order of composition matters. For example, when a <code>StateT s Maybe a</code> computation fails, the state ceases being updated (indeed, it simply disappears); on the other hand, the state of a <code>MaybeT (State s) a</code> computation may continue to be modified even after the computation has failed. This may seem backwards, but it is correct. Monad transformers build composite monads “inside out”; <code>MaybeT (State s) a</code> is isomorphic to <code>s -> (Maybe a, s)</code>. (Lambdabot has an indispensable <code>@unmtl</code> command which you can use to “unpack” a monad transformer stack in this way.)<br />
Intuitively, the monads become "more fundamental" the further down in the stack you get, and the effects of a given monad "have precedence" over the effects of monads further up the stack. Of course, this is just handwaving, and if you are unsure of the proper order for some monads you wish to combine, there is no substitute for using <code>@unmtl</code> or simply trying out the various options.<br />
<br />
==Definition and laws==<br />
<br />
All monad transformers should implement the <code>MonadTrans</code> type class, defined in <code>Control.Monad.Trans.Class</code>:<br />
<br />
<haskell><br />
class MonadTrans t where<br />
lift :: Monad m => m a -> t m a<br />
</haskell><br />
<br />
It allows arbitrary computations in the base monad <code>m</code> to be “lifted” into computations in the transformed monad <code>t m</code>. (Note that type application associates to the left, just like function application, so <code>t m a = (t m) a</code>.)<br />
<br />
<code>lift</code> must satisfy the laws<br />
<haskell><br />
lift . return = return<br />
lift (m >>= f) = lift m >>= (lift . f)<br />
</haskell><br />
which intuitively state that <code>lift</code> transforms <code>m a</code> computations into <code>t m a</code> computations in a "sensible" way, which sends the <code>return</code> and <code>(>>=)</code> of <code>m</code> to the <code>return</code> and <code>(>>=)</code> of <code>t m</code>.<br />
<br />
{{Exercises|<br />
# What is the kind of <code>t</code> in the declaration of <code>MonadTrans</code>?<br />
}}<br />
<br />
==Transformer type classes and "capability" style==<br />
<br />
{{note|The only problem with this scheme is the quadratic number of instances required as the number of standard monad transformers grows—but as the current set of standard monad transformers seems adequate for most common use cases, this may not be that big of a deal.}}<br />
<br />
There are also type classes (provided by the [http://hackage.haskell.org/package/mtl <code>mtl</code> package]) for the operations of each transformer. For example, the <code>MonadState</code> type class provides the state-specific methods <code>get</code> and <code>put</code>, allowing you to conveniently use these methods not only with <code>State</code>, but with any monad which is an instance of <code>MonadState</code>—including <code>MaybeT (State s)</code>, <code>StateT s (ReaderT r IO)</code>, and so on. Similar type classes exist for <code>Reader</code>, <code>Writer</code>, <code>Cont</code>, <code>IO</code>, and others {{noteref}}.<br />
<br />
These type classes serve two purposes. First, they get rid of (most of) the need for explicitly using <code>lift</code>, giving a type-directed way to automatically determine the right number of calls to <code>lift</code>. Simply writing <code>put</code> will be automatically translated into <code>lift . put</code>, <code>lift . lift . put</code>, or something similar depending on what concrete monad stack you are using.<br />
<br />
Second, they give you more flexibility to switch between different concrete monad stacks. For example, if you are writing a state-based algorithm, don't write<br />
<haskell><br />
foo :: State Int Char<br />
foo = modify (*2) >> return 'x'<br />
</haskell><br />
but rather<br />
<haskell><br />
foo :: MonadState Int m => m Char<br />
foo = modify (*2) >> return 'x'<br />
</haskell><br />
Now, if somewhere down the line you realize you need to introduce the possibility of failure, you might switch from <code>State Int</code> to <code>MaybeT (State Int)</code>. The type of the first version of <code>foo</code> would need to be modified to reflect this change, but the second version of <code>foo</code> can still be used as-is.<br />
<br />
However, this sort of "capability-based" style (<i>e.g.</i> specifying that <code>foo</code> works for any monad with the "state capability") quickly runs into problems when you try to naively scale it up: for example, what if you need to maintain two independent states? A very nice framework for solving this and related problems is described by Schrijvers and Olivera ([http://users.ugent.be/~tschrijv/Research/papers/icfp2011.pdf Monads, zippers and views: virtualizing the monad stack, ICFP 2011]) and is implemented in the [http://hackage.haskell.org/package/Monatron <code>Monatron</code> package].<br />
<br />
==Composing monads==<br />
<br />
Is the composition of two monads always a monad? As hinted previously, the answer is no. For example, ''XXX insert example here''.<br />
<br />
Since <code>Applicative</code> functors are closed under composition, the problem must lie with <code>join</code>. Indeed, suppose <code>m</code> and <code>n</code> are arbitrary monads; to make a monad out of their composition we would need to be able to implement<br />
<haskell><br />
join :: m (n (m (n a))) -> m (n a)<br />
</haskell><br />
but it is not clear how this could be done in general. The <code>join</code> method for <code>m</code> is no help, because the two occurrences of <code>m</code> are not next to each other (and likewise for <code>n</code>).<br />
<br />
However, one situation in which it can be done is if <code>n</code> ''distributes'' over <code>m</code>, that is, if there is a function<br />
<haskell><br />
distrib :: n (m a) -> m (n a)<br />
</haskell><br />
satisfying certain laws. See Jones and Duponcheel ([http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2605 Composing Monads]).<br />
<br />
{{Exercises|<br />
* Implement <code>join :: M (N (M (N a))) -> M (N a)</code>, given <code>distrib :: N (M a) -> M (N a)</code> and assuming <code>M</code> and <code>N</code> are instances of <code>Monad</code>.<br />
}}<br />
<br />
==Further reading==<br />
<br />
Much of the monad transformer library (originally [http://hackage.haskell.org/package/mtl <code>mtl</code>], now split between <code>mtl</code> and [http://hackage.haskell.org/package/transformers <code>transformers</code>]), including the <code>Reader</code>, <code>Writer</code>, <code>State</code>, and other monads, as well as the monad transformer framework itself, was inspired by Mark Jones’s classic paper [http://web.cecs.pdx.edu/~mpj/pubs/springschool.html Functional Programming with Overloading and Higher-Order Polymorphism]. It’s still very much worth a read—and highly readable—after almost fifteen years.<br />
<br />
There are two excellent references on monad transformers. Martin Grabmüller’s [http://www.grabmueller.de/martin/www/pub/Transformers.en.html Monad Transformers Step by Step] is a thorough description, with running examples, of how to use monad transformers to elegantly build up computations with various effects. [http://cale.yi.org/index.php/How_To_Use_Monad_Transformers Cale Gibbard’s article] on how to use monad transformers is more practical, describing how to structure code using monad transformers to make writing it as painless as possible. Another good starting place for learning about monad transformers is a [http://blog.sigfpe.com/2006/05/grok-haskell-monad-transformers.html blog post by Dan Piponi].<br />
<br />
The <code>ListT</code> transformer from the <code>transformers</code> package comes with the caveat that <code>ListT m</code> is only a monad when <code>m</code> is ''commutative'', that is, when <code>ma >>= \a -> mb >>= \b -> foo</code> is equivalent to <code>mb >>= \b -> ma >>= \a -> foo</code> (i.e. the order of <code>m</code>'s effects does not matter). For one explanation why, see Dan Piponi's blog post [http://blog.sigfpe.com/2006/11/why-isnt-listt-monad.html "Why isn't <code><nowiki>ListT []</nowiki></code> a monad"]. For more examples, as well as a design for a version of <code>ListT</code> which does not have this problem, see [http://haskell.org/haskellwiki/ListT_done_right <code>ListT</code> done right].<br />
<br />
There is an alternative way to compose monads, using coproducts, as described by [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.8.3581 Lüth and Ghani]. This method is interesting but has not (yet?) seen widespread use.<br />
<br />
=MonadFix=<br />
<br />
''Note: <code>MonadFix</code> is included here for completeness (and because it is interesting) but seems not to be used much. Skipping this section on a first read-through is perfectly OK (and perhaps even recommended).''<br />
<br />
==<code>do rec</code> notation==<br />
<br />
The <code>MonadFix</code> class describes monads which support the special fixpoint operation <code>mfix :: (a -> m a) -> m a</code>, which allows the output of monadic computations to be defined via (effectful) recursion. This is [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#recursive-do-notation supported in GHC] by a special “recursive do” notation, enabled by the <code>-XDoRec</code> flag. Within a <code>do</code> block, one may have a nested <code>rec</code> block, like so:<br />
<haskell><br />
do { x <- foo<br />
; rec { y <- baz<br />
; z <- bar<br />
; bob<br />
}<br />
; w <- frob<br />
}<br />
</haskell><br />
Normally (if we had <code>do</code> in place of <code>rec</code> in the above example), <code>y</code> would be in scope in <code>bar</code> and <code>bob</code> but not in <code>baz</code>, and <code>z</code> would be in scope only in <code>bob</code>. With the <code>rec</code>, however, <code>y</code> and <code>z</code> are both in scope in all three of <code>baz</code>, <code>bar</code>, and <code>bob</code>. A <code>rec</code> block is analogous to a <code>let</code> block such as<br />
<haskell><br />
let { y = baz<br />
; z = bar<br />
}<br />
in bob<br />
</haskell><br />
because, in Haskell, every variable bound in a <code>let</code>-block is in scope throughout the entire block. (From this point of view, Haskell's normal <code>do</code> blocks are analogous to Scheme's <code>let*</code> construct.)<br />
<br />
What could such a feature be used for? One of the motivating examples given in the original paper describing <code>MonadFix</code> (see below) is encoding circuit descriptions. A line in a <code>do</code>-block such as <br />
<haskell><br />
x <- gate y z<br />
</haskell><br />
describes a gate whose input wires are labeled <code>y</code> and <code>z</code> and whose output wire is labeled <code>x</code>. Many (most?) useful circuits, however, involve some sort of feedback loop, making them impossible to write in a normal <code>do</code>-block (since some wire would have to be mentioned as an input ''before'' being listed as an output). Using a <code>rec</code> block solves this problem.<br />
<br />
==Examples and intuition==<br />
<br />
Of course, not every monad supports such recursive binding. However, as mentioned above, it suffices to have an implementation of <code>mfix :: (a -> m a) -> m a</code>, satisfying a few laws. Let's try implementing <code>mfix</code> for the <code>Maybe</code> monad. That is, we want to implement a function<br />
<haskell><br />
maybeFix :: (a -> Maybe a) -> Maybe a<br />
</haskell><br />
{{note|Actually, <code>fix</code> is implemented slightly differently for efficiency reasons; but the given definition is equivalent and simpler for the present purpose.}}<br />
Let's think for a moment about the implementation {{noteref}} of the non-monadic <code>fix :: (a -> a) -> a</code>:<br />
<haskell><br />
fix f = f (fix f)<br />
</haskell><br />
Inspired by <code>fix</code>, our first attempt at implementing <code>maybeFix</code> might be something like<br />
<haskell><br />
maybeFix :: (a -> Maybe a) -> Maybe a<br />
maybeFix f = maybeFix f >>= f<br />
</haskell><br />
This has the right type. However, something seems wrong: there is nothing in particular here about <code>Maybe</code>; <code>maybeFix</code> actually has the more general type <code>Monad m => (a -> m a) -> m a</code>. But didn't we just say that not all monads support <code>mfix</code>?<br />
<br />
The answer is that although this implementation of <code>maybeFix</code> has the right type, it does ''not'' have the intended semantics. If we think about how <code>(>>=)</code> works for the <code>Maybe</code> monad (by pattern-matching on its first argument to see whether it is <code>Nothing</code> or <code>Just</code>) we can see that this definition of <code>maybeFix</code> is completely useless: it will just recurse infinitely, trying to decide whether it is going to return <code>Nothing</code> or <code>Just</code>, without ever even so much as a glance in the direction of <code>f</code>.<br />
<br />
The trick is to simply ''assume'' that <code>maybeFix</code> will return <code>Just</code>, and get on with life!<br />
<haskell><br />
maybeFix :: (a -> Maybe a) -> Maybe a<br />
maybeFix f = ma<br />
where ma = f (fromJust ma)<br />
</haskell><br />
This says that the result of <code>maybeFix</code> is <code>ma</code>, and assuming that <code>ma = Just x</code>, it is defined (recursively) to be equal to <code>f x</code>.<br />
<br />
Why is this OK? Isn't <code>fromJust</code> almost as bad as <code>unsafePerformIO</code>? Well, usually, yes. This is just about the only situation in which it is justified! The interesting thing to note is that <code>maybeFix</code> ''will never crash'' -- although it may, of course, fail to terminate. The only way we could get a crash is if we try to evaluate <code>fromJust ma</code> when we know that <code>ma = Nothing</code>. But how could we know <code>ma = Nothing</code>? Since <code>ma</code> is defined as <code>f (fromJust ma)</code>, it must be that this expression has already been evaluated to <code>Nothing</code> -- in which case there is no reason for us to be evaluating <code>fromJust ma</code> in the first place! <br />
<br />
To see this from another point of view, we can consider three possibilities. First, if <code>f</code> outputs <code>Nothing</code> without looking at its argument, then <code>maybeFix f</code> clearly returns <code>Nothing</code>. Second, if <code>f</code> always outputs <code>Just x</code>, where <code>x</code> depends on its argument, then the recursion can proceed usefully: <code>fromJust ma</code> will be able to evaluate to <code>x</code>, thus feeding <code>f</code>'s output back to it as input. Third, if <code>f</code> tries to use its argument to decide whether to output <code>Just</code> or <code>Nothing</code>, then <code>maybeFix f</code> will not terminate: evaluating <code>f</code>'s argument requires evaluating <code>ma</code> to see whether it is <code>Just</code>, which requires evaluating <code>f (fromJust ma)</code>, which requires evaluating <code>ma</code>, ... and so on.<br />
<br />
There are also instances of <code>MonadFix</code> for lists (which works analogously to the instance for <code>Maybe</code>), for <code>ST</code>, and for <code>IO</code>. The [http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/System-IO.html#fixIO instance for <code>IO</code>] is particularly amusing: it creates a new <code>IORef</code> (with a dummy value), immediately reads its contents using <code>unsafeInterleaveIO</code> (which delays the actual reading lazily until the value is needed), uses the contents of the <code>IORef</code> to compute a new value, which it then writes back into the <code>IORef</code>. It almost seems, spookily, that <code>mfix</code> is sending a value back in time to itself through the <code>IORef</code> -- though of course what is really going on is that the reading is delayed just long enough (via <code>unsafeInterleaveIO</code>) to get the process bootstrapped.<br />
<br />
{{Exercises|<br />
* Implement a <code>MonadFix</code> instance for <code>[]</code>.<br />
}}<br />
<br />
==Further reading==<br />
<br />
For more information (such as the precise desugaring rules for <code>rec</code> blocks), see Levent Erkök and John Launchbury's 2002 Haskell workshop paper, [http://sites.google.com/site/leventerkok/recdo.pdf?attredirects=0 A Recursive do for Haskell], or for full details, Levent Erkök’s thesis, [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.15.1543&rep=rep1&type=pdf Value Recursion in Monadic Computations]. (Note, while reading, that <code>do rec</code> used to be called <code>mdo</code>, and <code>MonadFix</code> used to be called <code>MonadRec</code>.)<br />
<br />
=Semigroup=<br />
<br />
A semigroup is a set <math>S\ </math> together with a binary operation <math>\oplus\ </math> which<br />
combines elements from <math>S\ </math>. The <math>\oplus\ </math> operator is required to be associative<br />
(that is, <math>(a \oplus b) \oplus c = a \oplus (b \oplus c)\ </math>, for any<br />
<math>a,b,c\ </math> which are elements of <math>S\ </math>).<br />
<br />
For example, the natural numbers under addition form a semigroup: the sum of any two natural numbers is a natural number, and <math>(a+b)+c = a+(b+c)\ </math> for any natural numbers <math>a\ </math>, <math>b\ </math>, and <math>c\,\ </math>. The integers under multiplication also form a semigroup, as do the integers (or rationals, or reals) under <math>\max\ </math> or <math>\min\ </math>, Boolean values under conjunction and disjunction, lists under concatenation, functions from a set to itself under composition ... Semigroups show up all over the place, once you know to look for them.<br />
<br />
Under construction, more coming soon...<br />
<br />
=Monoid=<br />
<br />
Many semigroups have a special element <math>e</math> for which the binary operation <math>\oplus</math> is the identity, that is, <math>e \oplus x = x \oplus e = x</math> for every element <math>x</math>. Such a semigroup-with-identity-element is called a ''monoid''.<br />
<br />
==Definition==<br />
<br />
The definition of the <code>Monoid</code> type class (defined in<br />
<code>Data.Monoid</code>; [http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Monoid.html haddock]) is:<br />
<br />
<haskell><br />
class Monoid a where<br />
mempty :: a<br />
mappend :: a -> a -> a<br />
<br />
mconcat :: [a] -> a<br />
mconcat = foldr mappend mempty<br />
</haskell><br />
<br />
The <code>mempty</code> value specifies the identity element of the monoid, and <code>mappend</code><br />
is the binary operation. The default definition for <code>mconcat</code><br />
“reduces” a list of elements by combining them all with <code>mappend</code>,<br />
using a right fold. It is only in the <code>Monoid</code> class so that specific<br />
instances have the option of providing an alternative, more efficient<br />
implementation; usually, you can safely ignore <code>mconcat</code> when creating<br />
a <code>Monoid</code> instance, since its default definition will work just fine.<br />
<br />
The <code>Monoid</code> methods are rather unfortunately named; they are inspired<br />
by the list instance of <code>Monoid</code>, where indeed <code>mempty = []</code> and <code>mappend = (++)</code>, but this is misleading since many<br />
monoids have little to do with appending (see these [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/50590 Comments from OCaml Hacker Brian Hurt] on the haskell-cafe mailing list).<br />
<br />
==Laws==<br />
<br />
Of course, every <code>Monoid</code> instance should actually be a monoid in the<br />
mathematical sense, which implies these laws:<br />
<br />
<haskell><br />
mempty `mappend` x = x<br />
x `mappend` mempty = x<br />
(x `mappend` y) `mappend` z = x `mappend` (y `mappend` z)<br />
</haskell><br />
<br />
==Instances==<br />
<br />
There are quite a few interesting <code>Monoid</code> instances defined in <code>Data.Monoid</code>.<br />
<br />
<ul><br />
<li><code>[a]</code> is a <code>Monoid</code>, with <code>mempty = []</code> and <code>mappend = (++)</code>. It is not hard to check that <code>(x ++ y) ++ z = x ++ (y ++ z)</code> for any lists <code>x</code>, <code>y</code>, and <code>z</code>, and that the empty list is the identity: <code>[] ++ x = x ++ [] = x</code>.</li><br />
<br />
<li>As noted previously, we can make a monoid out of any numeric type under either addition or multiplication. However, since we can’t have two instances for the same type, <code>Data.Monoid</code> provides two <code>newtype</code> wrappers, <code>Sum</code> and <code>Product</code>, with appropriate <code>Monoid</code> instances.<br />
<br />
<haskell><br />
> getSum (mconcat . map Sum $ [1..5])<br />
15<br />
> getProduct (mconcat . map Product $ [1..5])<br />
120<br />
</haskell><br />
<br />
This example code is silly, of course; we could just write<br />
<code>sum [1..5]</code> and <code>product [1..5]</code>. Nevertheless, these instances are useful in more generalized settings, as we will see in the [[Foldable|section <code>Foldable</code>]].</li><br />
<br />
<li><code>Any</code> and <code>All</code> are <code>newtype</code> wrappers providing <code>Monoid</code> instances for <code>Bool</code> (under disjunction and conjunction, respectively).</li><br />
<br />
<li> There are three instances for <code>Maybe</code>: a basic instance which lifts a <code>Monoid</code> instance for <code>a</code> to an instance for <code>Maybe a</code>, and two <code>newtype</code> wrappers <code>First</code> and <code>Last</code> for which <code>mappend</code> selects the first (respectively last) non-<code>Nothing</code> item.</li><br />
<br />
<li><code>Endo a</code> is a newtype wrapper for functions <code>a -> a</code>, which form a monoid under composition.</li><br />
<br />
<li>There are several ways to “lift” <code>Monoid</code> instances to instances with additional structure. We have already seen that an instance for <code>a</code> can be lifted to an instance for <code>Maybe a</code>. There are also tuple instances: if <code>a</code> and <code>b</code> are instances of <code>Monoid</code>, then so is <code>(a,b)</code>, using the monoid operations for <code>a</code> and <code>b</code> in the obvious pairwise manner. Finally, if <code>a</code> is a <code>Monoid</code>, then so is the function type <code>e -> a</code> for any <code>e</code>; in particular, <code>g `mappend` h</code> is the function which applies both <code>g</code> and <code>h</code> to its argument and then combines the results using the underlying <code>Monoid</code> instance for <code>a</code>. This can be quite useful and elegant (see [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/52416 example]).</li><br />
<br />
<li>The type <code>Ordering = LT || EQ || GT</code> is a <code>Monoid</code>, defined in such a way that <code>mconcat (zipWith compare xs ys)</code> computes the lexicographic ordering of <code>xs</code> and <code>ys</code> (if <code>xs</code> and <code>ys</code> have the same length). In particular, <code>mempty = EQ</code>, and <code>mappend</code> evaluates to its leftmost non-<code>EQ</code> argument (or <code>EQ</code> if both arguments are <code>EQ</code>). This can be used together with the function instance of <code>Monoid</code> to do some clever things ([http://www.reddit.com/r/programming/comments/7cf4r/monoids_in_my_programming_language/c06adnx example]).</li><br />
<br />
<li>There are also <code>Monoid</code> instances for several standard data structures in the containers library ([http://hackage.haskell.org/packages/archive/containers/0.2.0.0/doc/html/index.html haddock]), including <code>Map</code>, <code>Set</code>, and <code>Sequence</code>.</li><br />
</ul><br />
<br />
<code>Monoid</code> is also used to enable several other type class instances.<br />
As noted previously, we can use <code>Monoid</code> to make <code>((,) e)</code> an instance of <code>Applicative</code>:<br />
<br />
<haskell><br />
instance Monoid e => Applicative ((,) e) where<br />
pure x = (mempty, x)<br />
(u, f) <*> (v, x) = (u `mappend` v, f x)<br />
</haskell><br />
<br />
<code>Monoid</code> can be similarly used to make <code>((,) e)</code> an instance of <code>Monad</code> as well; this is known as the ''writer monad''. As we’ve already seen, <code>Writer</code> and <code>WriterT</code> are a newtype wrapper and transformer for this monad, respectively.<br />
<br />
<code>Monoid</code> also plays a key role in the <code>Foldable</code> type class (see section [[#Foldable|Foldable]]).<br />
<br />
==Other monoidal classes: Alternative, MonadPlus, ArrowPlus==<br />
<br />
The <code>Alternative</code> type class ([http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html#g:2 haddock])<br />
is for <code>Applicative</code> functors which also have<br />
a monoid structure:<br />
<br />
<haskell><br />
class Applicative f => Alternative f where<br />
empty :: f a<br />
(<|>) :: f a -> f a -> f a<br />
</haskell><br />
<br />
Of course, instances of <code>Alternative</code> should satisfy the monoid laws.<br />
<br />
Likewise, <code>MonadPlus</code> ([http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html#t:MonadPlus haddock])<br />
is for <code>Monad</code>s with a monoid structure:<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 />
<br />
The <code>MonadPlus</code> documentation states that it is intended to model<br />
monads which also support “choice and failure”; in addition to the<br />
monoid laws, instances of <code>MonadPlus</code> are expected to satisfy<br />
<br />
<haskell><br />
mzero >>= f = mzero<br />
v >> mzero = mzero<br />
</haskell><br />
<br />
which explains the sense in which <code>mzero</code> denotes failure. Since<br />
<code>mzero</code> should be the identity for <code>mplus</code>, the computation <code>m1 `mplus` m2</code> succeeds (evaluates to something other than <code>mzero</code>) if<br />
either <code>m1</code> or <code>m2</code> does; so <code>mplus</code> represents choice. The <code>guard</code><br />
function can also be used with instances of <code>MonadPlus</code>; it requires a<br />
condition to be satisfied and fails (using <code>mzero</code>) if it is not. A<br />
simple example of a <code>MonadPlus</code> instance is <code>[]</code>, which is exactly the<br />
same as the <code>Monoid</code> instance for <code>[]</code>: the empty list represents<br />
failure, and list concatenation represents choice. In general,<br />
however, a <code>MonadPlus</code> instance for a type need not be the same as its<br />
<code>Monoid</code> instance; <code>Maybe</code> is an example of such a type. A great<br />
introduction to the <code>MonadPlus</code> type class, with interesting examples<br />
of its use, is Doug Auclair’s ''MonadPlus: What a Super Monad!'' in [http://www.haskell.org/wikiupload/6/6a/TMR-Issue11.pdf the Monad.Reader issue 11].<br />
<br />
There used to be a type class called <code>MonadZero</code> containing only<br />
<code>mzero</code>, representing monads with failure. The <code>do</code>-notation requires<br />
some notion of failure to deal with failing pattern matches.<br />
Unfortunately, <code>MonadZero</code> was scrapped in favor of adding the <code>fail</code><br />
method to the <code>Monad</code> class. If we are lucky, someday <code>MonadZero</code> will<br />
be restored, and <code>fail</code> will be banished to the bit bucket where it<br />
belongs (see [[MonadPlus reform proposal]]). The idea is that any<br />
<code>do</code>-block which uses pattern matching (and hence may fail) would require<br />
a <code>MonadZero</code> constraint; otherwise, only a <code>Monad</code> constraint would be<br />
required.<br />
<br />
Finally, <code>ArrowZero</code> and <code>ArrowPlus</code> ([http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#t:ArrowZero haddock])<br />
represent <code>Arrow</code>s ([[#Arrow|see below]]) with a<br />
monoid structure:<br />
<br />
<haskell><br />
class Arrow (~>) => ArrowZero (~>) where<br />
zeroArrow :: b ~> c<br />
<br />
class ArrowZero (~>) => ArrowPlus (~>) where<br />
(<+>) :: (b ~> c) -> (b ~> c) -> (b ~> c)<br />
</haskell><br />
<br />
==Further reading==<br />
<br />
Monoids have gotten a fair bit of attention recently, ultimately due<br />
to<br />
[http://enfranchisedmind.com/blog/posts/random-thoughts-on-haskell/ a blog post by Brian Hurt], in which he<br />
complained about the fact that the names of many Haskell type classes<br />
(<code>Monoid</code> in particular) are taken from abstract mathematics. This<br />
resulted in [http://thread.gmane.org/gmane.comp.lang.haskell.cafe/50590 a long haskell-cafe thread]<br />
arguing the point and discussing monoids in general.<br />
<br />
{{note|May its name live forever.}}<br />
<br />
However, this was quickly followed by several blog posts about<br />
<code>Monoid</code> {{noteref}}. First, Dan Piponi<br />
wrote a great introductory post, [http://blog.sigfpe.com/2009/01/haskell-monoids-and-their-uses.html Haskell Monoids and their Uses]. This was quickly followed by<br />
Heinrich Apfelmus’s [http://apfelmus.nfshost.com/monoid-fingertree.html Monoids and Finger Trees], an accessible exposition of<br />
Hinze and Paterson’s [http://www.soi.city.ac.uk/%7Eross/papers/FingerTree.html classic paper on 2-3 finger trees], which makes very clever<br />
use of <code>Monoid</code> to implement an elegant and generic data structure.<br />
Dan Piponi then wrote two fascinating articles about using <code>Monoids</code><br />
(and finger trees): [http://blog.sigfpe.com/2009/01/fast-incremental-regular-expression.html Fast Incremental Regular Expressions] and [http://blog.sigfpe.com/2009/01/beyond-regular-expressions-more.html Beyond Regular Expressions]<br />
<br />
In a similar vein, David Place’s article on improving <code>Data.Map</code> in<br />
order to compute incremental folds (see [http://www.haskell.org/sitewiki/images/6/6a/TMR-Issue11.pdf the Monad Reader issue 11])<br />
is also a<br />
good example of using <code>Monoid</code> to generalize a data structure.<br />
<br />
Some other interesting examples of <code>Monoid</code> use include [http://www.reddit.com/r/programming/comments/7cf4r/monoids_in_my_programming_language/c06adnx building elegant list sorting combinators],<br />
[http://byorgey.wordpress.com/2008/04/17/collecting-unstructured-information-with-the-monoid-of-partial-knowledge/ collecting unstructured information],<br />
and a brilliant series of posts by Chung-Chieh Shan and Dylan Thurston<br />
using <code>Monoid</code>s to [http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers1/ elegantly solve a difficult combinatorial puzzle] (followed by<br />
[http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers2/ part 2],<br />
[http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers3/ part 3],<br />
[http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers4/ part 4]).<br />
<br />
As unlikely as it sounds, monads can actually be viewed as a sort of<br />
monoid, with <code>join</code> playing the role of the binary operation and<br />
<code>return</code> the role of the identity; see [http://blog.sigfpe.com/2008/11/from-monoids-to-monads.html Dan Piponi’s blog post].<br />
<br />
=Foldable=<br />
<br />
The <code>Foldable</code> class, defined in the <code>Data.Foldable</code><br />
module ([http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Foldable.html haddock]), abstracts over containers which can be<br />
“folded” into a summary value. This allows such folding operations<br />
to be written in a container-agnostic way.<br />
<br />
==Definition==<br />
<br />
The definition of the <code>Foldable</code> type class is:<br />
<br />
<haskell><br />
class Foldable t where<br />
fold :: Monoid m => t m -> m<br />
foldMap :: Monoid m => (a -> m) -> t a -> m<br />
<br />
foldr :: (a -> b -> b) -> b -> t a -> b<br />
foldl :: (a -> b -> a) -> a -> t b -> a<br />
foldr1 :: (a -> a -> a) -> t a -> a<br />
foldl1 :: (a -> a -> a) -> t a -> a<br />
</haskell><br />
<br />
This may look complicated, but in fact, to make a <code>Foldable</code> instance<br />
you only need to implement one method: your choice of <code>foldMap</code> or<br />
<code>foldr</code>. All the other methods have default implementations in terms<br />
of these, and are presumably included in the class in case more<br />
efficient implementations can be provided.<br />
<br />
==Instances and examples==<br />
<br />
The type of <code>foldMap</code> should make it clear what it is supposed to do:<br />
given a way to convert the data in a container into a <code>Monoid</code> (a<br />
function <code>a -> m</code>) and a container of <code>a</code>’s (<code>t a</code>), <code>foldMap</code><br />
provides a way to iterate over the entire contents of the container,<br />
converting all the <code>a</code>’s to <code>m</code>’s and combining all the <code>m</code>’s with<br />
<code>mappend</code>. The following code shows two examples: a simple<br />
implementation of <code>foldMap</code> for lists, and a binary tree example<br />
provided by the <code>Foldable</code> documentation.<br />
<br />
<haskell><br />
instance Foldable [] where<br />
foldMap g = mconcat . map g<br />
<br />
data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)<br />
<br />
instance Foldable Tree where<br />
foldMap f Empty = mempty<br />
foldMap f (Leaf x) = f x<br />
foldMap f (Node l k r) = foldMap f l ++ f k ++ foldMap f r<br />
where (++) = mappend<br />
</haskell><br />
<br />
The <code>foldr</code> function has a type similar to the <code>foldr</code> found in the <code>Prelude</code>, but<br />
more general, since the <code>foldr</code> in the <code>Prelude</code> works only on lists.<br />
<br />
The <code>Foldable</code> module also provides instances for <code>Maybe</code> and <code>Array</code>;<br />
additionally, many of the data structures found in the standard [http://hackage.haskell.org/package/containers containers library] (for example, <code>Map</code>, <code>Set</code>, <code>Tree</code>,<br />
and <code>Sequence</code>) provide their own <code>Foldable</code> instances.<br />
<br />
==Derived folds==<br />
<br />
Given an instance of <code>Foldable</code>, we can write generic,<br />
container-agnostic functions such as:<br />
<br />
<haskell><br />
-- Compute the size of any container.<br />
containerSize :: Foldable f => f a -> Int<br />
containerSize = getSum . foldMap (const (Sum 1))<br />
<br />
-- Compute a list of elements of a container satisfying a predicate.<br />
filterF :: Foldable f => (a -> Bool) -> f a -> [a]<br />
filterF p = foldMap (\a -> if p a then [a] else [])<br />
<br />
-- Get a list of all the Strings in a container which include the<br />
-- letter a.<br />
aStrings :: Foldable f => f String -> [String]<br />
aStrings = filterF (elem 'a')<br />
</haskell><br />
<br />
The <code>Foldable</code> module also provides a large number of predefined<br />
folds, many of which are generalized versions of <code>Prelude</code> functions of the<br />
same name that only work on lists: <code>concat</code>, <code>concatMap</code>, <code>and</code>,<br />
<code>or</code>, <code>any</code>, <code>all</code>, <code>sum</code>, <code>product</code>, <code>maximum</code>(<code>By</code>),<br />
<code>minimum</code>(<code>By</code>), <code>elem</code>, <code>notElem</code>, and <code>find</code>. The reader may enjoy<br />
coming up with elegant implementations of these functions using <code>fold</code><br />
or <code>foldMap</code> and appropriate <code>Monoid</code> instances.<br />
<br />
There are also generic functions that work with <code>Applicative</code> or<br />
<code>Monad</code> instances to generate some sort of computation from each<br />
element in a container, and then perform all the side effects from<br />
those computations, discarding the results: <code>traverse_</code>, <code>sequenceA_</code>,<br />
and others. The results must be discarded because the <code>Foldable</code><br />
class is too weak to specify what to do with them: we cannot, in<br />
general, make an arbitrary <code>Applicative</code> or <code>Monad</code> instance into a<br />
<code>Monoid</code>. If we do have an <code>Applicative</code> or <code>Monad</code> with a monoid<br />
structure—that is, an <code>Alternative</code> or a <code>MonadPlus</code>—then we can<br />
use the <code>asum</code> or <code>msum</code> functions, which can combine the results as<br />
well. Consult the [http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Foldable.html <code>Foldable</code> documentation] for<br />
more details on any of these functions.<br />
<br />
Note that the <code>Foldable</code> operations always forget the structure of<br />
the container being folded. If we start with a container of type <code>t a</code> for some <code>Foldable t</code>, then <code>t</code> will never appear in the output<br />
type of any operations defined in the <code>Foldable</code> module. Many times<br />
this is exactly what we want, but sometimes we would like to be able<br />
to generically traverse a container while preserving its<br />
structure—and this is exactly what the <code>Traversable</code> class provides,<br />
which will be discussed in the next section.<br />
<br />
==Further reading==<br />
<br />
The <code>Foldable</code> class had its genesis in [http://www.soi.city.ac.uk/~ross/papers/Applicative.html McBride and Paterson’s paper]<br />
introducing <code>Applicative</code>, although it has<br />
been fleshed out quite a bit from the form in the paper.<br />
<br />
An interesting use of <code>Foldable</code> (as well as <code>Traversable</code>) can be<br />
found in Janis Voigtländer’s paper [http://doi.acm.org/10.1145/1480881.1480904 Bidirectionalization for free!].<br />
<br />
=Traversable=<br />
<br />
==Definition==<br />
<br />
The <code>Traversable</code> type class, defined in the <code>Data.Traversable</code><br />
module ([http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Traversable.html haddock]), is:<br />
<br />
<haskell><br />
class (Functor t, Foldable t) => Traversable t where<br />
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)<br />
sequenceA :: Applicative f => t (f a) -> f (t a)<br />
mapM :: Monad m => (a -> m b) -> t a -> m (t b)<br />
sequence :: Monad m => t (m a) -> m (t a)<br />
</haskell><br />
<br />
As you can see, every <code>Traversable</code> is also a foldable functor. Like<br />
<code>Foldable</code>, there is a lot in this type class, but making instances is<br />
actually rather easy: one need only implement <code>traverse</code> or<br />
<code>sequenceA</code>; the other methods all have default implementations in<br />
terms of these functions. A good exercise is to figure out what the default<br />
implementations should be: given either <code>traverse</code> or <code>sequenceA</code>, how<br />
would you define the other three methods? (Hint for <code>mapM</code>:<br />
<code>Control.Applicative</code> exports the <code>WrapMonad</code> newtype, which makes any<br />
<code>Monad</code> into an <code>Applicative</code>. The <code>sequence</code> function can be implemented in terms<br />
of <code>mapM</code>.)<br />
<br />
==Intuition==<br />
<br />
The key method of the <code>Traversable</code> class, and the source of its<br />
unique power, is <code>sequenceA</code>. Consider its type:<br />
<haskell><br />
sequenceA :: Applicative f => t (f a) -> f (t a)<br />
</haskell><br />
This answers the fundamental question: when can we commute two<br />
functors? For example, can we turn a tree of lists into a list of<br />
trees? (Answer: yes, in two ways. Figuring out what they are, and<br />
why, is left as an exercise. A much more challenging question is<br />
whether a list of trees can be turned into a tree of lists.)<br />
<br />
The ability to compose two monads depends crucially on this ability to<br />
commute functors. Intuitively, if we want to build a composed monad<br />
<code>M a = m (n a)</code> out of monads <code>m</code> and <code>n</code>, then to be able to<br />
implement <code>join :: M (M a) -> M a</code>, that is,<br />
<code>join :: m (n (m (n a))) -> m (n a)</code>, we have to be able to commute<br />
the <code>n</code> past the <code>m</code> to get <code>m (m (n (n a)))</code>, and then we can use the<br />
<code>join</code>s for <code>m</code> and <code>n</code> to produce something of type <code>m (n a)</code>. See<br />
[http://web.cecs.pdx.edu/~mpj/pubs/springschool.html Mark Jones’s paper] for more details.<br />
<br />
==Instances and examples==<br />
<br />
What’s an example of a <code>Traversable</code> instance?<br />
The following code shows an example instance for the same<br />
<code>Tree</code> type used as an example in the previous <code>Foldable</code> section. It<br />
is instructive to compare this instance with a <code>Functor</code> instance for<br />
<code>Tree</code>, which is also shown.<br />
<br />
<haskell><br />
data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)<br />
<br />
instance Traversable Tree where<br />
traverse g Empty = pure Empty<br />
traverse g (Leaf x) = Leaf <$> g x<br />
traverse g (Node l x r) = Node <$> traverse g l<br />
<*> g x<br />
<*> traverse g r<br />
<br />
instance Functor Tree where<br />
fmap g Empty = Empty<br />
fmap g (Leaf x) = Leaf $ g x<br />
fmap g (Node l x r) = Node (fmap g l)<br />
(g x)<br />
(fmap g r)<br />
</haskell><br />
<br />
It should be clear that the <code>Traversable</code> and <code>Functor</code> instances for<br />
<code>Tree</code> are almost identical; the only difference is that the <code>Functor</code><br />
instance involves normal function application, whereas the<br />
applications in the <code>Traversable</code> instance take place within an<br />
<code>Applicative</code> context, using <code>(<$>)</code> and <code>(<*>)</code>. In fact, this will<br />
be<br />
true for any type.<br />
<br />
Any <code>Traversable</code> functor is also <code>Foldable</code>, and a <code>Functor</code>. We can see<br />
this not only from the class declaration, but by the fact that we can<br />
implement the methods of both classes given only the <code>Traversable</code><br />
methods. A good exercise is to implement <code>fmap</code> and <code>foldMap</code> using<br />
only the <code>Traversable</code> methods; the implementations are surprisingly<br />
elegant. The <code>Traversable</code> module provides these<br />
implementations as <code>fmapDefault</code> and <code>foldMapDefault</code>.<br />
<br />
The standard libraries provide a number of <code>Traversable</code> instances,<br />
including instances for <code>[]</code>, <code>Maybe</code>, <code>Map</code>, <code>Tree</code>, and <code>Sequence</code>.<br />
Notably, <code>Set</code> is not <code>Traversable</code>, although it is <code>Foldable</code>.<br />
<br />
==Further reading==<br />
<br />
The <code>Traversable</code> class also had its genesis in [http://www.soi.city.ac.uk/~ross/papers/Applicative.html McBride and Paterson’s <code>Applicative</code> paper],<br />
and is described in more detail in Gibbons and Oliveira, [http://www.comlab.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf The Essence of the Iterator Pattern],<br />
which also contains a wealth of references to related work.<br />
<br />
=Category=<br />
<br />
<code>Category</code> is another fairly new addition to the Haskell standard<br />
libraries; you may or may not have it installed depending on the<br />
version of your <code>base</code> package. It generalizes the notion of<br />
function composition to general “morphisms”.<br />
<br />
The definition of the <code>Category</code> type class (from<br />
<code>Control.Category</code>—[http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Category.html haddock]) is shown below. For ease of reading, note that I have used an<br />
infix type constructor <code>(~>)</code>, much like the infix function type<br />
constructor <code>(->)</code>. This syntax is not part of Haskell 98.<br />
The second definition shown is the one used in the standard libraries.<br />
For the remainder of this document, I will use the infix type<br />
constructor <code>(~>)</code> for <code>Category</code> as well as <code>Arrow</code>.<br />
<br />
<haskell><br />
class Category (~>) where<br />
id :: a ~> a<br />
(.) :: (b ~> c) -> (a ~> b) -> (a ~> c)<br />
<br />
-- The same thing, with a normal (prefix) type constructor<br />
class Category cat where<br />
id :: cat a a<br />
(.) :: cat b c -> cat a b -> cat a c<br />
</haskell><br />
<br />
Note that an instance of <code>Category</code> should be a type constructor which<br />
takes two type arguments, that is, something of kind <code>* -> * -> *</code>. It<br />
is instructive to imagine the type constructor variable <code>cat</code> replaced<br />
by the function constructor <code>(->)</code>: indeed, in this case we recover<br />
precisely the familiar identity function <code>id</code> and function composition<br />
operator <code>(.)</code> defined in the standard <code>Prelude</code>.<br />
<br />
Of course, the <code>Category</code> module provides exactly such an instance of<br />
<code>Category</code> for <code>(->)</code>. But it also provides one other instance, shown<br />
below, which should be familiar from the<br />
previous discussion of the <code>Monad</code> laws. <code>Kleisli m a b</code>, as defined<br />
in the <code>Control.Arrow</code> module, is just a <code>newtype</code> wrapper around <code>a -> m b</code>.<br />
<br />
<haskell><br />
newtype Kleisli m a b = Kleisli { runKleisli :: a -> m b }<br />
<br />
instance Monad m => Category (Kleisli m) where<br />
id = Kleisli return<br />
Kleisli g . Kleisli h = Kleisli (h >=> g)<br />
</haskell><br />
<br />
The only law that <code>Category</code> instances should satisfy is that <code>id</code> and<br />
<code>(.)</code> should form a monoid—that is, <code>id</code> should be the identity of<br />
<code>(.)</code>, and <code>(.)</code> should be associative.<br />
<br />
Finally, the <code>Category</code> module exports two additional operators:<br />
<code>(<<<)</code>, which is just a synonym for <code>(.)</code>, and <code>(>>>)</code>, which is<br />
<code>(.)</code> with its arguments reversed. (In previous versions of the<br />
libraries, these operators were defined as part of the <code>Arrow</code> class.)<br />
<br />
==Further reading==<br />
<br />
The name <code>Category</code> is a bit misleading, since the <code>Category</code> class<br />
cannot represent arbitrary categories, but only categories whose<br />
objects are objects of <code>Hask</code>, the category of Haskell types. For a<br />
more general treatment of categories within Haskell, see the<br />
[http://hackage.haskell.org/package/category-extras category-extras package]. For more about<br />
category theory in general, see the excellent [http://en.wikibooks.org/wiki/Haskell/Category_theory Haskell wikibook page],<br />
[http://books.google.com/books/about/Category_theory.html?id=-MCJ6x2lC7oC Steve Awodey’s new book],<br />
Benjamin Pierce’s<br />
[http://books.google.com/books/about/Basic_category_theory_for_computer_scien.html?id=ezdeaHfpYPwC Basic category theory for computer scientists], or<br />
[http://folli.loria.fr/cds/1999/esslli99/courses/barr-wells.html Barr and Wells’s category theory lecture notes]. [http://dekudekuplex.wordpress.com/2009/01/19/motivating-learning-category-theory-for-non-mathematicians/ Benjamin Russell’s blog post]<br />
is another good source of motivation and<br />
category theory links. You certainly don’t need to know any category<br />
theory to be a successful and productive Haskell programmer, but it<br />
does lend itself to much deeper appreciation of Haskell’s underlying<br />
theory.<br />
<br />
=Arrow=<br />
<br />
The <code>Arrow</code> class represents another abstraction of computation, in a<br />
similar vein to <code>Monad</code> and <code>Applicative</code>. However, unlike <code>Monad</code><br />
and <code>Applicative</code>, whose types only reflect their output, the type of<br />
an <code>Arrow</code> computation reflects both its input and output. Arrows<br />
generalize functions: if <code>(~>)</code> is an instance of <code>Arrow</code>, a value of<br />
type <code>b ~> c</code> can be thought of as a computation which takes values of<br />
type <code>b</code> as input, and produces values of type <code>c</code> as output. In the<br />
<code>(->)</code> instance of <code>Arrow</code> this is just a pure function; in general, however,<br />
an arrow may represent some sort of “effectful” computation.<br />
<br />
==Definition==<br />
<br />
The definition of the <code>Arrow</code> type class, from<br />
<code>Control.Arrow</code> ([http://haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html haddock]), is:<br />
<br />
<haskell><br />
class Category (~>) => Arrow (~>) where<br />
arr :: (b -> c) -> (b ~> c)<br />
first :: (b ~> c) -> ((b, d) ~> (c, d))<br />
second :: (b ~> c) -> ((d, b) ~> (d, c))<br />
(***) :: (b ~> c) -> (b' ~> c') -> ((b, b') ~> (c, c'))<br />
(&&&) :: (b ~> c) -> (b ~> c') -> (b ~> (c, c'))<br />
</haskell><br />
<br />
{{note|In versions of the <code>base</code><br />
package prior to version 4, there is no <code>Category</code> class, and the<br />
<code>Arrow</code> class includes the arrow composition operator <code>(>>>)</code>. It<br />
also includes <code>pure</code> as a synonym for <code>arr</code>, but this was removed<br />
since it conflicts with the <code>pure</code> from <code>Applicative</code>.}}<br />
<br />
The first thing to note is the <code>Category</code> class constraint, which<br />
means that we get identity arrows and arrow composition for free:<br />
given two arrows <code>g :: b ~> c</code> and <code>h :: c ~> d</code>, we can form their<br />
composition <code>g >>> h :: b ~> d</code> {{noteref}}.<br />
<br />
As should be a familiar pattern by now, the only methods which must be<br />
defined when writing a new instance of <code>Arrow</code> are <code>arr</code> and <code>first</code>;<br />
the other methods have default definitions in terms of these, but are<br />
included in the <code>Arrow</code> class so that they can be overridden with more<br />
efficient implementations if desired.<br />
<br />
==Intuition==<br />
<br />
Let’s look at each of the arrow methods in turn. [http://www.haskell.org/arrows/ Ross Paterson’s web page on arrows] has nice diagrams which can help<br />
build intuition.<br />
<br />
* The <code>arr</code> function takes any function <code>b -> c</code> and turns it into a generalized arrow <code>b ~> c</code>. The <code>arr</code> method justifies the claim that arrows generalize functions, since it says that we can treat any function as an arrow. It is intended that the arrow <code>arr g</code> is “pure” in the sense that it only computes <code>g</code> and has no “effects” (whatever that might mean for any particular arrow type).<br />
<br />
* The <code>first</code> method turns any arrow from <code>b</code> to <code>c</code> into an arrow from <code>(b,d)</code> to <code>(c,d)</code>. The idea is that <code>first g</code> uses <code>g</code> to process the first element of a tuple, and lets the second element pass through unchanged. For the function instance of <code>Arrow</code>, of course, <code>first g (x,y) = (g x, y)</code>.<br />
<br />
* The <code>second</code> function is similar to <code>first</code>, but with the elements of the tuples swapped. Indeed, it can be defined in terms of <code>first</code> using an auxiliary function <code>swap</code>, defined by <code>swap (x,y) = (y,x)</code>.<br />
<br />
* The <code>(***)</code> operator is “parallel composition” of arrows: it takes two arrows and makes them into one arrow on tuples, which has the behavior of the first arrow on the first element of a tuple, and the behavior of the second arrow on the second element. The mnemonic is that <code>g *** h</code> is the ''product'' (hence <code>*</code>) of <code>g</code> and <code>h</code>. For the function instance of <code>Arrow</code>, we define <code>(g *** h) (x,y) = (g x, h y)</code>. The default implementation of <code>(***)</code> is in terms of <code>first</code>, <code>second</code>, and sequential arrow composition <code>(>>>)</code>. The reader may also wish to think about how to implement <code>first</code> and <code>second</code> in terms of <code>(***)</code>.<br />
<br />
* The <code>(&&&)</code> operator is “fanout composition” of arrows: it takes two arrows <code>g</code> and <code>h</code> and makes them into a new arrow <code>g &&& h</code> which supplies its input as the input to both <code>g</code> and <code>h</code>, returning their results as a tuple. The mnemonic is that <code>g &&& h</code> performs both <code>g</code> ''and'' <code>h</code> (hence <code>&</code>) on its input. For functions, we define <code>(g &&& h) x = (g x, h x)</code>.<br />
<br />
==Instances==<br />
<br />
The <code>Arrow</code> library itself only provides two <code>Arrow</code> instances, both<br />
of which we have already seen: <code>(->)</code>, the normal function<br />
constructor, and <code>Kleisli m</code>, which makes functions of<br />
type <code>a -> m b</code> into <code>Arrow</code>s for any <code>Monad m</code>. These instances are:<br />
<br />
<haskell><br />
instance Arrow (->) where<br />
arr g = g<br />
first g (x,y) = (g x, y)<br />
<br />
newtype Kleisli m a b = Kleisli { runKleisli :: a -> m b }<br />
<br />
instance Monad m => Arrow (Kleisli m) where<br />
arr f = Kleisli (return . f)<br />
first (Kleisli f) = Kleisli (\ ~(b,d) -> do c <- f b<br />
return (c,d) )<br />
</haskell><br />
<br />
==Laws==<br />
<br />
{{note|See [http://dx.doi.org/10.1016/S0167-6423(99)00023-4 John Hughes: Generalising monads to arrows]; [http://homepages.inf.ed.ac.uk/wadler/papers/arrows/arrows.pdf Sam Lindley, Philip Wadler, Jeremy Yallop: The arrow calculus]; [http://www.soi.city.ac.uk/~ross/papers/fop.html Ross Paterson: Programming with Arrows].}}<br />
<br />
There are quite a few laws that instances of <code>Arrow</code> should<br />
satisfy {{noteref}}:<br />
<br />
<haskell><br />
arr id = id<br />
arr (h . g) = arr g >>> arr h<br />
first (arr g) = arr (g *** id)<br />
first (g >>> h) = first g >>> first h<br />
first g >>> arr (id *** h) = arr (id *** h) >>> first g<br />
first g >>> arr fst = arr fst >>> g<br />
first (first g) >>> arr assoc = arr assoc >>> first g<br />
<br />
assoc ((x,y),z) = (x,(y,z))<br />
</haskell><br />
<br />
Note that this version of the laws is slightly different than the laws given in the<br />
first two above references, since several of the laws have now been<br />
subsumed by the <code>Category</code> laws (in particular, the requirements that<br />
<code>id</code> is the identity arrow and that <code>(>>>)</code> is associative). The laws<br />
shown here follow those in Paterson’s Programming with Arrows, which uses the<br />
<code>Category</code> class.<br />
<br />
{{note|Unless category-theory-induced insomnolence is your cup of tea.}}<br />
<br />
The reader is advised not to lose too much sleep over the <code>Arrow</code><br />
laws {{noteref}}, since it is not essential to understand them in order to<br />
program with arrows. There are also laws that <code>ArrowChoice</code>,<br />
<code>ArrowApply</code>, and <code>ArrowLoop</code> instances should satisfy; the interested<br />
reader should consult [http://www.soi.city.ac.uk/~ross/papers/fop.html Paterson: Programming with Arrows].<br />
<br />
==ArrowChoice==<br />
<br />
Computations built using the <code>Arrow</code> class, like those built using<br />
the <code>Applicative</code> class, are rather inflexible: the structure of the computation<br />
is fixed at the outset, and there is no ability to choose between<br />
alternate execution paths based on intermediate results.<br />
The <code>ArrowChoice</code> class provides exactly such an ability:<br />
<br />
<haskell><br />
class Arrow (~>) => ArrowChoice (~>) where<br />
left :: (b ~> c) -> (Either b d ~> Either c d)<br />
right :: (b ~> c) -> (Either d b ~> Either d c)<br />
(+++) :: (b ~> c) -> (b' ~> c') -> (Either b b' ~> Either c c')<br />
(|||) :: (b ~> d) -> (c ~> d) -> (Either b c ~> d)<br />
</haskell><br />
<br />
A comparison of <code>ArrowChoice</code> to <code>Arrow</code> will reveal a striking<br />
parallel between <code>left</code>, <code>right</code>, <code>(+++)</code>, <code>(|||)</code> and <code>first</code>,<br />
<code>second</code>, <code>(***)</code>, <code>(&&&)</code>, respectively. Indeed, they are dual:<br />
<code>first</code>, <code>second</code>, <code>(***)</code>, and <code>(&&&)</code> all operate on product types<br />
(tuples), and <code>left</code>, <code>right</code>, <code>(+++)</code>, and <code>(|||)</code> are the<br />
corresponding operations on sum types. In general, these operations<br />
create arrows whose inputs are tagged with <code>Left</code> or <code>Right</code>, and can<br />
choose how to act based on these tags.<br />
<br />
* If <code>g</code> is an arrow from <code>b</code> to <code>c</code>, then <code>left g</code> is an arrow from <code>Either b d</code> to <code>Either c d</code>. On inputs tagged with <code>Left</code>, the <code>left g</code> arrow has the behavior of <code>g</code>; on inputs tagged with <code>Right</code>, it behaves as the identity.<br />
<br />
* The <code>right</code> function, of course, is the mirror image of <code>left</code>. The arrow <code>right g</code> has the behavior of <code>g</code> on inputs tagged with <code>Right</code>.<br />
<br />
* The <code>(+++)</code> operator performs “multiplexing”: <code>g +++ h</code> behaves as <code>g</code> on inputs tagged with <code>Left</code>, and as <code>h</code> on inputs tagged with <code>Right</code>. The tags are preserved. The <code>(+++)</code> operator is the ''sum'' (hence <code>+</code>) of two arrows, just as <code>(***)</code> is the product.<br />
<br />
* The <code>(|||)</code> operator is “merge” or “fanin”: the arrow <code>g ||| h</code> behaves as <code>g</code> on inputs tagged with <code>Left</code>, and <code>h</code> on inputs tagged with <code>Right</code>, but the tags are discarded (hence, <code>g</code> and <code>h</code> must have the same output type). The mnemonic is that <code>g ||| h</code> performs either <code>g</code> ''or'' <code>h</code> on its input.<br />
<br />
The <code>ArrowChoice</code> class allows computations to choose among a finite number of execution paths, based on intermediate results. The possible<br />
execution paths must be known in advance, and explicitly assembled with <code>(+++)</code> or <code>(|||)</code>. However, sometimes more flexibility is<br />
needed: we would like to be able to ''compute'' an arrow from intermediate results, and use this computed arrow to continue the computation. This is the power given to us by <code>ArrowApply</code>.<br />
<br />
==ArrowApply==<br />
<br />
The <code>ArrowApply</code> type class is:<br />
<br />
<haskell><br />
class Arrow (~>) => ArrowApply (~>) where<br />
app :: (b ~> c, b) ~> c<br />
</haskell><br />
<br />
If we have computed an arrow as the output of some previous<br />
computation, then <code>app</code> allows us to apply that arrow to an input,<br />
producing its output as the output of <code>app</code>. As an exercise, the<br />
reader may wish to use <code>app</code> to implement an alternative “curried”<br />
version, <code>app2 :: b ~> ((b ~> c) ~> c)</code>.<br />
<br />
This notion of being able to ''compute'' a new computation<br />
may sound familiar:<br />
this is exactly what the monadic bind operator <code>(>>=)</code> does. It<br />
should not particularly come as a surprise that <code>ArrowApply</code> and<br />
<code>Monad</code> are exactly equivalent in expressive power. In particular,<br />
<code>Kleisli m</code> can be made an instance of <code>ArrowApply</code>, and any instance<br />
of <code>ArrowApply</code> can be made a <code>Monad</code> (via the <code>newtype</code> wrapper<br />
<code>ArrowMonad</code>). As an exercise, the reader may wish to try<br />
implementing these instances:<br />
<br />
<haskell><br />
instance Monad m => ArrowApply (Kleisli m) where<br />
app = -- exercise<br />
<br />
newtype ArrowApply a => ArrowMonad a b = ArrowMonad (a () b)<br />
<br />
instance ArrowApply a => Monad (ArrowMonad a) where<br />
return = -- exercise<br />
(ArrowMonad a) >>= k = -- exercise<br />
</haskell><br />
<br />
==ArrowLoop==<br />
<br />
The <code>ArrowLoop</code> type class is:<br />
<br />
<haskell><br />
class Arrow a => ArrowLoop a where<br />
loop :: a (b, d) (c, d) -> a b c<br />
<br />
trace :: ((b,d) -> (c,d)) -> b -> c<br />
trace f b = let (c,d) = f (b,d) in c<br />
</haskell><br />
<br />
It describes arrows that can use recursion to compute results, and is<br />
used to desugar the <code>rec</code> construct in arrow notation (described<br />
below).<br />
<br />
Taken by itself, the type of the <code>loop</code> method does not seem to tell<br />
us much. Its intention, however, is a generalization of the <code>trace</code><br />
function which is also shown. The <code>d</code> component of the first arrow’s<br />
output is fed back in as its own input. In other words, the arrow<br />
<code>loop g</code> is obtained by recursively “fixing” the second component of<br />
the input to <code>g</code>.<br />
<br />
It can be a bit difficult to grok what the <code>trace</code> function is doing.<br />
How can <code>d</code> appear on the left and right sides of the <code>let</code>? Well,<br />
this is Haskell’s laziness at work. There is not space here for a<br />
full explanation; the interested reader is encouraged to study the<br />
standard <code>fix</code> function, and to read [http://www.soi.city.ac.uk/~ross/papers/fop.html Paterson’s arrow tutorial].<br />
<br />
==Arrow notation==<br />
<br />
Programming directly with the arrow combinators can be painful,<br />
especially when writing complex computations which need to retain<br />
simultaneous reference to a number of intermediate results. With<br />
nothing but the arrow combinators, such intermediate results must be<br />
kept in nested tuples, and it is up to the programmer to remember<br />
which intermediate results are in which components, and to swap,<br />
reassociate, and generally mangle tuples as necessary. This problem<br />
is solved by the special arrow notation supported by GHC, similar to<br />
<code>do</code> notation for monads, that allows names to be assigned to<br />
intermediate results while building up arrow computations. An example<br />
arrow implemented using arrow notation, taken from<br />
Paterson, is:<br />
<br />
<haskell><br />
class ArrowLoop (~>) => ArrowCircuit (~>) where<br />
delay :: b -> (b ~> b)<br />
<br />
counter :: ArrowCircuit (~>) => Bool ~> Int<br />
counter = proc reset -> do<br />
rec output <- idA -< if reset then 0 else next<br />
next <- delay 0 -< output + 1<br />
idA -< output<br />
</haskell><br />
<br />
This arrow is intended to<br />
represent a recursively defined counter circuit with a reset line.<br />
<br />
There is not space here for a full explanation of arrow notation; the<br />
interested reader should consult [http://www.soi.city.ac.uk/~ross/papers/notation.html Paterson’s paper introducing the<br />
notation], or his later [http://www.soi.city.ac.uk/~ross/papers/fop.html<br />
tutorial which presents a simplified version].<br />
<br />
==Further reading==<br />
<br />
An excellent starting place for the student of arrows is the [http://www.haskell.org/arrows/ arrows web page], which contains an<br />
introduction and many references. Some key papers on arrows include<br />
Hughes’s original paper introducing arrows, [http://dx.doi.org/10.1016/S0167-6423(99)00023-4 Generalising monads to arrows], and [http://www.soi.city.ac.uk/~ross/papers/notation.html Paterson’s paper on arrow notation].<br />
<br />
Both Hughes and Paterson later wrote accessible tutorials intended for a broader<br />
audience: [http://www.soi.city.ac.uk/~ross/papers/fop.html Paterson: Programming with Arrows] and [http://www.cse.chalmers.se/~rjmh/afp-arrows.pdf Hughes: Programming with Arrows].<br />
<br />
Although Hughes’s goal in defining the <code>Arrow</code> class was to<br />
generalize <code>Monad</code>s, and it has been said that <code>Arrow</code> lies “between<br />
<code>Applicative</code> and <code>Monad</code>” in power, they are not directly<br />
comparable. The precise relationship remained in some confusion until<br />
[http://homepages.inf.ed.ac.uk/wadler/papers/arrows-and-idioms/arrows-and-idioms.pdf analyzed by Lindley, Wadler, and Yallop], who<br />
also invented a new calculus of arrows, based on the lambda calculus,<br />
which considerably simplifies the presentation of the arrow laws<br />
(see [http://homepages.inf.ed.ac.uk/wadler/papers/arrows/arrows.pdf The arrow calculus]).<br />
<br />
Some examples of <code>Arrow</code>s include [http://www.haskell.org/yampa/ Yampa], the<br />
[http://www.fh-wedel.de/~si/HXmlToolbox/ Haskell XML Toolkit], and the functional GUI library [[Grapefruit]].<br />
<br />
Some extensions to arrows have been explored; for example, the<br />
[http://www.cs.ru.nl/A.vanWeelden/bi-arrows/ <code>BiArrow</code>s of Alimarine et al.], for two-way instead of one-way<br />
computation.<br />
<br />
The Haskell wiki has [[Research papers/Monads and Arrows|links to many additional research papers relating to <code>Arrow</code>s]].<br />
<br />
=Comonad=<br />
<br />
The final type class we will examine is <code>Comonad</code>. The <code>Comonad</code> class<br />
is the categorical dual of <code>Monad</code>; that is, <code>Comonad</code> is like <code>Monad</code><br />
but with all the function arrows flipped. It is not actually in the<br />
standard Haskell libraries, but it has seen some interesting uses<br />
recently, so we include it here for completeness.<br />
<br />
==Definition==<br />
<br />
The <code>Comonad</code> type class, defined in the <code>Control.Comonad</code> module of<br />
the [http://hackage.haskell.org/package/category-extras category-extras library], is:<br />
<br />
<haskell><br />
class Functor f => Copointed f where<br />
extract :: f a -> a<br />
<br />
class Copointed w => Comonad w where<br />
duplicate :: w a -> w (w a)<br />
extend :: (w a -> b) -> w a -> w b<br />
</haskell><br />
<br />
As you can see, <code>extract</code> is the dual of <code>return</code>, <code>duplicate</code> is the<br />
dual of <code>join</code>, and <code>extend</code> is the dual of <code>(>>=)</code> (although its<br />
arguments are in a different order). The definition<br />
of <code>Comonad</code> is a bit redundant (after all, the <code>Monad</code> class does not<br />
need <code>join</code>), but this is so that a <code>Comonad</code> can be defined by <code>fmap</code>,<br />
<code>extract</code>, and ''either'' <code>duplicate</code> or <code>extend</code>. Each has a<br />
default implementation in terms of the other.<br />
<br />
A prototypical example of a <code>Comonad</code> instance is:<br />
<br />
<haskell><br />
-- Infinite lazy streams<br />
data Stream a = Cons a (Stream a)<br />
<br />
instance Functor Stream where<br />
fmap g (Cons x xs) = Cons (g x) (fmap g xs)<br />
<br />
instance Copointed Stream where<br />
extract (Cons x _) = x<br />
<br />
-- 'duplicate' is like the list function 'tails'<br />
-- 'extend' computes a new Stream from an old, where the element<br />
-- at position n is computed as a function of everything from<br />
-- position n onwards in the old Stream<br />
instance Comonad Stream where<br />
duplicate s@(Cons x xs) = Cons s (duplicate xs)<br />
extend g s@(Cons x xs) = Cons (g s) (extend g xs)<br />
-- = fmap g (duplicate s)<br />
</haskell><br />
<br />
==Further reading==<br />
<br />
Dan Piponi explains in a blog post what [http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html cellular automata have to do with comonads]. In another blog post, Conal Elliott has examined [http://conal.net/blog/posts/functional-interactive-behavior/ a comonadic formulation of functional reactive programming]. Sterling Clover’s blog post [http://fmapfixreturn.wordpress.com/2008/07/09/comonads-in-everyday-life/ Comonads in everyday life] explains the relationship between comonads and zippers, and how comonads can be used to design a menu system for a web site.<br />
<br />
Uustalu and Vene have a number of papers exploring ideas related to comonads and functional programming:<br />
* [http://dx.doi.org/10.1016/j.entcs.2008.05.029 Comonadic Notions of Computation]<br />
* [http://www.ioc.ee/~tarmo/papers/sfp01-book.pdf The dual of substitution is redecoration] (Also available as [http://www.cs.ut.ee/~varmo/papers/sfp01-book.ps.gz ps.gz].)<br />
* [http://dx.doi.org/10.1016/j.ic.2005.08.005 Recursive coalgebras from comonads]<br />
* [http://www.fing.edu.uy/~pardo/papers/njc01.ps.gz Recursion schemes from comonads]<br />
* [http://cs.ioc.ee/~tarmo/papers/essence.pdf The Essence of Dataflow Programming].<br />
<br />
=Acknowledgements=<br />
<br />
A special thanks to all of those who taught me about standard Haskell<br />
type classes and helped me develop good intuition for them,<br />
particularly Jules Bean (quicksilver), Derek Elkins (ddarius), Conal<br />
Elliott (conal), Cale Gibbard (Cale), David House, Dan Piponi<br />
(sigfpe), and Kevin Reid (kpreid).<br />
<br />
I also thank the many people who provided a mountain of helpful<br />
feedback and suggestions on a first draft of the Typeclassopedia: David Amos,<br />
Kevin Ballard, Reid Barton, Doug Beardsley, Joachim Breitner, Andrew<br />
Cave, David Christiansen, Gregory Collins, Mark Jason Dominus, Conal<br />
Elliott, Yitz Gale, George Giorgidze, Steven Grady, Travis Hartwell,<br />
Steve Hicks, Philip Hölzenspies, Edward Kmett, Eric Kow, Serge Le<br />
Huitouze, Felipe Lessa, Stefan Ljungstrand, Eric Macaulay, Rob MacAulay, Simon Meier,<br />
Eric Mertens, Tim Newsham, Russell O’Connor, Conrad Parker, Walt<br />
Rorie-Baety, Colin Ross, Tom Schrijvers, Aditya Siram, C. Smith,<br />
Martijn van Steenbergen, Joe Thornber, Jared Updike, Rob Vollmert,<br />
Andrew Wagner, Louis Wasserman, and Ashley Yakeley, as well as a few<br />
only known to me by their IRC nicks: b_jonas, maltem, tehgeekmeister,<br />
and ziman. I have undoubtedly omitted a few inadvertently, which in<br />
no way diminishes my gratitude.<br />
<br />
Finally, I would like to thank Wouter Swierstra for his fantastic work<br />
editing the Monad.Reader, and my wife Joyia for her patience during<br />
the process of writing the Typeclassopedia.<br />
<br />
=About the author=<br />
<br />
Brent Yorgey ([http://byorgey.wordpress.com/ blog], [http://www.cis.upenn.edu/~byorgey/ homepage]) is (as of November 2011) a fourth-year Ph.D. student in the [http://www.cis.upenn.edu/~plclub/ programming languages group] at the [http://www.upenn.edu University of Pennsylvania]. He enjoys teaching, creating EDSLs, playing Bach fugues, musing upon category theory, and cooking tasty lambda-treats for the denizens of #haskell.<br />
<br />
=Colophon=<br />
<br />
The Typeclassopedia was written by Brent Yorgey and initally published in March 2009. Painstakingly converted to wiki syntax by [[User:Geheimdienst]] in November 2011, after asking Brent’s permission.<br />
<br />
If something like this tex to wiki syntax conversion ever needs to be done again, here are some vim commands that helped:<br />
<br />
* <nowiki>%s/\\section{\([^}]*\)}/=\1=/gc</nowiki><br />
* <nowiki>%s/\\subsection{\([^}]*\)}/==\1==/gc</nowiki><br />
* <nowiki>%s/^ *\\item /\r* /gc</nowiki><br />
* <nowiki>%s/---/—/gc</nowiki><br />
* <nowiki>%s/\$\([^$]*\)\$/<math>\1\\ <\/math>/gc</nowiki> ''Appending “\ ” forces images to be rendered. Otherwise, Mediawiki would go back and forth between one font for short <nowiki><math></nowiki> tags, and another more Tex-like font for longer tags (containing more than a few characters)""<br />
* <nowiki>%s/|\([^|]*\)|/<code>\1<\/code>/gc</nowiki><br />
* <nowiki>%s/\\dots/.../gc</nowiki><br />
* <nowiki>%s/^\\label{.*$//gc</nowiki><br />
* <nowiki>%s/\\emph{\([^}]*\)}/''\1''/gc</nowiki><br />
* <nowiki>%s/\\term{\([^}]*\)}/''\1''/gc</nowiki><br />
<br />
The biggest issue was taking the academic-paper-style citations and turning them into hyperlinks with an appropriate title and an appropriate target. In most cases there was an obvious thing to do (e.g. online PDFs of the cited papers or Citeseer entries). Sometimes, however, it’s less clear and you might want to check the<br />
[[Media:Typeclassopedia.pdf|original Typeclassopedia PDF]]<br />
with the<br />
[http://code.haskell.org/~byorgey/TMR/Issue13/typeclassopedia.bib original bibliography file].<br />
<br />
To get all the citations into the main text, I first tried processing the source with Tex or Lyx. This didn’t work due to missing unfindable packages, syntax errors, and my general ineptitude with Tex.<br />
<br />
I then went for the next best solution, which seemed to be extracting all instances of “\cite{something}” from the source and ''in that order'' pulling the referenced entries from the .bib file. This way you can go through the source file and sorted-references file in parallel, copying over what you need, without searching back and forth in the .bib file. I used:<br />
<br />
* <nowiki>egrep -o "\cite\{[^\}]*\}" ~/typeclassopedia.lhs | cut -c 6- | tr "," "\n" | tr -d "}" > /tmp/citations</nowiki><br />
* <nowiki>for i in $(cat /tmp/citations); do grep -A99 "$i" ~/typeclassopedia.bib|egrep -B99 '^\}$' -m1 ; done > ~/typeclasso-refs-sorted</nowiki><br />
<br />
[[Category:Applicative Functor]]<br />
[[Category:Arrow]]<br />
[[Category:Functor]]<br />
[[Category:Monad]]<br />
[[Category:Standard classes]]<br />
[[Category:Standard libraries]]<br />
[[Category:Standard packages]]<br />
[[Category:Standard types]]</div>Daghttps://wiki.haskell.org/index.php?title=Web/Frameworks&diff=45782Web/Frameworks2012-05-25T19:11:04Z<p>Dag: /* Happstack */ update link for hamlet and shorten blaze-html link text</p>
<hr />
<div>[[Category:Web|*]]<br />
{{Web infobox}}<br />
<br />
Content from [[Web]] should be merged here.<br />
<br />
Below is a list of known to be active Haskell web frameworks. Rather than one framework to rule them all, Haskell provides several options. You can view the [[Web/Deploy]] page to get an idea of how you might deploy an application written in some of these frameworks.<br />
<br />
See also: there are also many [[Web/Frameworks/Inactive|inactive web frameworks]] to draw inspiration from<br />
<br />
== Happstack ==<br />
<br />
Happstack is a Haskell web framework. Happstack is designed so that developers can prototype quickly, deploy painlessly, scale massively, operate reliably, and change easily. It supports GNU/Linux, OS X, FreeBSD, and Windows environments.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author:<br />
| Happstack team, HAppS LLC<br />
|-<br />
! Maintainer:<br />
| Happstack team <happs@googlegroups.com><br />
|-<br />
! Home page:<br />
| http://happstack.com/<br />
|-<br />
! Documentation:<br />
| http://www.happstack.com/C/ViewPage/3<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/happstack-server Hackage] - [http://patch-tag.com/r/mae/happstack Darcs]<br />
|}<br />
<br />
[http://happstack.com/ Happstack] is a complete web framework. The main component is [http://hackage.haskell.org/package/happstack-server happstack-server]: an integrated HTTP server, routing combinators, fileserving, etc. In addition, a number of packages that used to be coupled to Happstack have now been decoupled from it, but remain promoted and documented for use with Happstack:<br />
<br />
* [http://hackage.haskell.org/package/safecopy safecopy]: datatype serialization and migration support<br />
* [http://hackage.haskell.org/package/acid-state acid-state]: a powerful NoSQL ACID storage system with native support for Haskell types<br />
<br />
It also includes integration with many 3rd party libraries including:<br />
<br />
*templating: [http://hackage.haskell.org/package/blaze-html Blaze HTML], [http://www.yesodweb.com/book/shakespearean-templates Hamlet], [[HSP]], [[HStringTemplate]], [[Heist]], and more<br />
*forms: [http://hackage.haskell.org/package/reform reform]<br />
*routing: [http://hackage.haskell.org/package/web-routes web-routes] type-safe urls and routing<br />
*databases: can be used with most [[Database interfaces]] with no special support required<br />
<br />
See the [http://happstack.com/ Happstack Home Page] for more information and to learn how to get support via IRC and mailing lists.<br />
<br />
== Snap ==<br />
<br />
Snap is a simple web development framework for unix systems, written in the Haskell programming language.<br />
<br />
Snap is well-documented and has a test suite with a high level of code coverage, but it is early-stage software with still-evolving interfaces. Snap is therefore likely to be most appropriate for early adopters and potential contributors.<br />
<br />
* A fast HTTP server library with an optional high-concurrency backend using the libev event loop library<br />
* A sensible and clean monad for web programming<br />
* An XML-based templating system for generating HTML<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| James Sanders, Gregory Collins, Doug Beardsley<br />
|-<br />
! Maintainer:<br />
| snap@snapframework.com<br />
|-<br />
! Home page:<br />
| http://snapframework.com/<br />
|-<br />
! Documentation:<br />
| http://snapframework.com/docs<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/snap-server Hackage] - [http://git.snapframework.com/snap-server.git Git]<br />
|}<br />
<br />
== Yesod ==<br />
<br />
Yesod is designed for RESTful, type-safe, performant web apps. By leveraging quasi-quotation for the more boilerplate tasks, we get concise web apps with high levels of type safety. Its Hamlet templates are compile-time checked for correctness, and the controller (web-routes-quasi) uses type-safe URLs to make certain you are only generating valid URLs. It loosely follows Model/View/Controller principles.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Maintainer:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074271.html<br />
|-<br />
! Home page:<br />
| http://docs.yesodweb.com/<br />
|-<br />
! Documentation:<br />
| http://docs.yesodweb.com/yesod/<br />
|-<br />
! Screencast:<br />
| http://www.youtube.com/watch?v=BEWJnDgrmp0<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/yesod Hackage] - [http://github.com/snoyberg/yesod Github]<br />
|}<br />
<br />
[http://docs.yesodweb.com/ Yesod] is a full-featured web framework. It takes a modular approach to development, so many parts of the framework such as [http://docs.yesodweb.com/book/templates Hamlet] and [http://docs.yesodweb.com/book/persistent Persistent] are available as standalone packages. However, put together, Yesod provides you with solutions for templating, routing, persistence, sessions, JSON, authentication/authorization, and more. Yesod's major guiding principle is type safety: if your application compiles, it works.<br />
<br />
Yesod is very well documented through the [http://docs.yesodweb.com/book Yesod book]. Work is being done on an constant basis to improve the documentation status, but the first ten chapters (covering all the basics) are already done, so it should be easy to get started.<br />
<br />
Yesod is built on [http://hackage.haskell.org/package/wai WAI], or the Web Application Interface. This is similar to WSGI in Python or Rack in Ruby. It provides a single interface that all applications can target and work on multiple backends. Backends exist for CGI, FastCGI, SCGI, development server (auto-recompile) and even a Webkit-powered desktop version.<br />
<br />
But the premier backend is [http://hackage.haskell.org/package/warp Warp]: a very simple web server which, at the time of writing, is the fastest Haskell has to offer. You can read more in its [http://docs.yesodweb.com/blog/announcing-warp release announcement] and see some [http://docs.yesodweb.com/blog/warp-speed-ahead followup benchmarks]. Warp is already powering Yesod; some other major players that are planning a move are Hoogle and Happstack.<br />
<br />
You can see a [http://wiki.yesodweb.com/Powered%20by%20Yesod list of Yesod-powered sites and packages], or check out the [https://github.com/snoyberg/haskellers source code for Haskellers]. Most discussions for Yesod take place on the [http://groups.google.com/group/yesodweb yesodweb list], so feel free to join in and ask any questions you have, the Yesod community is very beginner-friendly.<br />
<br />
== Haskell on a Horse ==<br />
<br />
Haskell on a Horse (HoH) is a combinatorial web framework for the programming language Haskell. It is currently at an early, unsettled stage of development. It is available under the "BSD3" open-source license.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Jason Hart Priestley<br />
|-<br />
! Maintainer<br />
| jason@on-a-horse.org<br />
|-<br />
! Home page:<br />
| http://haskell.on-a-horse.org/<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/on-a-horse Hackage]<br />
|}<br />
<br />
== miku ==<br />
<br />
A simple library for fast web prototyping in Haskell, inspired by Ruby's Rack and Sinatra.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Wang, Jinjing<br />
|-<br />
! Maintainer<br />
| Wang, Jinjing <nfjinjing@gmail.com><br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/miku Hackage] - [http://github.com/nfjinjing/miku Github]<br />
|}<br />
<br />
== Lemmachine ==<br />
<br />
Lemmachine is a REST'ful web framework that makes it easy to get HTTP right by exposing users to overridable hooks with sane defaults. The main architecture is a copy of Erlang-based Webmachine, which is currently the best documentation reference (for hooks & general design).<br />
<br />
Lemmachine stands out from the dynamically typed Webmachine by being written in dependently typed Agda. The goal of the project is to show the advantages gained from compositional testing by taking advantage of proofs being inherently compositional. See proofs for examples of universally quantified proofs (tests over all possible input values) written against the default resource, which does not override any hooks.<br />
<br />
[http://github.com/larrytheliquid/Lemmachine#readme More information]<br />
<br />
{| class="wikitable"<br />
! Author<br />
| Larry Diehl<br />
|-<br />
! Packages & repositories<br />
| [http://github.com/larrytheliquid/Lemmachine Github]<br />
|}<br />
<br />
== mohws ==<br />
<br />
A web server with a module system and support for CGI. Based on Simon Marlow's original Haskell Web Server.<br />
<br />
{| class="wikitable"<br />
!License:<br />
|BSD3<br />
|-<br />
!Copyright:<br />
|Simon Marlow, Bjorn Bringert<br />
|-<br />
!Author:<br />
|Simon Marlow, Bjorn Bringert <bjorn@bringert.net><br />
|-<br />
!Maintainer:<br />
|Henning Thielemann <webserver@henning-thielemann.de><br />
|-<br />
!Packages & repositories<br />
|[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/mohws Hackage] - [http://code.haskell.org/mohws/ Darcs]<br />
|}<br />
<br />
== Salvia ==<br />
<br />
Salvia is a feature rich modular web server and web application framework that can be used to write dynamic websites in Haskell. From the lower level protocol code up to the high level application code, everything is written as a Salvia handler. This approach makes the server extremely extensible. To see a demo of a Salvia website, please see the salvia-demo package.<br />
<br />
All the low level protocol code can be found in the salvia-protocol package, which exposes the datatypes, parsers and pretty-printers for the URI, HTTP, Cookie and MIME protocols.<br />
<br />
This Salvia package itself can be separated into three different parts: the interface, the handlers and the implementation. The interface module defines a number of type classes that the user can build the web application against. Reading the request object, writing to the response, or gaining direct access to the socket, all of these actions are reflected using one type class aspect in the interface. The handlers are self contained modules that implement a single aspect of the Salvia web server. The handlers expose their interface requirements in their type context. Salvia can have multiple implementations which can be switched by using different instances for the interface type classes. This package has only one implementation, a simple accepting socket loop server. The salvia-extras package has two additional implementations. Keeping a clear distinction between the abstract server aspects and the actual implementation makes it very easy to migrate existing web application to different back-ends.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Sebastiaan Visser<br />
|-<br />
! Maintainer:<br />
| sfvisser@cs.uu.nl<br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074870.html<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/salvia Hackage] - [http://github.com/sebastiaanvisser/salvia Git]<br />
|}<br />
<br />
== Scotty ==<br />
<br />
A Haskell web framework inspired by Ruby's Sinatra, using WAI and Warp. Sinatra + Warp = Scotty.<br />
<br />
Scotty is the cheap and cheerful way to write RESTful, declarative web applications.<br />
<br />
* A page is as simple as defining the verb, url pattern, and Text content.<br />
* It is template-language agnostic. Anything that returns a Text value will do.<br />
* Conforms to WAI Application interface.<br />
* Uses very fast Warp webserver by default.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Andrew Farmer<br />
|-<br />
! Maintainer:<br />
| Andrew Farmer<br />
|-<br />
! Home page:<br />
| http://ittc.ku.edu/csdl/fpg/Tools/Scotty<br />
|-<br />
! Documentation:<br />
| http://hackage.haskell.org/package/scotty<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/scotty Hackage] - [https://github.com/xich/scotty Git]<br />
|}<br />
<br />
==See also==<br />
<br />
* [[Web/Framework survey]]</div>Daghttps://wiki.haskell.org/index.php?title=Web/Frameworks&diff=45781Web/Frameworks2012-05-25T19:05:18Z<p>Dag: /* Happstack */ link happstack-server to hackage</p>
<hr />
<div>[[Category:Web|*]]<br />
{{Web infobox}}<br />
<br />
Content from [[Web]] should be merged here.<br />
<br />
Below is a list of known to be active Haskell web frameworks. Rather than one framework to rule them all, Haskell provides several options. You can view the [[Web/Deploy]] page to get an idea of how you might deploy an application written in some of these frameworks.<br />
<br />
See also: there are also many [[Web/Frameworks/Inactive|inactive web frameworks]] to draw inspiration from<br />
<br />
== Happstack ==<br />
<br />
Happstack is a Haskell web framework. Happstack is designed so that developers can prototype quickly, deploy painlessly, scale massively, operate reliably, and change easily. It supports GNU/Linux, OS X, FreeBSD, and Windows environments.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author:<br />
| Happstack team, HAppS LLC<br />
|-<br />
! Maintainer:<br />
| Happstack team <happs@googlegroups.com><br />
|-<br />
! Home page:<br />
| http://happstack.com/<br />
|-<br />
! Documentation:<br />
| http://www.happstack.com/C/ViewPage/3<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/happstack-server Hackage] - [http://patch-tag.com/r/mae/happstack Darcs]<br />
|}<br />
<br />
[http://happstack.com/ Happstack] is a complete web framework. The main component is [http://hackage.haskell.org/package/happstack-server happstack-server]: an integrated HTTP server, routing combinators, fileserving, etc. In addition, a number of packages that used to be coupled to Happstack have now been decoupled from it, but remain promoted and documented for use with Happstack:<br />
<br />
* [http://hackage.haskell.org/package/safecopy safecopy]: datatype serialization and migration support<br />
* [http://hackage.haskell.org/package/acid-state acid-state]: a powerful NoSQL ACID storage system with native support for Haskell types<br />
<br />
It also includes integration with many 3rd party libraries including:<br />
<br />
*templating: [http://hackage.haskell.org/package/blaze-html Blaze HTML combinator library], [http://docs.yesodweb.com/ Hamlet], [[HSP]], [[HStringTemplate]], [[Heist]], and more<br />
*forms: [http://hackage.haskell.org/package/reform reform]<br />
*routing: [http://hackage.haskell.org/package/web-routes web-routes] type-safe urls and routing<br />
*databases: can be used with most [[Database interfaces]] with no special support required<br />
<br />
See the [http://happstack.com/ Happstack Home Page] for more information and to learn how to get support via IRC and mailing lists.<br />
<br />
== Snap ==<br />
<br />
Snap is a simple web development framework for unix systems, written in the Haskell programming language.<br />
<br />
Snap is well-documented and has a test suite with a high level of code coverage, but it is early-stage software with still-evolving interfaces. Snap is therefore likely to be most appropriate for early adopters and potential contributors.<br />
<br />
* A fast HTTP server library with an optional high-concurrency backend using the libev event loop library<br />
* A sensible and clean monad for web programming<br />
* An XML-based templating system for generating HTML<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| James Sanders, Gregory Collins, Doug Beardsley<br />
|-<br />
! Maintainer:<br />
| snap@snapframework.com<br />
|-<br />
! Home page:<br />
| http://snapframework.com/<br />
|-<br />
! Documentation:<br />
| http://snapframework.com/docs<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/snap-server Hackage] - [http://git.snapframework.com/snap-server.git Git]<br />
|}<br />
<br />
== Yesod ==<br />
<br />
Yesod is designed for RESTful, type-safe, performant web apps. By leveraging quasi-quotation for the more boilerplate tasks, we get concise web apps with high levels of type safety. Its Hamlet templates are compile-time checked for correctness, and the controller (web-routes-quasi) uses type-safe URLs to make certain you are only generating valid URLs. It loosely follows Model/View/Controller principles.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Maintainer:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074271.html<br />
|-<br />
! Home page:<br />
| http://docs.yesodweb.com/<br />
|-<br />
! Documentation:<br />
| http://docs.yesodweb.com/yesod/<br />
|-<br />
! Screencast:<br />
| http://www.youtube.com/watch?v=BEWJnDgrmp0<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/yesod Hackage] - [http://github.com/snoyberg/yesod Github]<br />
|}<br />
<br />
[http://docs.yesodweb.com/ Yesod] is a full-featured web framework. It takes a modular approach to development, so many parts of the framework such as [http://docs.yesodweb.com/book/templates Hamlet] and [http://docs.yesodweb.com/book/persistent Persistent] are available as standalone packages. However, put together, Yesod provides you with solutions for templating, routing, persistence, sessions, JSON, authentication/authorization, and more. Yesod's major guiding principle is type safety: if your application compiles, it works.<br />
<br />
Yesod is very well documented through the [http://docs.yesodweb.com/book Yesod book]. Work is being done on an constant basis to improve the documentation status, but the first ten chapters (covering all the basics) are already done, so it should be easy to get started.<br />
<br />
Yesod is built on [http://hackage.haskell.org/package/wai WAI], or the Web Application Interface. This is similar to WSGI in Python or Rack in Ruby. It provides a single interface that all applications can target and work on multiple backends. Backends exist for CGI, FastCGI, SCGI, development server (auto-recompile) and even a Webkit-powered desktop version.<br />
<br />
But the premier backend is [http://hackage.haskell.org/package/warp Warp]: a very simple web server which, at the time of writing, is the fastest Haskell has to offer. You can read more in its [http://docs.yesodweb.com/blog/announcing-warp release announcement] and see some [http://docs.yesodweb.com/blog/warp-speed-ahead followup benchmarks]. Warp is already powering Yesod; some other major players that are planning a move are Hoogle and Happstack.<br />
<br />
You can see a [http://wiki.yesodweb.com/Powered%20by%20Yesod list of Yesod-powered sites and packages], or check out the [https://github.com/snoyberg/haskellers source code for Haskellers]. Most discussions for Yesod take place on the [http://groups.google.com/group/yesodweb yesodweb list], so feel free to join in and ask any questions you have, the Yesod community is very beginner-friendly.<br />
<br />
== Haskell on a Horse ==<br />
<br />
Haskell on a Horse (HoH) is a combinatorial web framework for the programming language Haskell. It is currently at an early, unsettled stage of development. It is available under the "BSD3" open-source license.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Jason Hart Priestley<br />
|-<br />
! Maintainer<br />
| jason@on-a-horse.org<br />
|-<br />
! Home page:<br />
| http://haskell.on-a-horse.org/<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/on-a-horse Hackage]<br />
|}<br />
<br />
== miku ==<br />
<br />
A simple library for fast web prototyping in Haskell, inspired by Ruby's Rack and Sinatra.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Wang, Jinjing<br />
|-<br />
! Maintainer<br />
| Wang, Jinjing <nfjinjing@gmail.com><br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/miku Hackage] - [http://github.com/nfjinjing/miku Github]<br />
|}<br />
<br />
== Lemmachine ==<br />
<br />
Lemmachine is a REST'ful web framework that makes it easy to get HTTP right by exposing users to overridable hooks with sane defaults. The main architecture is a copy of Erlang-based Webmachine, which is currently the best documentation reference (for hooks & general design).<br />
<br />
Lemmachine stands out from the dynamically typed Webmachine by being written in dependently typed Agda. The goal of the project is to show the advantages gained from compositional testing by taking advantage of proofs being inherently compositional. See proofs for examples of universally quantified proofs (tests over all possible input values) written against the default resource, which does not override any hooks.<br />
<br />
[http://github.com/larrytheliquid/Lemmachine#readme More information]<br />
<br />
{| class="wikitable"<br />
! Author<br />
| Larry Diehl<br />
|-<br />
! Packages & repositories<br />
| [http://github.com/larrytheliquid/Lemmachine Github]<br />
|}<br />
<br />
== mohws ==<br />
<br />
A web server with a module system and support for CGI. Based on Simon Marlow's original Haskell Web Server.<br />
<br />
{| class="wikitable"<br />
!License:<br />
|BSD3<br />
|-<br />
!Copyright:<br />
|Simon Marlow, Bjorn Bringert<br />
|-<br />
!Author:<br />
|Simon Marlow, Bjorn Bringert <bjorn@bringert.net><br />
|-<br />
!Maintainer:<br />
|Henning Thielemann <webserver@henning-thielemann.de><br />
|-<br />
!Packages & repositories<br />
|[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/mohws Hackage] - [http://code.haskell.org/mohws/ Darcs]<br />
|}<br />
<br />
== Salvia ==<br />
<br />
Salvia is a feature rich modular web server and web application framework that can be used to write dynamic websites in Haskell. From the lower level protocol code up to the high level application code, everything is written as a Salvia handler. This approach makes the server extremely extensible. To see a demo of a Salvia website, please see the salvia-demo package.<br />
<br />
All the low level protocol code can be found in the salvia-protocol package, which exposes the datatypes, parsers and pretty-printers for the URI, HTTP, Cookie and MIME protocols.<br />
<br />
This Salvia package itself can be separated into three different parts: the interface, the handlers and the implementation. The interface module defines a number of type classes that the user can build the web application against. Reading the request object, writing to the response, or gaining direct access to the socket, all of these actions are reflected using one type class aspect in the interface. The handlers are self contained modules that implement a single aspect of the Salvia web server. The handlers expose their interface requirements in their type context. Salvia can have multiple implementations which can be switched by using different instances for the interface type classes. This package has only one implementation, a simple accepting socket loop server. The salvia-extras package has two additional implementations. Keeping a clear distinction between the abstract server aspects and the actual implementation makes it very easy to migrate existing web application to different back-ends.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Sebastiaan Visser<br />
|-<br />
! Maintainer:<br />
| sfvisser@cs.uu.nl<br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074870.html<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/salvia Hackage] - [http://github.com/sebastiaanvisser/salvia Git]<br />
|}<br />
<br />
== Scotty ==<br />
<br />
A Haskell web framework inspired by Ruby's Sinatra, using WAI and Warp. Sinatra + Warp = Scotty.<br />
<br />
Scotty is the cheap and cheerful way to write RESTful, declarative web applications.<br />
<br />
* A page is as simple as defining the verb, url pattern, and Text content.<br />
* It is template-language agnostic. Anything that returns a Text value will do.<br />
* Conforms to WAI Application interface.<br />
* Uses very fast Warp webserver by default.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Andrew Farmer<br />
|-<br />
! Maintainer:<br />
| Andrew Farmer<br />
|-<br />
! Home page:<br />
| http://ittc.ku.edu/csdl/fpg/Tools/Scotty<br />
|-<br />
! Documentation:<br />
| http://hackage.haskell.org/package/scotty<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/scotty Hackage] - [https://github.com/xich/scotty Git]<br />
|}<br />
<br />
==See also==<br />
<br />
* [[Web/Framework survey]]</div>Daghttps://wiki.haskell.org/index.php?title=Web/Frameworks&diff=45780Web/Frameworks2012-05-25T19:04:12Z<p>Dag: /* Happstack */ bring up to date with recent developments</p>
<hr />
<div>[[Category:Web|*]]<br />
{{Web infobox}}<br />
<br />
Content from [[Web]] should be merged here.<br />
<br />
Below is a list of known to be active Haskell web frameworks. Rather than one framework to rule them all, Haskell provides several options. You can view the [[Web/Deploy]] page to get an idea of how you might deploy an application written in some of these frameworks.<br />
<br />
See also: there are also many [[Web/Frameworks/Inactive|inactive web frameworks]] to draw inspiration from<br />
<br />
== Happstack ==<br />
<br />
Happstack is a Haskell web framework. Happstack is designed so that developers can prototype quickly, deploy painlessly, scale massively, operate reliably, and change easily. It supports GNU/Linux, OS X, FreeBSD, and Windows environments.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author:<br />
| Happstack team, HAppS LLC<br />
|-<br />
! Maintainer:<br />
| Happstack team <happs@googlegroups.com><br />
|-<br />
! Home page:<br />
| http://happstack.com/<br />
|-<br />
! Documentation:<br />
| http://www.happstack.com/C/ViewPage/3<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/happstack-server Hackage] - [http://patch-tag.com/r/mae/happstack Darcs]<br />
|}<br />
<br />
[http://happstack.com/ Happstack] is a complete web framework. The main component is happstack-server: an integrated HTTP server, routing combinators, fileserving, etc. In addition, a number of packages that used to be coupled to Happstack have now been decoupled from it, but remain promoted and documented for use with Happstack:<br />
<br />
* [http://hackage.haskell.org/package/safecopy safecopy]: datatype serialization and migration support<br />
* [http://hackage.haskell.org/package/acid-state acid-state]: a powerful NoSQL ACID storage system with native support for Haskell types<br />
<br />
It also includes integration with many 3rd party libraries including:<br />
<br />
*templating: [http://hackage.haskell.org/package/blaze-html Blaze HTML combinator library], [http://docs.yesodweb.com/ Hamlet], [[HSP]], [[HStringTemplate]], [[Heist]], and more<br />
*forms: [http://hackage.haskell.org/package/reform reform]<br />
*routing: [http://hackage.haskell.org/package/web-routes web-routes] type-safe urls and routing<br />
*databases: can be used with most [[Database interfaces]] with no special support required<br />
<br />
See the [http://happstack.com/ Happstack Home Page] for more information and to learn how to get support via IRC and mailing lists.<br />
<br />
== Snap ==<br />
<br />
Snap is a simple web development framework for unix systems, written in the Haskell programming language.<br />
<br />
Snap is well-documented and has a test suite with a high level of code coverage, but it is early-stage software with still-evolving interfaces. Snap is therefore likely to be most appropriate for early adopters and potential contributors.<br />
<br />
* A fast HTTP server library with an optional high-concurrency backend using the libev event loop library<br />
* A sensible and clean monad for web programming<br />
* An XML-based templating system for generating HTML<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| James Sanders, Gregory Collins, Doug Beardsley<br />
|-<br />
! Maintainer:<br />
| snap@snapframework.com<br />
|-<br />
! Home page:<br />
| http://snapframework.com/<br />
|-<br />
! Documentation:<br />
| http://snapframework.com/docs<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/snap-server Hackage] - [http://git.snapframework.com/snap-server.git Git]<br />
|}<br />
<br />
== Yesod ==<br />
<br />
Yesod is designed for RESTful, type-safe, performant web apps. By leveraging quasi-quotation for the more boilerplate tasks, we get concise web apps with high levels of type safety. Its Hamlet templates are compile-time checked for correctness, and the controller (web-routes-quasi) uses type-safe URLs to make certain you are only generating valid URLs. It loosely follows Model/View/Controller principles.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Maintainer:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074271.html<br />
|-<br />
! Home page:<br />
| http://docs.yesodweb.com/<br />
|-<br />
! Documentation:<br />
| http://docs.yesodweb.com/yesod/<br />
|-<br />
! Screencast:<br />
| http://www.youtube.com/watch?v=BEWJnDgrmp0<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/yesod Hackage] - [http://github.com/snoyberg/yesod Github]<br />
|}<br />
<br />
[http://docs.yesodweb.com/ Yesod] is a full-featured web framework. It takes a modular approach to development, so many parts of the framework such as [http://docs.yesodweb.com/book/templates Hamlet] and [http://docs.yesodweb.com/book/persistent Persistent] are available as standalone packages. However, put together, Yesod provides you with solutions for templating, routing, persistence, sessions, JSON, authentication/authorization, and more. Yesod's major guiding principle is type safety: if your application compiles, it works.<br />
<br />
Yesod is very well documented through the [http://docs.yesodweb.com/book Yesod book]. Work is being done on an constant basis to improve the documentation status, but the first ten chapters (covering all the basics) are already done, so it should be easy to get started.<br />
<br />
Yesod is built on [http://hackage.haskell.org/package/wai WAI], or the Web Application Interface. This is similar to WSGI in Python or Rack in Ruby. It provides a single interface that all applications can target and work on multiple backends. Backends exist for CGI, FastCGI, SCGI, development server (auto-recompile) and even a Webkit-powered desktop version.<br />
<br />
But the premier backend is [http://hackage.haskell.org/package/warp Warp]: a very simple web server which, at the time of writing, is the fastest Haskell has to offer. You can read more in its [http://docs.yesodweb.com/blog/announcing-warp release announcement] and see some [http://docs.yesodweb.com/blog/warp-speed-ahead followup benchmarks]. Warp is already powering Yesod; some other major players that are planning a move are Hoogle and Happstack.<br />
<br />
You can see a [http://wiki.yesodweb.com/Powered%20by%20Yesod list of Yesod-powered sites and packages], or check out the [https://github.com/snoyberg/haskellers source code for Haskellers]. Most discussions for Yesod take place on the [http://groups.google.com/group/yesodweb yesodweb list], so feel free to join in and ask any questions you have, the Yesod community is very beginner-friendly.<br />
<br />
== Haskell on a Horse ==<br />
<br />
Haskell on a Horse (HoH) is a combinatorial web framework for the programming language Haskell. It is currently at an early, unsettled stage of development. It is available under the "BSD3" open-source license.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Jason Hart Priestley<br />
|-<br />
! Maintainer<br />
| jason@on-a-horse.org<br />
|-<br />
! Home page:<br />
| http://haskell.on-a-horse.org/<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/on-a-horse Hackage]<br />
|}<br />
<br />
== miku ==<br />
<br />
A simple library for fast web prototyping in Haskell, inspired by Ruby's Rack and Sinatra.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Wang, Jinjing<br />
|-<br />
! Maintainer<br />
| Wang, Jinjing <nfjinjing@gmail.com><br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/miku Hackage] - [http://github.com/nfjinjing/miku Github]<br />
|}<br />
<br />
== Lemmachine ==<br />
<br />
Lemmachine is a REST'ful web framework that makes it easy to get HTTP right by exposing users to overridable hooks with sane defaults. The main architecture is a copy of Erlang-based Webmachine, which is currently the best documentation reference (for hooks & general design).<br />
<br />
Lemmachine stands out from the dynamically typed Webmachine by being written in dependently typed Agda. The goal of the project is to show the advantages gained from compositional testing by taking advantage of proofs being inherently compositional. See proofs for examples of universally quantified proofs (tests over all possible input values) written against the default resource, which does not override any hooks.<br />
<br />
[http://github.com/larrytheliquid/Lemmachine#readme More information]<br />
<br />
{| class="wikitable"<br />
! Author<br />
| Larry Diehl<br />
|-<br />
! Packages & repositories<br />
| [http://github.com/larrytheliquid/Lemmachine Github]<br />
|}<br />
<br />
== mohws ==<br />
<br />
A web server with a module system and support for CGI. Based on Simon Marlow's original Haskell Web Server.<br />
<br />
{| class="wikitable"<br />
!License:<br />
|BSD3<br />
|-<br />
!Copyright:<br />
|Simon Marlow, Bjorn Bringert<br />
|-<br />
!Author:<br />
|Simon Marlow, Bjorn Bringert <bjorn@bringert.net><br />
|-<br />
!Maintainer:<br />
|Henning Thielemann <webserver@henning-thielemann.de><br />
|-<br />
!Packages & repositories<br />
|[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/mohws Hackage] - [http://code.haskell.org/mohws/ Darcs]<br />
|}<br />
<br />
== Salvia ==<br />
<br />
Salvia is a feature rich modular web server and web application framework that can be used to write dynamic websites in Haskell. From the lower level protocol code up to the high level application code, everything is written as a Salvia handler. This approach makes the server extremely extensible. To see a demo of a Salvia website, please see the salvia-demo package.<br />
<br />
All the low level protocol code can be found in the salvia-protocol package, which exposes the datatypes, parsers and pretty-printers for the URI, HTTP, Cookie and MIME protocols.<br />
<br />
This Salvia package itself can be separated into three different parts: the interface, the handlers and the implementation. The interface module defines a number of type classes that the user can build the web application against. Reading the request object, writing to the response, or gaining direct access to the socket, all of these actions are reflected using one type class aspect in the interface. The handlers are self contained modules that implement a single aspect of the Salvia web server. The handlers expose their interface requirements in their type context. Salvia can have multiple implementations which can be switched by using different instances for the interface type classes. This package has only one implementation, a simple accepting socket loop server. The salvia-extras package has two additional implementations. Keeping a clear distinction between the abstract server aspects and the actual implementation makes it very easy to migrate existing web application to different back-ends.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Sebastiaan Visser<br />
|-<br />
! Maintainer:<br />
| sfvisser@cs.uu.nl<br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074870.html<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/salvia Hackage] - [http://github.com/sebastiaanvisser/salvia Git]<br />
|}<br />
<br />
== Scotty ==<br />
<br />
A Haskell web framework inspired by Ruby's Sinatra, using WAI and Warp. Sinatra + Warp = Scotty.<br />
<br />
Scotty is the cheap and cheerful way to write RESTful, declarative web applications.<br />
<br />
* A page is as simple as defining the verb, url pattern, and Text content.<br />
* It is template-language agnostic. Anything that returns a Text value will do.<br />
* Conforms to WAI Application interface.<br />
* Uses very fast Warp webserver by default.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Andrew Farmer<br />
|-<br />
! Maintainer:<br />
| Andrew Farmer<br />
|-<br />
! Home page:<br />
| http://ittc.ku.edu/csdl/fpg/Tools/Scotty<br />
|-<br />
! Documentation:<br />
| http://hackage.haskell.org/package/scotty<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/scotty Hackage] - [https://github.com/xich/scotty Git]<br />
|}<br />
<br />
==See also==<br />
<br />
* [[Web/Framework survey]]</div>Daghttps://wiki.haskell.org/index.php?title=Web/Frameworks&diff=45779Web/Frameworks2012-05-25T18:34:30Z<p>Dag: /* Happstack */ Update links to docs and hackage</p>
<hr />
<div>[[Category:Web|*]]<br />
{{Web infobox}}<br />
<br />
Content from [[Web]] should be merged here.<br />
<br />
Below is a list of known to be active Haskell web frameworks. Rather than one framework to rule them all, Haskell provides several options. You can view the [[Web/Deploy]] page to get an idea of how you might deploy an application written in some of these frameworks.<br />
<br />
See also: there are also many [[Web/Frameworks/Inactive|inactive web frameworks]] to draw inspiration from<br />
<br />
== Happstack ==<br />
<br />
Happstack is a Haskell web framework. Happstack is designed so that developers can prototype quickly, deploy painlessly, scale massively, operate reliably, and change easily. It supports GNU/Linux, OS X, FreeBSD, and Windows environments.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author:<br />
| Happstack team, HAppS LLC<br />
|-<br />
! Maintainer:<br />
| Happstack team <happs@googlegroups.com><br />
|-<br />
! Home page:<br />
| http://happstack.com/<br />
|-<br />
! Documentation:<br />
| http://www.happstack.com/C/ViewPage/3<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/happstack-server Hackage] - [http://patch-tag.com/r/mae/happstack Darcs]<br />
|}<br />
<br />
<br />
[http://happstack.com/ Happstack] is a complete web framework. It is organized as a suite of libraries including: <br />
* happstack-server: an integrated HTTP server, routing combinators, fileserving, etc<br />
* happstack-data: datatype serialization and migration support<br />
* happstack-state (aka macid): an (optional) powerful NoSQL ACID storage system with native support for Haskell types and replication<br />
<br />
It also includes integration with many 3rd party libraries including:<br />
<br />
*templating: [http://hackage.haskell.org/package/blaze-html Blaze HTML combinator library], [http://docs.yesodweb.com/ Hamlet], [[HSP]], [[HStringTemplate]], [[Heist]], and more<br />
*forms: [[Formlets]]<br />
*routing: [http://hackage.haskell.org/package/web-routes web-routes] type-safe urls and routing<br />
*databases: can be used with most [[Database interfaces]] with no special support required<br />
<br />
Happstack is primarily intended for use on VPS or dedicated hosts, but can be used with CGI via FastCGI or [http://hackage.haskell.org/package/hack-handler-happstack-2009.12.20 hack].<br />
<br />
See the [http://happstack.com/ Happstack Home Page] for more information and to learn how to get support via IRC and mailing lists.<br />
<br />
== Snap ==<br />
<br />
Snap is a simple web development framework for unix systems, written in the Haskell programming language.<br />
<br />
Snap is well-documented and has a test suite with a high level of code coverage, but it is early-stage software with still-evolving interfaces. Snap is therefore likely to be most appropriate for early adopters and potential contributors.<br />
<br />
* A fast HTTP server library with an optional high-concurrency backend using the libev event loop library<br />
* A sensible and clean monad for web programming<br />
* An XML-based templating system for generating HTML<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| James Sanders, Gregory Collins, Doug Beardsley<br />
|-<br />
! Maintainer:<br />
| snap@snapframework.com<br />
|-<br />
! Home page:<br />
| http://snapframework.com/<br />
|-<br />
! Documentation:<br />
| http://snapframework.com/docs<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/snap-server Hackage] - [http://git.snapframework.com/snap-server.git Git]<br />
|}<br />
<br />
== Yesod ==<br />
<br />
Yesod is designed for RESTful, type-safe, performant web apps. By leveraging quasi-quotation for the more boilerplate tasks, we get concise web apps with high levels of type safety. Its Hamlet templates are compile-time checked for correctness, and the controller (web-routes-quasi) uses type-safe URLs to make certain you are only generating valid URLs. It loosely follows Model/View/Controller principles.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Maintainer:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074271.html<br />
|-<br />
! Home page:<br />
| http://docs.yesodweb.com/<br />
|-<br />
! Documentation:<br />
| http://docs.yesodweb.com/yesod/<br />
|-<br />
! Screencast:<br />
| http://www.youtube.com/watch?v=BEWJnDgrmp0<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/yesod Hackage] - [http://github.com/snoyberg/yesod Github]<br />
|}<br />
<br />
[http://docs.yesodweb.com/ Yesod] is a full-featured web framework. It takes a modular approach to development, so many parts of the framework such as [http://docs.yesodweb.com/book/templates Hamlet] and [http://docs.yesodweb.com/book/persistent Persistent] are available as standalone packages. However, put together, Yesod provides you with solutions for templating, routing, persistence, sessions, JSON, authentication/authorization, and more. Yesod's major guiding principle is type safety: if your application compiles, it works.<br />
<br />
Yesod is very well documented through the [http://docs.yesodweb.com/book Yesod book]. Work is being done on an constant basis to improve the documentation status, but the first ten chapters (covering all the basics) are already done, so it should be easy to get started.<br />
<br />
Yesod is built on [http://hackage.haskell.org/package/wai WAI], or the Web Application Interface. This is similar to WSGI in Python or Rack in Ruby. It provides a single interface that all applications can target and work on multiple backends. Backends exist for CGI, FastCGI, SCGI, development server (auto-recompile) and even a Webkit-powered desktop version.<br />
<br />
But the premier backend is [http://hackage.haskell.org/package/warp Warp]: a very simple web server which, at the time of writing, is the fastest Haskell has to offer. You can read more in its [http://docs.yesodweb.com/blog/announcing-warp release announcement] and see some [http://docs.yesodweb.com/blog/warp-speed-ahead followup benchmarks]. Warp is already powering Yesod; some other major players that are planning a move are Hoogle and Happstack.<br />
<br />
You can see a [http://wiki.yesodweb.com/Powered%20by%20Yesod list of Yesod-powered sites and packages], or check out the [https://github.com/snoyberg/haskellers source code for Haskellers]. Most discussions for Yesod take place on the [http://groups.google.com/group/yesodweb yesodweb list], so feel free to join in and ask any questions you have, the Yesod community is very beginner-friendly.<br />
<br />
== Haskell on a Horse ==<br />
<br />
Haskell on a Horse (HoH) is a combinatorial web framework for the programming language Haskell. It is currently at an early, unsettled stage of development. It is available under the "BSD3" open-source license.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Jason Hart Priestley<br />
|-<br />
! Maintainer<br />
| jason@on-a-horse.org<br />
|-<br />
! Home page:<br />
| http://haskell.on-a-horse.org/<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/on-a-horse Hackage]<br />
|}<br />
<br />
== miku ==<br />
<br />
A simple library for fast web prototyping in Haskell, inspired by Ruby's Rack and Sinatra.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Wang, Jinjing<br />
|-<br />
! Maintainer<br />
| Wang, Jinjing <nfjinjing@gmail.com><br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/miku Hackage] - [http://github.com/nfjinjing/miku Github]<br />
|}<br />
<br />
== Lemmachine ==<br />
<br />
Lemmachine is a REST'ful web framework that makes it easy to get HTTP right by exposing users to overridable hooks with sane defaults. The main architecture is a copy of Erlang-based Webmachine, which is currently the best documentation reference (for hooks & general design).<br />
<br />
Lemmachine stands out from the dynamically typed Webmachine by being written in dependently typed Agda. The goal of the project is to show the advantages gained from compositional testing by taking advantage of proofs being inherently compositional. See proofs for examples of universally quantified proofs (tests over all possible input values) written against the default resource, which does not override any hooks.<br />
<br />
[http://github.com/larrytheliquid/Lemmachine#readme More information]<br />
<br />
{| class="wikitable"<br />
! Author<br />
| Larry Diehl<br />
|-<br />
! Packages & repositories<br />
| [http://github.com/larrytheliquid/Lemmachine Github]<br />
|}<br />
<br />
== mohws ==<br />
<br />
A web server with a module system and support for CGI. Based on Simon Marlow's original Haskell Web Server.<br />
<br />
{| class="wikitable"<br />
!License:<br />
|BSD3<br />
|-<br />
!Copyright:<br />
|Simon Marlow, Bjorn Bringert<br />
|-<br />
!Author:<br />
|Simon Marlow, Bjorn Bringert <bjorn@bringert.net><br />
|-<br />
!Maintainer:<br />
|Henning Thielemann <webserver@henning-thielemann.de><br />
|-<br />
!Packages & repositories<br />
|[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/mohws Hackage] - [http://code.haskell.org/mohws/ Darcs]<br />
|}<br />
<br />
== Salvia ==<br />
<br />
Salvia is a feature rich modular web server and web application framework that can be used to write dynamic websites in Haskell. From the lower level protocol code up to the high level application code, everything is written as a Salvia handler. This approach makes the server extremely extensible. To see a demo of a Salvia website, please see the salvia-demo package.<br />
<br />
All the low level protocol code can be found in the salvia-protocol package, which exposes the datatypes, parsers and pretty-printers for the URI, HTTP, Cookie and MIME protocols.<br />
<br />
This Salvia package itself can be separated into three different parts: the interface, the handlers and the implementation. The interface module defines a number of type classes that the user can build the web application against. Reading the request object, writing to the response, or gaining direct access to the socket, all of these actions are reflected using one type class aspect in the interface. The handlers are self contained modules that implement a single aspect of the Salvia web server. The handlers expose their interface requirements in their type context. Salvia can have multiple implementations which can be switched by using different instances for the interface type classes. This package has only one implementation, a simple accepting socket loop server. The salvia-extras package has two additional implementations. Keeping a clear distinction between the abstract server aspects and the actual implementation makes it very easy to migrate existing web application to different back-ends.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Sebastiaan Visser<br />
|-<br />
! Maintainer:<br />
| sfvisser@cs.uu.nl<br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074870.html<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/salvia Hackage] - [http://github.com/sebastiaanvisser/salvia Git]<br />
|}<br />
<br />
== Scotty ==<br />
<br />
A Haskell web framework inspired by Ruby's Sinatra, using WAI and Warp. Sinatra + Warp = Scotty.<br />
<br />
Scotty is the cheap and cheerful way to write RESTful, declarative web applications.<br />
<br />
* A page is as simple as defining the verb, url pattern, and Text content.<br />
* It is template-language agnostic. Anything that returns a Text value will do.<br />
* Conforms to WAI Application interface.<br />
* Uses very fast Warp webserver by default.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Andrew Farmer<br />
|-<br />
! Maintainer:<br />
| Andrew Farmer<br />
|-<br />
! Home page:<br />
| http://ittc.ku.edu/csdl/fpg/Tools/Scotty<br />
|-<br />
! Documentation:<br />
| http://hackage.haskell.org/package/scotty<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/scotty Hackage] - [https://github.com/xich/scotty Git]<br />
|}<br />
<br />
==See also==<br />
<br />
* [[Web/Framework survey]]</div>Daghttps://wiki.haskell.org/index.php?title=Web/Databases_and_Persistence&diff=44516Web/Databases and Persistence2012-02-13T19:41:33Z<p>Dag: Add acid-state</p>
<hr />
<div>[[Category:Web|*]]<br />
{{Web infobox}}<br />
<br />
Below is a list of databases that have been used or designed for web development. See also: [[Libraries_and_tools/Database_interfaces|Database Interfaces]]<br />
<br />
== acid-state ==<br />
<br />
acid-state is the successor of the now deprecated happstack-state and is completely free from any dependencies on happstack.<br />
<br />
{| class="wikitable"<br />
! License<br />
| Public Domain<br />
|-<br />
! Author:<br />
| David Himmelstrup<br />
|-<br />
! Home page:<br />
| http://acid-state.seize.it/<br />
|-<br />
! Documentation:<br />
| [http://mirror.seize.it/acid-state/examples/ Stand-alone examples], [http://happstack.com/docs/crashcourse/AcidState.html usage with Happstack] and [https://github.com/mightybyte/snaplet-acid-state/blob/master/examples/Site.hs usage with Snap].<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/acid-state Hackage] - [http://mirror.seize.it/acid-state/ Darcs]<br />
|}<br />
<br />
== happstack-state ==<br />
<br />
happstack-state, also referred to as MACID, is a native Haskell persistent data store layer. It stores Haskell datatypes and queries are written in Haskell. Although it is part of the [[Happstack]] suite, it does not depend on happstack-server and can easily be used with other web frameworks.<br />
<br />
In buzzword terms, happstack-state is a NoSQL, RAM-cloud which can store arbitrary Haskell datatypes. <br />
<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author:<br />
| Happstack team, HAppS LLC<br />
|-<br />
! Maintainer:<br />
| Happstack team <happs@googlegroups.com><br />
|-<br />
! Home page:<br />
| http://happstack.com/index.html<br />
|-<br />
! Documentation:<br />
| http://happstack.com/docs<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/happstack Hackage] - [http://patch-tag.com/r/mae/happstack/pullrepo Darcs]<br />
|}<br />
<br />
== HDBC ==<br />
<br />
HDBC (Haskell Database Connectivity) provides an abstraction layer between Haskell programs and SQL relational databases. This lets you write database code once, in Haskell, and have it work with any number of backend SQL databases (MySQL, Oracle, PostgreSQL, ODBC-compliant databases, etc.)<br />
<br />
* HDBC provides an abstraction layer between Haskell programs and SQL relational databases. This lets you write database code once, in Haskell, and have it work with any number of backend SQL databases (MySQL, Oracle, PostgreSQL, ODBC-compliant databases, etc.)<br />
* HDBC is modeled loosely on Perl’s DBI interface, though it has also been influenced by Python’s DB-API v2, JDBC in Java, and HSQL in Haskell.<br />
* HDBC is a from-scratch effort. It is not a reimplementation of HSQL, though its purpose is the same.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| LGPL<br />
|-<br />
! Author:<br />
| John Goerzen<br />
|-<br />
! Maintainer:<br />
| John Goerzen <jgoerzen@complete.org><br />
|-<br />
! Home page:<br />
| http://github.com/jgoerzen/hdbc/wiki<br />
|-<br />
! Documentation:<br />
| [http://hackage.haskell.org/packages/archive/HDBC/latest/doc/html/Database-HDBC.html Haddock]<br />
|}<br />
<br />
== Persistent ==<br />
<br />
Persistent is a high-level, non-relational, type-safe persistence layer for Haskell. Its design allows it to be used on both SQL and non-SQL backends. Heavy usage of type families allows strong type guarantees, while usage of template haskell removes the need for boilerplate coding.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Maintainer:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Documentation:<br />
| http://docs.yesodweb.com/book/persistent<br />
|-<br />
! Packages & repositories<br />
| [http://hackage.haskell.org/package/persistent Hackage] - [http://github.com/snoyberg/persistent Github]<br />
|}<br />
<br />
== Takusen ==<br />
<br />
Takusen is a DBMS access library. Like HSQL and HDBC, we support arbitrary SQL statements (currently strings, extensible to anything that can be converted to a string).<br />
<br />
Takusen's unique selling point is safety and efficiency. We statically ensure all acquired database resources - such as cursors, connections, and statement handles - are released, exactly once, at predictable times. Takusen can avoid loading the whole result set in memory, and so can handle queries returning millions of rows in constant space. Takusen also supports automatic marshalling and unmarshalling of results and query parameters. These benefits come from the design of query result processing around a left-fold enumerator.<br />
<br />
Currently we fully support ODBC, Oracle, Sqlite, and PostgreSQL.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Alistair Bayley, Oleg Kiselyov<br />
|-<br />
! Maintainer:<br />
| alistair@abayley.org, oleg@pobox.com<br />
|-<br />
! Announcement:<br />
| [http://www.haskell.org/pipermail/haskell-cafe/2010-July/081224.html Haskell-Cafe]<br />
|-<br />
! Packages & repositories<br />
| [http://hackage.haskell.org/package/Takusen Hackage] - [http://code.haskell.org/takusen Darcs]<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=44355Web/Comparison of Happstack, Snap and Yesod2012-02-06T13:58:50Z<p>Dag: /* Happstack */ fixed a typo</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — Happstack is currently maintained by [http://www.n-heptane.com/ Jeremy Shaw (aka stepcut)] with financial support from [http://seereason.com seereason.com]. Significant past (and present) contributors and maintainers include Alex Jacobson, Lemmih, Matthew Elder, Andrea Vezzosi (Saizan), Thomas Hartman, Gracjan Polak, Antoine Latter, Joachim Fasting, Facundo Domínguez, Creighton Hogg, Einar Karttunen, Shae Erisson (shapr), Ian Lynagh, and others.<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group], and the [http://stackoverflow.com/questions/tagged/happstack happstack tag on StackOverflow].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create Hackage 2.0.<br />
* [http://happstack.com/index.html The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
* [http://npaste.de/ npaste.de] Happstack + PostgreSQL pastebin with [https://github.com/mcmaniac/npaste.de src on github]<br />
* [http://substack.net/ Personal site of James Halliday] with [https://github.com/substack/slackstack src on github]<br />
* [https://github.com/rostayob/reskell reskell] a hacker news clone<br />
* [http://noscrolls.com/ noscolls.com] a website for tracking CrossFit workout results<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content. (runs a mixture of Ruby, Happstack, and Snap)<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://patch-tag.com/r/mae/happstack the patch-tag Darcs repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.</div>Daghttps://wiki.haskell.org/index.php?title=Template:Main/News&diff=44132Template:Main/News2012-01-22T20:38:37Z<p>Dag: Updating</p>
<hr />
<div><div class="subtitle">Recent Package Updates [http://haskell.org/haskellwiki/Hackage_statistics http://i.imgur.com/mHvNV.png] [http://hackage.haskell.org/packages/archive/recent.rss http://haskell.org/wikiupload/7/7c/Rss16.png]</div><br />
<br />
<div style="font-size:80%"><br />
;[http://hackage.haskell.org/package/language-javascript-0.4.6 language-javascript 0.4.6]<br />
:Parser for JavaScript<br />
;[http://hackage.haskell.org/package/c0parser-0.1.0.1 c0parser 0.1.0.1]<br />
:Simple C0 Parser<br />
;[http://hackage.haskell.org/package/HStringTemplate-0.6.8 HStringTemplate 0.6.8]<br />
:StringTemplate implementation in Haskell.<br />
;[http://hackage.haskell.org/package/c0check-0.1 c0check 0.1]<br />
:Simple C0 Syntax Check<br />
;[http://hackage.haskell.org/package/HUnit-Diff-0.1 HUnit-Diff 0.1]<br />
:Assertions for HUnit with difference reporting<br />
;[http://hackage.haskell.org/package/aeson-pretty-0.6 aeson-pretty 0.6]<br />
:JSON pretty-printing library and command-line tool.<br />
;[http://hackage.haskell.org/package/newtype-th-0.3.1 newtype-th 0.3.1]<br />
:A template haskell deriver to create Control.Newtype instances.<br />
;[http://hackage.haskell.org/package/theta-functions-1.0.0 theta-functions 1.0.0]<br />
:Theta-functions implemented as trigonometric series<br />
;[http://hackage.haskell.org/package/gtk-toy-0.2.0 gtk-toy 0.2.0]<br />
:Convenient Gtk canvas with mouse and keyboard input.<br />
;[http://hackage.haskell.org/package/highlighting-kate-0.4 highlighting-kate 0.4]<br />
:Syntax highlighting<br />
;[http://hackage.haskell.org/package/hepevt-0.3.1 hepevt 0.3.1]<br />
:HEPEVT parser and writer<br />
;[http://hackage.haskell.org/package/couchdb-conduit-0.3.0.1 couchdb-conduit 0.3.0.1]<br />
:Couch DB client library using http-conduit and aeson<br />
;[http://hackage.haskell.org/package/ircbot-0.2.1 ircbot 0.2.1]<br />
:A library for writing irc bots<br />
;[http://hackage.haskell.org/package/aeson-0.6.0.0 aeson 0.6.0.0]<br />
:Fast JSON parsing and encoding<br />
;[http://hackage.haskell.org/package/criterion-0.6.0.1 criterion 0.6.0.1]<br />
:Robust, reliable performance measurement and analysis<br />
[http://hackage.haskell.org/packages/archive/pkg-list.html More...]<br />
<br />
</div></div>Daghttps://wiki.haskell.org/index.php?title=Template:Main/News&diff=43942Template:Main/News2012-01-14T13:24:29Z<p>Dag: Update</p>
<hr />
<div><div class="subtitle">Recent Package Updates [http://haskell.org/haskellwiki/Hackage_statistics http://i.imgur.com/mHvNV.png] [http://hackage.haskell.org/packages/archive/recent.rss http://haskell.org/wikiupload/7/7c/Rss16.png]</div><br />
<br />
<div style="font-size:80%"><br />
;[http://hackage.haskell.org/package/data-lens-ixset-0.1.1 data-lens-ixset 0.1.1]<br />
:A Lens for IxSet<br />
;[http://hackage.haskell.org/package/streamproc-1.6 streamproc 1.6]<br />
:Stream Processer Arrow<br />
;[http://hackage.haskell.org/package/cabalvchk-0.3 cabalvchk 0.3]<br />
:Verify installed package version against user-specified constraints.<br />
;[http://hackage.haskell.org/package/cabal-progdeps-1.0 cabal-progdeps 1.0]<br />
:Show dependencies of program being built in current directory<br />
;[http://hackage.haskell.org/package/splot-0.3.2 splot 0.3.2]<br />
:A tool for visualizing the lifecycle of many concurrent multi-staged processes.<br />
;[http://hackage.haskell.org/package/couchdb-conduit-0.1.3.0 couchdb-conduit 0.1.3.0]<br />
:Couch DB client library using http-conduit and aeson<br />
;[http://hackage.haskell.org/package/GPX-0.6.1 GPX 0.6.1]<br />
:Parse GPX files<br />
;[http://hackage.haskell.org/package/threadscope-0.2.1 threadscope 0.2.1]<br />
:A graphical tool for profiling parallel Haskell programs.<br />
;[http://hackage.haskell.org/package/ghc-events-0.4.0.0 ghc-events 0.4.0.0]<br />
:Library and tool for parsing .eventlog files from GHC<br />
;[http://hackage.haskell.org/package/cereal-0.3.5.1 cereal 0.3.5.1]<br />
:A binary serialization library<br />
;[http://hackage.haskell.org/package/statistics-0.10.1.0 statistics 0.10.1.0]<br />
:A library of statistical types, data, and functions<br />
;[http://hackage.haskell.org/package/mwc-random-0.11.0.0 mwc-random 0.11.0.0]<br />
:Fast, high quality pseudo random number generation<br />
;[http://hackage.haskell.org/package/math-functions-0.1.1.0 math-functions 0.1.1.0]<br />
:Special functions and Chebyshev polynomials<br />
;[http://hackage.haskell.org/package/llvm-3.0.0.0 llvm 3.0.0.0]<br />
:Bindings to the LLVM compiler toolkit.<br />
;[http://hackage.haskell.org/package/resource-pool-0.2.1.0 resource-pool 0.2.1.0]<br />
:A high-performance striped resource pooling implementation<br />
;[http://hackage.haskell.org/package/llvm-base-3.0.0.0 llvm-base 3.0.0.0]<br />
:FFI bindings to the LLVM compiler toolkit.<br />
;[http://hackage.haskell.org/package/lio-0.1.1 lio 0.1.1]<br />
:Labeled IO Information Flow Control Library<br />
;[http://hackage.haskell.org/package/base64-bytestring-0.1.1.0 base64-bytestring 0.1.1.0]<br />
:Fast base64 encoding and deconding for ByteStrings<br />
[http://hackage.haskell.org/packages/archive/pkg-list.html More...]<br />
</div></div>Daghttps://wiki.haskell.org/index.php?title=IRC_channel&diff=43918IRC channel2012-01-12T16:05:55Z<p>Dag: /* Related channels */ #fedora-haskell</p>
<hr />
<div>Internet Relay Chat is a worldwide text chat service with many thousands<br />
of users among various irc networks.<br />
<br />
The Freenode IRC network hosts the very large #haskell channel, and we've had<br />
up to 884<br />
concurrent users<br />
(average is 787<br />
), making the channel consistently<br />
[http://searchirc.com/search.php?SCHANS=1&SSORT=SIZE&N=freenode one of the largest]<br />
of the thousands of channels on freenode. One famous<br />
resident is [[Lambdabot]], another is [http://hpaste.org hpaste] (see<br />
the [[#Bots|Bots]] section below).<br />
<br />
The IRC channel can be an excellent place to learn more about Haskell,<br />
and to just keep in the loop on new things in the Haskell world. Many<br />
new developments in the Haskell world first appear on the irc channel.<br />
<br />
Since 2009, the Haskell channel has grown large enough that we've split it in two parts:<br />
<br />
* #haskell, for all the usual things<br />
* #haskell-in-depth , for those seeking in depth, or more theoretical discussion<br />
<br />
As always, #haskell remains the primary place for new user questions.<br />
<br />
--------------------------<br />
<br />
[http://haskell.org/sitewiki/images/3/3c/Haskell-current.png [[Image:Haskell-current-small.png|thumb|The #haskell social graph, Jan 2008]]]<br />
<br />
[[Image:Irc-raw.png|thumb|Daily traffic in #haskell since 2004]]<br />
<br />
[[Image:Nick-activity.png|thumb|Growth of #haskell]]<br />
<br />
[[Image:Haskell-wordle-irc.png|thumb|Haskell noun map]]<br />
<br />
== Getting there ==<br />
<br />
If you point your irc client to [irc://chat.freenode.net/haskell chat.freenode.net] and then join the #haskell channel, you'll be there. Alternately, you can try http://java.freenode.net/ or http://webchat.freenode.net/ which connects inside the browser.<br />
<br />
Example, using [http://www.irssi.org/ irssi]:<br />
<br />
$ irssi -c chat.freenode.net -n myname -w mypassword<br />
/join #haskell<br />
<br />
Tip, if you're using Emacs to edit your Haskell sources then why not use it to chat about Haskell? Check out [http://www.emacswiki.org/cgi-bin/wiki/EmacsIRCClient ERC], The Emacs IRC client. Invoke it like this and follow the commands:<br />
<br />
M-x erc-select<br />
...<br />
/join #haskell<br />
<br />
[[Image:Irc--haskell-screenshot.png|frame|A screenshot of an irssi session in #haskell]]<br />
<br />
== Principles ==<br />
<br />
The #haskell channel is a very friendly, welcoming place to hang out,<br />
teach and learn. The goal of #haskell is to encourage learning and<br />
discussion of Haskell, functional programming, and programming in<br />
general. As part of this we welcome newbies, and encourage teaching of<br />
the language.<br />
<br />
Part of the #haskell success comes from the approach that the community<br />
is quite tight knit -- we know each other -- it's not just a homework<br />
channel. As a result, many collaborative projects have arisen between<br />
Haskell irc channel citizens.<br />
<br />
To maintain the friendly, open culture, the following is required:<br />
<br />
* Low to zero tolerance for ridiculing questions. Insulting new users is unacceptable.<br />
<br />
New Haskell users should feel entirely comfortable asking new questions.<br />
Helpful answers should be encouraged with <hask>name++</hask> karma<br />
points, in public, as a reward for providing a good answer.<br />
<br />
As the channel grows, we see a diverse range of people, with different<br />
programming backgrounds, trying to make their way with Haskell. A good<br />
rule of thumb, to avoid frustration is:<br />
<br />
* approach negative comments by asking for details (kind of like [http://en.wikipedia.org/wiki/Socratic_method Socratic questioning]), rather than challenging the competence of the writer (ad hominem).<br />
<br />
<br />
== History ==<br />
<br />
The #haskell channel appeared in the late 90s, and really got going<br />
in early 2001, with the help of Shae Erisson (aka shapr).<br />
<br />
A fairly extensive analysis of the traffic on #haskell over the years is<br />
[http://www.cse.unsw.edu.au/~dons/irc/ kept here]<br />
<br />
== Related channels ==<br />
<br />
In addition to the main Haskell channel there are also:<br />
<br />
{| border="1" cellspacing="0" cellpadding="5" align="center"<br />
! Channel<br />
! Purpose<br />
|-<br />
| #haskell-br<br />
| Brazilian Portuguese (pt_BR) speakers<br />
|-<br />
| #haskell.cz<br />
| Czech speakers (UTF-8)<br />
|- <br />
| #haskell.de<br />
| German speakers<br />
|-<br />
| #haskell.dut<br />
| Dutch speakers<br />
|-<br />
| #haskell.es<br />
| Spanish speakers<br />
|-<br />
| #haskell.fi<br />
| Finnish speakers<br />
|-<br />
| #haskell-fr (note the hyphen!)<br />
| French speakers <br />
|-<br />
| #haskell.hr<br />
| Croatian speakers<br />
|-<br />
| #haskell.it <br />
| Italian speakers<br />
|-<br />
| #haskell.jp <br />
| Japanese speakers<br />
|-<br />
| #haskell.no <br />
| Norwegian speakers<br />
|-<br />
| #haskell.pt<br />
| Portuguese speakers<br />
|-<br />
| #haskell.ru <br />
| Russian speakers. Seems that most of them migrated to Jabber conference (haskell@conference.jabber.ru).<br />
|-<br />
| #haskell_ru <br />
| Russian speakers again, in UTF-8. For those, who prefer good ol' IRC channel with a lambdabot.<br />
|-<br />
| #haskell.se <br />
| Swedish speakers<br />
|-<br />
| #haskell-blah <br />
| Haskell people talking about anything except Haskell itself<br />
|-<br />
| #haskell-books <br />
| Authors organizing the collaborative writing of the [http://en.wikibooks.org/wiki/Haskell Haskell wikibook] and other books or tutorials.<br />
|-<br />
| #haskell-game<br />
| The hub for Haskell-based [[Game Development|game development]]<br />
|-<br />
| #haskell-in-depth<br />
| slower paced discussion of use, theory, implementation etc with no monad tutorials!<br />
|-<br />
| #haskell-iphone<br />
| Haskell-based [[iPhone]] development<br />
|-<br />
| #haskell-overflow<br />
| Overflow conversations<br />
|-<br />
| #haskell-web<br />
| Friendly, practical discussion of haskell web app/framework/server development<br />
|-<br />
| '''Platform-specific:'''<br />
|<br />
|-<br />
| #arch-haskell <br />
| [[Arch Linux]]/ specific Haskell conversations<br />
|-<br />
| #fedora-haskell<br />
| [[Fedora]] Haskell SIG<br />
|-<br />
| #gentoo-haskell <br />
| [[Gentoo]]/Linux specific Haskell conversations<br />
|-<br />
| '''Projects using haskell:'''<br />
|<br />
|-<br />
| #darcs <br />
| [[Darcs]] revision control system<br />
|-<br />
| #hackage<br />
| Haskell's software distribution infrastructure<br />
|-<br />
| #happs<br />
| [http://happstack.com Happstack] web framework<br />
|-<br />
| #hledger<br />
| [http://hledger.org hledger] accounting tools and library<br />
|-<br />
| #leksah<br />
| [http://leksah.org Leksah] IDE for Haskell development<br />
|-<br />
| #perl6 <br />
| [http://www.pugscode.org Perl 6] development (plenty of Haskell chat there too)<br />
|-<br />
| #snapframework<br />
| [http://snapframework.com/ Snap] web framework<br />
|-<br />
| #xmonad<br />
| [http://xmonad.org Xmonad] tiling window manager<br />
|}<br />
<br />
== Logs ==<br />
<br />
'''Logs''' are kept at http://tunes.org/~nef/logs/haskell/<br />
<br />
<!-- anywhere else? ircbrowse.com is a goner, apparently --><br />
<br />
== Bots ==<br />
<br />
There are various bots on the channel. Their names and usage are described here.<br />
<br />
=== lambdabot ===<br />
<br />
[[Lambdabot]] is both the name of a software package and a bot on the channel. It provides many useful services for visitors to the IRC channel. It is available as a haskell package and can be integrated into ghci. Details on the software are found on a [[Lambdabot|separate wiki page]].<br />
<br />
Here is its interface for the IRC user:<br />
<br />
lambdabot's commands are prepended by a '@' sign.<br />
<br />
{| border="1" cellspacing="0" cellpadding="5" align="center"<br />
! Command<br />
! Usage<br />
|-<br />
| @help<br />
| display help to other commands, but help text is not available for all commands.<br />
|-<br />
| @type EXPR or ':t' EXPR<br />
| shows the type of an expression<br />
|-<br />
| @kind TYPECONSTRUCTOR<br />
| shows the kind of a type constructor<br />
|-<br />
| @run EXPR or '>' EXPR<br />
| evaluates EXPR<br />
|-<br />
| @pl FUNCTION<br />
| shows a [[pointfree]] version of FUNCTION<br />
|-<br />
| @pointful FUNCTION or '@unpl' FUNCTION<br />
| shows a 'pointful' version of FUNCTION<br />
|}<br />
<br />
=== preflex ===<br />
<br />
is the name of a lambdabot with more commands/plugins enabled. It is run by ?? To talk to preflex, write <tt>preflex: command ARGS</tt><br />
<br />
{| border="1" cellspacing="0" cellpadding="5" align="center"<br />
! Command<br />
! Usage<br />
|-<br />
| help COMMAND<br />
| displays help to other commands.<br />
|-<br />
| list<br />
| lists all plugins with their commands<br />
|-<br />
| NICK++ / NICK--<br />
| in/decrements the karma of NICK.<br />
|-<br />
| karma NICK<br />
| shows the karma of NICK<br />
|-<br />
| seen NICK<br />
| shows information about the last message of a user<br />
|-<br />
| tell / ask<br />
| sends NICK MSG a message when she becomes active.<br />
|-<br />
| xseen<br />
| ''see 'seen' ?? any difference ?''<br />
|-<br />
| quote NICK<br />
| prints a random quote of NICK<br />
|-<br />
| remember NAME QUOTE<br />
| associates NAME with quote. can be accessed by 'quote'<br />
|-<br />
| ...<br />
| ...<br />
|}<br />
<br />
=== hpaste ===<br />
The hpaste bot provides a notification interface to the [http://hpaste.org hpaste pastebin]. [[Hpaste.el|Emacs integration]] is available.<br />
<br />
''Usage?''<br />
<br />
''Not online often !? ''<br />
<br />
=== hackage ===<br />
The hackage bot provides real-time notifications of new package uploads to [http://hackage.haskell.org Hackage].<br />
<br />
== Locations ==<br />
<br />
To get an overview of where everybody on the channel might<br />
be, physically, please visit [[Haskell user locations]].<br />
<br />
<br />
[[Category:Community]]</div>Daghttps://wiki.haskell.org/index.php?title=Web/Comparison_of_Happstack,_Snap_and_Yesod&diff=43913Web/Comparison of Happstack, Snap and Yesod2012-01-11T22:12:03Z<p>Dag: /* Happstack */ Adding patch-tag</p>
<hr />
<div>'''Note''': Work in progress. I will outline planned sections in headings momentarily.<br />
<br />
There is no existing complete comparison of Happstack, Snap and Yesod. Such a thing helps people to choose and feel they've made a well-founded decision.<br />
<br />
== The home page ==<br />
<br />
I'll start with the web sites at first impression.<br />
<br />
* [http://happstack.com/index.html Happstack's web site] is simple and clean.<br />
* [http://snapframework.com/ Snap's web site] is pretty and professionally designed.<br />
* [http://www.yesodweb.com/ Yesod's web site] is okay, good links.<br />
<br />
== Maintainers ==<br />
<br />
Next, the main maintainers of the projects is handy to know:<br />
<br />
* Happstack — There is no link on the homepage about maintainers, but I garnered [http://www.n-heptane.com/ Jeremy Shaw], (Figured out from [http://www.haskellers.com/user/52 here], “Maintainer of Happstack, the Haskell web application framework: <http://www.happstack.com/>”) aka stepcut. I can't tell if there are any more maintainers, [http://patch-tag.com/r/mae/happstack/snapshots/all/history the darcs history] doesn't show any major contributors. A list of contributors, I suppose, can be seen [http://patch-tag.com/r/mae/happstack/home on the patch-tag homepage], I'm not going to bother trying to convert usernames to real names. (Lemmih, Saizan, alexjacobson, creighton, mightybyte, stepcut, tphyahoo.)<br />
* Snap — Many are listed as ‘contributors’ on [http://snapframework.com/about the about page], but [http://gregorycollins.net/ Gregory Collins] and [http://softwaresimply.blogspot.com/ Doug Beardsley] are certainly maintainers, the rest I'm not sure, may be just contributors; ([http://rfrn.org/~shu Shu-yu Guo], [http://james-sanders.com/ James Sanders], Carl Howells, Shane O'Brien, [http://github.com/ozataman Ozgun Ataman], [http://github.com/cdsmith Chris Smith], [https://github.com/norm2782 Jurriën Stutterheim].) the site doesn't distinguish.<br />
* Yesod — [http://www.snoyman.com/ Michael Snoyman], [http://blog.gregweber.info/ Greg Weber], (Garnered from [http://www.yesodweb.com/page/contributors the contributors page], via Community.) there are other contributors listed, some of which might be maintainers. (Felipe Lessa, [http://pbrisbin.com/ Patrick Brisbin], [https://github.com/luite Luite Stegeman], [http://konn.x0.com/ Hiromi ISHII], [http://www.mew.org/~kazu/ Kazu Yamamoto]. See the page for past contributors.)<br />
<br />
== Communities ==<br />
<br />
* Happstack — Garnered from [http://happstack.com/community the Community page], [http://groups.google.com/group/HAppS the HappS mailing list], #happs on Freenode IRC, [http://happstack.com/irc-logs/ with IRC logs], [http://code.google.com/p/happstack/issues/list Google Code] for issue tracking, [http://code.google.com/p/happstack/w/list a wiki], [http://www.twitter.com/happstack Twitter], a [http://www.facebook.com/happstack Facebook group].<br />
* Snap — Garnered from the [http://snapframework.com/about About page], [http://mailman-mail5.webfaction.com/listinfo/snap the Snap mailing list] #snapframework on Freenode IRC, [https://github.com/snapframework/snap-core/issues Github] for issue tracking.<br />
* Yesod — Garnered from the [http://www.yesodweb.com/page/community Community Resources], [http://stackoverflow.com/questions/tagged/yesod StackOverflow], a [http://groups.google.com/group/yesodweb?pli=1 Google Group], [http://www.haskell.org/mailman/listinfo/web-devel the web-devel mailing list], (Which, due to the large proportion of Yesod-related questions, has essentially become ‘yesod-devel’.) #yesod on Freenode IRC, [https://github.com/yesodweb/yesod/issues Github] for issue tracking, a [http://www.yesodweb.com/wiki wiki] for posting documentation.<br />
<br />
== Documentation ==<br />
<br />
There is roughly the same set of documentation for each, varying in side and detail, with a quickstart for each, more complete tutorials, and haddock API documentation.<br />
<br />
* Happstack — [http://happstack.com/docs/happstack-lite/happstack-lite.html A small tutorial] covering writing a simple program, a larger [http://happstack.com/docs/crashcourse/index.html crash course] cover routing, templating, request handling, static files and database state, and examples. And [http://happstack.com/docs/6.0.0/index.html haddock docs.]<br />
* Snap — [http://snapframework.com/docs/quickstart A simple quickstart guide], a [http://snapframework.com/docs/tutorials/snap-api slightly larger tutorial similar to happstack's], a [http://snapframework.com/docs/tutorials/snaplets-tutorial tutorial on snaplets (Snap's means of extension)], a tutorial on [http://snapframework.com/docs/tutorials/heist/ heist (Snap's templating)] and [http://hackage.haskell.org/packages/archive/snap/0.7/doc/html/Snap.html haddock docs].<br />
* Yesod — a [http://www.yesodweb.com/page/five-minutes simple quickstart guide similar to Snap's], [http://www.yesodweb.com/page/screencasts screencasts], an online [http://www.yesodweb.com/book book] similar to Happstack's crash course, covering templates, widgets, routing, forms, sessions, databases, deployment, authentication, scaffolding, internationalisation, and examples. And [http://www.yesodweb.com/wiki/API%20Documentation haddock docs].<br />
<br />
== Use Cases ==<br />
<br />
It's interesting to know who is using these frameworks.<br />
<br />
=== Happstack ===<br />
<br />
* [http://cogracenotes.wordpress.com/2010/08/08/hackage-on-sparky/ Matt Gruen] used Happstack to create Hackage 2.0.<br />
* [http://happstack.com/index.html The Happstack homepage] is written with Happstack.<br />
* [http://www.creativeprompts.com/ Creative Prompts] — A site for exchanging story ideas -- which was developed but never got around to promoting.<br />
* [http://www.seereason.com See Reason] — A site which allows you to construct and prove arguments using first order logic. This site is in public beta.<br />
* [http://src.seereason.com/examples/happstack-imageboard/ A (4chan clone) image board] (not running anywhere).<br />
* [https://github.com/jgm/gitit Gitit] is a Happstack wiki app.<br />
* [http://patch-tag.com/r/tphyahoo/patch-tag-public/home Patch-Tag] provides hosting for Darcs repositories and Gitit wikis.<br />
<br />
=== Snap ===<br />
<br />
* [http://hpaste.org/ hpaste] — the Haskell pastebin.<br />
* [http://darcsden.com/alex/darcsden Darcs Den] — a place to share your darcs projects and collaborate with others.<br />
* [http://housetab.org/ housetab.org] — a webapp for sharing expenses (source code here)<br />
* [https://github.com/norm2782/JCU JCU] — a web-based Prolog environment.<br />
* [https://github.com/Palmik/snap-pastie snap-pastie] another pastebin.<br />
* [http://snapframework.com snapframework.com] the Snap home page.<br />
* [http://www.silkapp.com/ Silk] — a new way to create and consume content.<br />
* [http://www.karamaan.com Karamaan Group] — uses Snap for an internal company intranet.<br />
<br />
=== Yesod ===<br />
<br />
* Haskellers uses Yesod: https://github.com/snoyberg/haskellers<br />
* [http://braincrater.wordpress.com/2010/07/22/ajax-chat-app-using-yesod/2 Braden Shepherdson] made an AJAX chat application using Yesod.<br />
* [http://flygdynamikern.blogspot.com/2011/06/toy-url-shortener-with-yesod-and-acid.html Björn Buckwalter] made a URL shortener using Yesod.<br />
* [http://blog.foldr.in/tkyprof-a-web-based-interactive-visualizer-fo TKYProf] — a ghc profiling visualizer<br />
* [http://www.orangeroster.com/ Orange Roster] — Open source, privacy-centric shared address book.<br />
* [http://demo.hledger.org/ hledger-web] — The web interface for the hledger accounting tool.<br />
* [http://www.urbanlisting.co.za/ Urban Listings] — A free listing website for the South African property market.<br />
* [http://luach.snoyman.com/ Luach] — English and Hebrew anniversary reminders.<br />
* [http://www.haskellers.com/ Haskellers] — Professional network of Haskell programmers.<br />
* [http://packdeps.haskellers.com/ packdeps] — Track outdated Hackage dependencies.<br />
* [http://hackage.haskell.org/package/yackage yackage] — A personal Hackage serving for testing new packages.<br />
* [https://github.com/cutsea110/Kestrel Kestrel] — A Wiki clone. This site has been published as a home customized to a university department ([http://soubun.seitoku.ac.jp Seitoku University Junior College]).<br />
* [http://pirates.dyndns-free.com/ Buccaneer Battle] — A multi-player game in the browser: as the captain of a pirate ship, try to sink your opponent!<br />
* [http://pbrisbin.com/ Personal site of Patrick Brisbin] — might be of interest for those wanting to create a blog.<br />
* [http://meadowstalk.com/post/new-blog Personal site of Blake Rain] <br />
* [https://www.pascal-wittmann.de/ Personal site of Pascal Wittmann]<br />
<br />
== Repositories and Installation ==<br />
<br />
I am running Ubuntu 10.04.<br />
<br />
=== Happstack ===<br />
<br />
Installed from the <tt>happstack</tt> package from Hackage, or can be retrieved via [http://patch-tag.com/r/mae/happstack the patch-tag Darcs repository.] Info from [http://happstack.com/download the Download page].<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install happstack<br />
…<br />
Registering happstack-6.0.5...<br />
<br />
real 2m13.240s<br />
user 1m38.886s<br />
sys 0m7.588s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Snap ===<br />
<br />
The [http://snapframework.com/download web site Download page] advises to install the <tt>snap</tt> package from Hackage:<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ cabal-dev install snap<br />
…<br />
Registering snap-0.7...<br />
<br />
real 5m1.105s<br />
user 4m24.369s<br />
sys 0m15.389s</pre><br />
Installs fine in GHC 6.12.3 in a couple of minutes.<br />
<br />
=== Yesod ===<br />
<br />
The web site advises to install the <tt>yesod</tt> package from Hackage.<br />
<br />
<pre>$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 6.12.3<br />
$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library <br />
$ time cabal-dev install yesod<br />
Resolving dependencies...<br />
cabal: cannot configure conduit-0.0.1.1. It requires base &gt;=4.3 &amp;&amp;<br />
&lt;5 For the dependency on base &gt;=4.3 &amp;&amp; &lt;5 there are these<br />
packages: base-4.3.0.0, base-4.3.1.0, base-4.4.0.0 and<br />
base-4.4.1.0. However none of them are available.</pre><br />
This was anticipated in the documentation, (“If you want to install yesod painlessly, get ghc &gt;= 7.” from [http://www.yesodweb.com/wiki/install-help the install help wiki page.]<br />
) so the behaviour is expected.<br />
<br />
<pre>chris@cn-done:~/yesod$ export PATH=/opt/ghc/7.0.4/bin/:$PATH<br />
chris@cn-done:~/yesod$ ghc --version<br />
The Glorious Glasgow Haskell Compilation System, version 7.0.4<br />
chris@cn-done:~/yesod$ cabal install Cabal cabal-install<br />
--bindir=/opt/ghc/7.0.4/bin<br />
…<br />
Linking dist/build/cabal/cabal ...<br />
Installing executable(s) in /opt/ghc/7.0.4/bin<br />
chris@cn-done:~/yesod$ cabal --version<br />
cabal-install version 0.10.2<br />
using version 1.10.2.0 of the Cabal library </pre><br />
So I'm now on 7.0.4 with the latest cabal installed for 7.0.4. Proceeding should work:<br />
<br />
<pre>$ time cabal-dev install yesod<br />
…<br />
Registering yesod-0.9.4.1...<br />
<br />
real 8m55.781s<br />
user 7m2.446s<br />
sys 0m21.809s</pre><br />
Installs with no problems as the guide suggests.</div>Daghttps://wiki.haskell.org/index.php?title=Web/Frameworks&diff=43895Web/Frameworks2012-01-11T20:02:16Z<p>Dag: /* Happstack */ fix darcs link</p>
<hr />
<div>[[Category:Web|*]]<br />
{{Web infobox}}<br />
<br />
Content from [[Web]] should be merged here.<br />
<br />
Below is a list of known to be active Haskell web frameworks. Rather than one framework to rule them all, Haskell provides several options. You can view the [[Web/Deploy]] page to get an idea of how you might deploy an application written in some of these frameworks.<br />
<br />
See also: there are also many [[Web/Frameworks/Inactive|inactive web frameworks]] to draw inspiration from<br />
<br />
== Happstack ==<br />
<br />
Happstack is a Haskell web framework. Happstack is designed so that developers can prototype quickly, deploy painlessly, scale massively, operate reliably, and change easily. It supports GNU/Linux, OS X, FreeBSD, and Windows environments.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author:<br />
| Happstack team, HAppS LLC<br />
|-<br />
! Maintainer:<br />
| Happstack team <happs@googlegroups.com><br />
|-<br />
! Home page:<br />
| http://happstack.com/index.html<br />
|-<br />
! Documentation:<br />
| http://happstack.com/docs<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/happstack Hackage] - [http://patch-tag.com/r/mae/happstack Darcs]<br />
|}<br />
<br />
<br />
[http://happstack.com/index.html Happstack] is a complete web framework. It is organized as a suite of libraries including: <br />
* happstack-server: an integrated HTTP server, routing combinators, fileserving, etc<br />
* happstack-data: datatype serialization and migration support<br />
* happstack-state (aka macid): an (optional) powerful NoSQL ACID storage system with native support for Haskell types and replication<br />
<br />
It also includes integration with many 3rd party libraries including:<br />
<br />
*templating: [http://hackage.haskell.org/package/blaze-html Blaze HTML combinator library], [http://docs.yesodweb.com/ Hamlet], [[HSP]], [[HStringTemplate]], [[Heist]], and more<br />
*forms: [[Formlets]]<br />
*routing: [http://hackage.haskell.org/package/web-routes web-routes] type-safe urls and routing<br />
*databases: can be used with most [[Database interfaces]] with no special support required<br />
<br />
Happstack is primarily intended for use on VPS or dedicated hosts, but can be used with CGI via FastCGI or [http://hackage.haskell.org/package/hack-handler-happstack-2009.12.20 hack].<br />
<br />
See the [http://happstack.com/index.html Happstack Home Page] for more information and to learn how to get support via IRC and mailing lists.<br />
<br />
== Snap ==<br />
<br />
Snap is a simple web development framework for unix systems, written in the Haskell programming language.<br />
<br />
Snap is well-documented and has a test suite with a high level of code coverage, but it is early-stage software with still-evolving interfaces. Snap is therefore likely to be most appropriate for early adopters and potential contributors.<br />
<br />
* A fast HTTP server library with an optional high-concurrency backend using the libev event loop library<br />
* A sensible and clean monad for web programming<br />
* An XML-based templating system for generating HTML<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| James Sanders, Gregory Collins, Doug Beardsley<br />
|-<br />
! Maintainer:<br />
| snap@snapframework.com<br />
|-<br />
! Home page:<br />
| http://snapframework.com/<br />
|-<br />
! Documentation:<br />
| http://snapframework.com/docs<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/snap-server Hackage] - [http://git.snapframework.com/snap-server.git Git]<br />
|}<br />
<br />
== Yesod ==<br />
<br />
Yesod is designed for RESTful, type-safe, performant web apps. By leveraging quasi-quotation for the more boilerplate tasks, we get concise web apps with high levels of type safety. Its Hamlet templates are compile-time checked for correctness, and the controller (web-routes-quasi) uses type-safe URLs to make certain you are only generating valid URLs. It loosely follows Model/View/Controller principles.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Maintainer:<br />
| Michael Snoyman <michael@snoyman.com><br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074271.html<br />
|-<br />
! Home page:<br />
| http://docs.yesodweb.com/<br />
|-<br />
! Documentation:<br />
| http://docs.yesodweb.com/yesod/<br />
|-<br />
! Screencast:<br />
| http://www.youtube.com/watch?v=BEWJnDgrmp0<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/yesod Hackage] - [http://github.com/snoyberg/yesod Github]<br />
|}<br />
<br />
[http://docs.yesodweb.com/ Yesod] is a full-featured web framework. It takes a modular approach to development, so many parts of the framework such as [http://docs.yesodweb.com/book/templates Hamlet] and [http://docs.yesodweb.com/book/persistent Persistent] are available as standalone packages. However, put together, Yesod provides you with solutions for templating, routing, persistence, sessions, JSON, authentication/authorization, and more. Yesod's major guiding principle is type safety: if your application compiles, it works.<br />
<br />
Yesod is very well documented through the [http://docs.yesodweb.com/book Yesod book]. Work is being done on an constant basis to improve the documentation status, but the first ten chapters (covering all the basics) are already done, so it should be easy to get started.<br />
<br />
Yesod is built on [http://hackage.haskell.org/package/wai WAI], or the Web Application Interface. This is similar to WSGI in Python or Rack in Ruby. It provides a single interface that all applications can target and work on multiple backends. Backends exist for CGI, FastCGI, SCGI, development server (auto-recompile) and even a Webkit-powered desktop version.<br />
<br />
But the premier backend is [http://hackage.haskell.org/package/warp Warp]: a very simple web server which, at the time of writing, is the fastest Haskell has to offer. You can read more in its [http://docs.yesodweb.com/blog/announcing-warp release announcement] and see some [http://docs.yesodweb.com/blog/warp-speed-ahead followup benchmarks]. Warp is already powering Yesod; some other major players that are planning a move are Hoogle and Happstack.<br />
<br />
You can see a [http://wiki.yesodweb.com/Powered%20by%20Yesod list of Yesod-powered sites and packages], or check out the [https://github.com/snoyberg/haskellers source code for Haskellers]. Most discussions for Yesod take place on the [http://groups.google.com/group/yesodweb yesodweb list], so feel free to join in and ask any questions you have, the Yesod community is very beginner-friendly.<br />
<br />
== Haskell on a Horse ==<br />
<br />
Haskell on a Horse (HoH) is a combinatorial web framework for the programming language Haskell. It is currently at an early, unsettled stage of development. It is available under the "BSD3" open-source license.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Jason Hart Priestley<br />
|-<br />
! Maintainer<br />
| jason@on-a-horse.org<br />
|-<br />
! Home page:<br />
| http://haskell.on-a-horse.org/<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/on-a-horse Hackage]<br />
|}<br />
<br />
== miku ==<br />
<br />
A simple library for fast web prototyping in Haskell, inspired by Ruby's Rack and Sinatra.<br />
<br />
{| class="wikitable"<br />
! License<br />
| BSD3<br />
|-<br />
! Author<br />
| Wang, Jinjing<br />
|-<br />
! Maintainer<br />
| Wang, Jinjing <nfjinjing@gmail.com><br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/miku Hackage] - [http://github.com/nfjinjing/miku Github]<br />
|}<br />
<br />
== Lemmachine ==<br />
<br />
Lemmachine is a REST'ful web framework that makes it easy to get HTTP right by exposing users to overridable hooks with sane defaults. The main architecture is a copy of Erlang-based Webmachine, which is currently the best documentation reference (for hooks & general design).<br />
<br />
Lemmachine stands out from the dynamically typed Webmachine by being written in dependently typed Agda. The goal of the project is to show the advantages gained from compositional testing by taking advantage of proofs being inherently compositional. See proofs for examples of universally quantified proofs (tests over all possible input values) written against the default resource, which does not override any hooks.<br />
<br />
[http://github.com/larrytheliquid/Lemmachine#readme More information]<br />
<br />
{| class="wikitable"<br />
! Author<br />
| Larry Diehl<br />
|-<br />
! Packages & repositories<br />
| [http://github.com/larrytheliquid/Lemmachine Github]<br />
|}<br />
<br />
== mohws ==<br />
<br />
A web server with a module system and support for CGI. Based on Simon Marlow's original Haskell Web Server.<br />
<br />
{| class="wikitable"<br />
!License:<br />
|BSD3<br />
|-<br />
!Copyright:<br />
|Simon Marlow, Bjorn Bringert<br />
|-<br />
!Author:<br />
|Simon Marlow, Bjorn Bringert <bjorn@bringert.net><br />
|-<br />
!Maintainer:<br />
|Henning Thielemann <webserver@henning-thielemann.de><br />
|-<br />
!Packages & repositories<br />
|[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/mohws Hackage] - [http://code.haskell.org/mohws/ Darcs]<br />
|}<br />
<br />
== Salvia ==<br />
<br />
Salvia is a feature rich modular web server and web application framework that can be used to write dynamic websites in Haskell. From the lower level protocol code up to the high level application code, everything is written as a Salvia handler. This approach makes the server extremely extensible. To see a demo of a Salvia website, please see the salvia-demo package.<br />
<br />
All the low level protocol code can be found in the salvia-protocol package, which exposes the datatypes, parsers and pretty-printers for the URI, HTTP, Cookie and MIME protocols.<br />
<br />
This Salvia package itself can be separated into three different parts: the interface, the handlers and the implementation. The interface module defines a number of type classes that the user can build the web application against. Reading the request object, writing to the response, or gaining direct access to the socket, all of these actions are reflected using one type class aspect in the interface. The handlers are self contained modules that implement a single aspect of the Salvia web server. The handlers expose their interface requirements in their type context. Salvia can have multiple implementations which can be switched by using different instances for the interface type classes. This package has only one implementation, a simple accepting socket loop server. The salvia-extras package has two additional implementations. Keeping a clear distinction between the abstract server aspects and the actual implementation makes it very easy to migrate existing web application to different back-ends.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Sebastiaan Visser<br />
|-<br />
! Maintainer:<br />
| sfvisser@cs.uu.nl<br />
|-<br />
! Announcement:<br />
| http://www.haskell.org/pipermail/haskell-cafe/2010-March/074870.html<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/salvia Hackage] - [http://github.com/sebastiaanvisser/salvia Git]<br />
|}<br />
<br />
== Scotty ==<br />
<br />
A Haskell web framework inspired by Ruby's Sinatra, using WAI and Warp. Sinatra + Warp = Scotty.<br />
<br />
Scotty is the cheap and cheerful way to write RESTful, declarative web applications.<br />
<br />
* A page is as simple as defining the verb, url pattern, and Text content.<br />
* It is template-language agnostic. Anything that returns a Text value will do.<br />
* Conforms to WAI Application interface.<br />
* Uses very fast Warp webserver by default.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Andrew Farmer<br />
|-<br />
! Maintainer:<br />
| Andrew Farmer<br />
|-<br />
! Home page:<br />
| http://ittc.ku.edu/csdl/fpg/Tools/Scotty<br />
|-<br />
! Documentation:<br />
| http://hackage.haskell.org/package/scotty<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/scotty Hackage] - [https://github.com/xich/scotty Git]<br />
|}<br />
<br />
==See also==<br />
<br />
* [[Web/Framework survey]]</div>Daghttps://wiki.haskell.org/index.php?title=Template:Main/News&diff=43835Template:Main/News2012-01-05T17:13:55Z<p>Dag: Selfishly updating</p>
<hr />
<div><div class="subtitle">Recent Package Updates [http://haskell.org/haskellwiki/Hackage_statistics http://i.imgur.com/mHvNV.png] [http://hackage.haskell.org/packages/archive/recent.rss http://haskell.org/wikiupload/7/7c/Rss16.png]</div><br />
<br />
<div style="font-size:80%"><br />
;[http://hackage.haskell.org/package/data-lens-ixset-0.1.0 data-lens-ixset 0.1.0]<br />
:A Lens for IxSet<br />
;[http://hackage.haskell.org/package/wx-0.13.2 wx 0.13.2]<br />
:wxHaskell<br />
;[http://hackage.haskell.org/package/wxcore-0.13.2 wxcore 0.13.2]<br />
:wxHaskell core<br />
;[http://hackage.haskell.org/package/wxdirect-0.13.1 wxdirect 0.13.1]<br />
:helper tool for building wxHaskell<br />
;[http://hackage.haskell.org/package/IntervalMap-0.2.2 IntervalMap 0.2.2]<br />
:Maps from Intervals to values, with efficient search.<br />
;[http://hackage.haskell.org/package/monadiccp-0.7.2 monadiccp 0.7.2]<br />
:Constraint Programming<br />
;[http://hackage.haskell.org/package/paragon-0.1.7 paragon 0.1.7]<br />
:Paragon<br />
;[http://hackage.haskell.org/package/uAgda-1.2.0.0 uAgda 1.2.0.0]<br />
:A simplistic dependently-typed language with parametricity.<br />
;[http://hackage.haskell.org/package/unix-compat-0.3.0.1 unix-compat 0.3.0.1]<br />
:Portable POSIX-compatibility layer.<br />
;[http://hackage.haskell.org/package/cmdargs-0.9.1 cmdargs 0.9.1]<br />
:Command line argument processing<br />
;[http://hackage.haskell.org/package/http-proxy-0.0.5 http-proxy 0.0.5]<br />
:A library for writing HTTP and HTTPS proxies<br />
;[http://hackage.haskell.org/package/http-enumerator-0.7.2.3 http-enumerator 0.7.2.3]<br />
:HTTP client package with enumerator interface and HTTPS support.<br />
;[http://hackage.haskell.org/package/iteratee-0.8.7.6 iteratee 0.8.7.6]<br />
:Iteratee-based I/O<br />
;[http://hackage.haskell.org/package/haskell-src-exts-qq-0.6.0 haskell-src-exts-qq 0.6.0]<br />
:A quasiquoter for haskell-src-exts.<br />
;[http://hackage.haskell.org/package/yesod-core-0.9.4.1 yesod-core 0.9.4.1]<br />
:Creation of type-safe, RESTful web applications.<br />
;[http://hackage.haskell.org/package/scalable-server-0.2.2 scalable-server 0.2.2]<br />
:Library for writing fast/scalable TCP-based services<br />
;[http://hackage.haskell.org/package/websockets-snap-0.5.0.0 websockets-snap 0.5.0.0]<br />
:Snap integration for the websockets library<br />
;[http://hackage.haskell.org/package/xml-catalog-0.5.0 xml-catalog 0.5.0]<br />
:Parse XML catalog files<br />
;[http://hackage.haskell.org/package/copilot-2.0.4 copilot 2.0.4]<br />
:A stream DSL for writing embedded C programs.<br />
;[http://hackage.haskell.org/package/persistent-postgresql-0.6.1.3 persistent-postgresql 0.6.1.3]<br />
:Backend for the persistent library using postgresql.<br />
[http://hackage.haskell.org/packages/archive/pkg-list.html More...]<br />
</div></div>Daghttps://wiki.haskell.org/index.php?title=User_talk:Dag&diff=43711User talk:Dag2011-12-21T18:15:26Z<p>Dag: /* Spam */</p>
<hr />
<div>Hi Dag,<br />
<br />
Can we just revert all of the &lt;hask&gt; tags in the Typeclassopedia? I'm glad we did the experiment, but the formatting is messed up in a lot of places, and the syntax highlighting simply looks bad because it's inconsistent (see e.g. the highighting of Monad vs. Applicative, the highlighting of &&&, etc.).<br />
<br />
--[[User:Byorgey|Byorgey]] 01:44, 27 November 2011 (UTC)<br />
<br />
:Agreed, done. --[[User:Dag|Dag]] 01:52, 27 November 2011 (UTC)<br />
<br />
::Thanks. I had wondered about using &lt;hask&gt; tags; now we know. =) I added a note to the [[Talk:Typeclassopedia|talk page]] recording the reasons for having things the way they are, for the benefit of future editors. --[[User:Byorgey|Byorgey]] 01:57, 27 November 2011 (UTC)<br />
<br />
== Spam ==<br />
<br />
I know you are trying to help, but moving stuff around actually makes it more difficult for me. --[[User:Gwern|Gwern]] 16:59, 21 December 2011 (UTC)<br />
<br />
:Noted. --[[User:Dag|dag]] 18:15, 21 December 2011 (UTC)</div>Daghttps://wiki.haskell.org/index.php?title=Template:Main/Headlines&diff=43702Template:Main/Headlines2011-12-21T15:07:42Z<p>Dag: New Platform</p>
<hr />
<div><div class="subtitle">Headlines</div><br />
<br />
* ''2011:''<br />
** The '''[http://haskell.org/platform Haskell Platform 2011.4]''' is now available<br />
** A [http://www.cs.nott.ac.uk/~gmh/phd-advert.html Fully-Funded PhD Studentship in Functional Programming] is available from July 2011<br />
** The [http://www.well-typed.com/blog/53 Parallel Haskell Digest] is out, with 2011 news about Haskell and parallelism<br />
** Joyride Laboratories releases '''[http://joyridelabs.de/ Nikki and the Robots]''', an independent 2D game written in Haskell <br />
** '''[http://learnyouahaskell.com/ Learn You a Haskell]''', the fun, fast Haskell introduction, is now available as a book<br />
** [http://www.yesodweb.com/blog/warp-speed-ahead Warp Speed Ahead!] The '''[http://www.yesodweb.com/ Yesod web framework]''' matures and shows its speed.<br />
<br />
* ''2010:''<br />
** [http://blog.johantibell.com/2010/08/results-from-state-of-haskell-2010.html The State of Haskell Report], 2010 edition.<br />
** Try the new [http://snapframework.com/ Snap web framework] for Haskell -- fast, simple, easy.</div>Daghttps://wiki.haskell.org/index.php?title=Template:Main/News&diff=43701Template:Main/News2011-12-21T15:03:13Z<p>Dag: Updating (someone automate this!)</p>
<hr />
<div><div class="subtitle">Recent Package Updates [http://haskell.org/haskellwiki/Hackage_statistics http://i.imgur.com/mHvNV.png] [http://hackage.haskell.org/packages/archive/recent.rss http://haskell.org/wikiupload/7/7c/Rss16.png]</div><br />
<br />
<div style="font-size:80%"><br />
;[http://hackage.haskell.org/package/fclabels-1.1.0 fclabels 1.1.0]<br />
:First class accessor labels.<br />
;[http://hackage.haskell.org/package/snaplet-hdbc-0.7.1.1 snaplet-hdbc 0.7.1.1]<br />
:HDBC snaplet for Snap Framework<br />
;[http://hackage.haskell.org/package/GLFW-b-0.1.0.1 GLFW-b 0.1.0.1]<br />
:GLFW bindings<br />
;[http://hackage.haskell.org/package/math-functions-0.1.0.0 math-functions 0.1.0.0]<br />
:Special functions and Chebyshev polynomials<br />
;[http://hackage.haskell.org/package/arx-0.1.0 arx 0.1.0]<br />
:Archive execution tool.<br />
;[http://hackage.haskell.org/package/text-0.11.1.10 text 0.11.1.10]<br />
:An efficient packed Unicode text type.<br />
;[http://hackage.haskell.org/package/blaze-textual-0.2.0.6 blaze-textual 0.2.0.6]<br />
:Fast rendering of common datatypes<br />
;[http://hackage.haskell.org/package/double-conversion-0.2.0.4 double-conversion 0.2.0.4]<br />
:Fast conversion between double precision floating point and text<br />
;[http://hackage.haskell.org/package/text-format-0.3.0.7 text-format 0.3.0.7]<br />
:Text formatting<br />
;[http://hackage.haskell.org/package/base16-bytestring-0.1.1.4 base16-bytestring 0.1.1.4]<br />
:Fast base16 (hex) encoding and decoding for ByteStrings<br />
;[http://hackage.haskell.org/package/mighttpd2-2.4.1 mighttpd2 2.4.1]<br />
:A classical web server on WAI/warp<br />
;[http://hackage.haskell.org/package/wai-app-file-cgi-0.4.3 wai-app-file-cgi 0.4.3]<br />
:File/CGI App of WAI<br />
;[http://hackage.haskell.org/package/wai-logger-prefork-0.1.0 wai-logger-prefork 0.1.0]<br />
:A logging system for preforked WAI apps<br />
;[http://hackage.haskell.org/package/partial-lens-0.0.1 partial-lens 0.0.1]<br />
:Haskell 98 Partial Lenses<br />
;[http://hackage.haskell.org/package/wai-logger-0.1.0 wai-logger 0.1.0]<br />
:A logging system for WAI<br />
;[http://hackage.haskell.org/package/fast-logger-0.0.0 fast-logger 0.0.0]<br />
:A fast logging system<br />
;[http://hackage.haskell.org/package/force-layout-0.1.0.0 force-layout 0.1.0.0]<br />
:Simple force-directed layout<br />
;[http://hackage.haskell.org/package/smtLib-1.0.2 smtLib 1.0.2]<br />
:A library for working with the SMTLIB format.<br />
;[http://hackage.haskell.org/package/network-bitcoin-0.1.5 network-bitcoin 0.1.5]<br />
:Interface with Bitcoin RPC<br />
[http://hackage.haskell.org/packages/archive/pkg-list.html More...]<br />
</div></div>Daghttps://wiki.haskell.org/index.php?title=Template:Main/News&diff=43545Template:Main/News2011-12-10T00:49:27Z<p>Dag: Update list</p>
<hr />
<div><div class="subtitle">Recent Package Updates [http://haskell.org/haskellwiki/Hackage_statistics http://i.imgur.com/mHvNV.png] [http://hackage.haskell.org/packages/archive/recent.rss http://haskell.org/wikiupload/7/7c/Rss16.png]</div><br />
<br />
<div style="font-size:80%"><br />
;[http://hackage.haskell.org/package/cpsa-2.2.6 cpsa 2.2.6]<br />
:Symbolic cryptographic protocol analyzer<br />
;[http://hackage.haskell.org/package/resource-pool-0.2.0.4 resource-pool 0.2.0.4]<br />
:A high-performance striped resource pooling implementation<br />
;[http://hackage.haskell.org/package/HaTeX-3.1.0 HaTeX 3.1.0]<br />
:LaTeX code writer.<br />
;[http://hackage.haskell.org/package/HaTeX-meta-1.1.0 HaTeX-meta 1.1.0]<br />
:HaTeX monad modules builder.<br />
;[http://hackage.haskell.org/package/test-framework-0.4.2.0 test-framework 0.4.2.0]<br />
:Framework for running and organising tests, with HUnit and QuickCheck support<br />
;[http://hackage.haskell.org/package/snaplet-hdbc-0.7 snaplet-hdbc 0.7]<br />
:HDBC snaplet for Snap Framework<br />
;[http://hackage.haskell.org/package/acme-realworld-0.1.1 acme-realworld 0.1.1]<br />
:Primitives for manipulating the state of the universe<br />
;[http://hackage.haskell.org/package/zoom-cache-sndfile-0.3.0.0 zoom-cache-sndfile 0.3.0.0]<br />
:Tools for generating zoom-cache-pcm files<br />
;[http://hackage.haskell.org/package/zoom-cache-pcm-0.2.1.0 zoom-cache-pcm 0.2.1.0]<br />
:Library for zoom-cache PCM audio codecs<br />
;[http://hackage.haskell.org/package/scope-0.5.1.0 scope 0.5.1.0]<br />
:An interactive renderer for plotting time-series data<br />
;[http://hackage.haskell.org/package/zoom-cache-0.9.0.0 zoom-cache 0.9.0.0]<br />
:A streamable, seekable, zoomable cache file format<br />
;[http://hackage.haskell.org/package/http-enumerator-0.7.2 http-enumerator 0.7.2]<br />
:HTTP client package with enumerator interface and HTTPS support.<br />
;[http://hackage.haskell.org/package/IORefCAS-0.1.0.1 IORefCAS 0.1.0.1]<br />
:Atomic compare and swap for IORefs and STRefs.<br />
;[http://hackage.haskell.org/package/abstract-deque-0.1.1 abstract-deque 0.1.1]<br />
:Abstract, parameterized interface to mutable Deques.<br />
;[http://hackage.haskell.org/package/cereal-0.3.5.0 cereal 0.3.5.0]<br />
:A binary serialization library<br />
;[http://hackage.haskell.org/package/noodle-0.0.18 noodle 0.0.18]<br />
:the noodle programming language<br />
;[http://hackage.haskell.org/package/cuda-0.4.0.2 cuda 0.4.0.2]<br />
:FFI binding to the CUDA interface for programming NVIDIA GPUs<br />
;[http://hackage.haskell.org/package/blaze-builder-0.3.0.2 blaze-builder 0.3.0.2]<br />
:Efficient buffered output.<br />
;[http://hackage.haskell.org/package/hmatrix-0.12.0.2 hmatrix 0.12.0.2]<br />
:Linear algebra and numerical computation<br />
[http://hackage.haskell.org/packages/archive/pkg-list.html More...]<br />
</div></div>Daghttps://wiki.haskell.org/index.php?title=Tutorials&diff=43476Tutorials2011-12-08T00:43:51Z<p>Dag: /* Recommended tutorials */ all about monads moved to wiki</p>
<hr />
<div>==Introductions to Haskell==<br />
<br />
These are the recommended places to start learning, short of buying a textbook.<br />
<br />
=== Best places to start ===<br />
<br />
;[http://learnyouahaskell.com Learn You a Haskell for Great Good! (LYAH)]<br />
: Nicely illustrated tutorial showing Haskell concepts while interacting in GHCi. Written and drawn by Miran Lipovača.<br />
<br />
;[http://book.realworldhaskell.org/ Real World Haskell (RWH)]<br />
: A free online version of the complete book, with numerous reader-submitted comments. RWH is best suited for people who know the fundamentals of haskell already, and can write basic Haskell programs themselves already. It makes a great follow up after finishing LYAH. It can easily be read cover-to-cover, or you can focus on the chapters that interest you most, or when you find an idea you don't yet understand.<br />
<br />
;[http://darcs.haskell.org/yaht/yaht.pdf Yet Another Haskell Tutorial (YAHT)]<br />
:By Hal Daume III et al. A recommended tutorial for Haskell that is still under construction but covers already much ground. Also a classic text. Now available [http://en.wikibooks.org/wiki/Haskell/YAHT as a wikibook].<br />
<br />
;[http://en.wikibooks.org/wiki/Haskell Haskell Wikibook] <br />
:A communal effort by several authors to produce the definitive Haskell textbook. Its very much a work in progress at the moment, and contributions are welcome.<br />
<br />
;[http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours Write Yourself a Scheme in 48 Hours in Haskell]<br />
:A Haskell Tutorial, by Jonathan Tang. Most Haskell tutorials on the web seem to take a language-reference-manual approach to teaching. They show you the syntax of the language, a few language constructs, and then have you construct a few simple functions at the interactive prompt. The "hard stuff" of how to write a functioning, useful program is left to the end, or sometimes omitted entirely. This tutorial takes a different tack. You'll start off with command-line arguments and parsing, and progress to writing a fully-functional Scheme interpreter that implements a good-sized subset of R5RS Scheme. Along the way, you'll learn Haskell's I/O, mutable state, dynamic typing, error handling, and parsing features. By the time you finish, you should be fairly fluent in both Haskell and Scheme.<br />
<br />
;[http://acm.wustl.edu/functional/haskell.php How to Learn Haskell]<br />
:Some students at Washington University in St. Louis documented the path they took to learning Haskell and put together a nice meta-tutorial to guide beginners through some of the available resources. Experienced programmers looking for some quick code examples may be interested in their [http://acm.wustl.edu/functional/hs-breads.php breadcrumbs].<br />
<br />
=== More important tutorials ===<br />
<br />
;[http://www.haskell.org/tutorial/ A [[Gentle]] Introduction to Haskell] :By Paul Hudak, John Peterson, and Joseph H. Fasel. The title is misleading. Some knowledge of another functional programming language is expected. The emphasis is on the type system and those features which are really new in Haskell (compared to other functional programming languages). A classic, but not for the faint of heart (it's not so gentle). Also available in [http://www.haskell.org/wikiupload//5/5e/GentleFR.pdf French] [http://gorgonite.developpez.com/livres/traductions/haskell/gentle-haskell/ from this website] and also [http://www.rsdn.ru/article/haskell/haskell_part1.xml in Russian]. <br />
<br />
;[[H-99: Ninety-Nine Haskell Problems]]<br />
:A collection of programming puzzles, with Haskell solutions. Solving these is a great way to get into Haskell programming.<br />
<br />
;[[Haskell Tutorial for C Programmers]]<br />
:By Eric Etheridge. From the intro: "This tutorial assumes that the reader is familiar with C/C++, Python, Java, or Pascal. I am writing for you because it seems that no other tutorial was written to help students overcome the difficulty of moving from C/C++, Java, and the like to Haskell."<br />
<br />
;[http://www-106.ibm.com/developerworks/edu/os-dw-linuxhask-i.html Beginning Haskell] <br />
:From IBM developerWorks. This tutorial targets programmers of imperative languages wanting to learn about functional programming in the language Haskell. If you have programmed in languages such as C, Pascal, Fortran, C++, Java, Cobol, Ada, Perl, TCL, REXX, JavaScript, Visual Basic, or many others, you have been using an imperative paradigm. This tutorial provides a gentle introduction to the paradigm of functional programming, with specific illustrations in the Haskell 98 language. (Free registration required.)<br />
<br />
;[http://www.informatik.uni-bonn.de/~ralf/teaching/Hskurs_toc.html Online Haskell Course] <br />
:By Ralf Hinze (in German).<br />
<br />
;[http://www.cse.chalmers.se/~rjmh/tutorials.html Tutorial Papers in Functional Programming].<br />
:A collection of links to other Haskell tutorials, from John Hughes.<br />
<br />
;[http://www.cs.ou.edu/cs1323h/textbook/haskell.shtml Two Dozen Short Lessons in Haskell] <br />
:By Rex Page. A draft of a textbook on functional programming, available by ftp. It calls for active participation from readers by omitting material at certain points and asking the reader to attempt to fill in the missing information based on knowledge they have already acquired. The missing information is then supplied on the reverse side of the page. <br />
<br />
;[ftp://ftp.geoinfo.tuwien.ac.at/navratil/HaskellTutorial.pdf Haskell-Tutorial] <br />
:By Damir Medak and Gerhard Navratil. The fundamentals of functional languages for beginners. <br />
<br />
;[http://video.s-inf.de/#FP.2005-SS-Giesl.(COt).HD_Videoaufzeichnung Video Lectures] <br />
:Lectures (in English) by Jürgen Giesl. About 30 hours in total, and great for learning Haskell. The lectures are 2005-SS-FP.V01 through 2005-SS-FP.V26. Videos 2005-SS-FP.U01 through 2005-SS-FP.U11 are exercise answer sessions, so you probably don't want those.<br />
<br />
;[http://www.cs.utoronto.ca/~trebla/fp/ Albert's Functional Programming Course] <br />
:A 15 lesson introduction to most aspects of Haskell.<br />
<br />
;[http://www.iceteks.com/articles.php/haskell/1 Introduction to Haskell]<br />
:By Chris Dutton, An "attempt to bring the ideas of functional programming to the masses here, and an experiment in finding ways to make it easy and interesting to follow".<br />
<br />
;[http://www.csc.depauw.edu/~bhoward/courses/0203Spring/csc122/haskintro/ An Introduction to Haskell]<br />
:A brief introduction, by Brian Howard.<br />
<br />
;[http://web.syntaxpolice.org/lectures/haskellTalk/slides/index.html Introduction to Haskell]<br />
:By Isaac Jones (2003).<br />
<br />
;[http://www.linuxjournal.com/article/9096 Translating Haskell into English]<br />
:By Shannon Behrens, a glimpse of the Zen of Haskell, without requiring that they already be Haskell converts.<br />
<br />
;[http://www.shlomifish.org/lecture/Perl/Haskell/slides/ Haskell for Perl Programmers]<br />
:Brief introduction to Haskell, with a view to what perl programmers are interested in<br />
<br />
;[http://lisperati.com/haskell/ How To Organize a Picnic on a Computer]<br />
:Fun introduction to Haskell, step by step building of a program to seat people at a planned picnic, based on their similarities using data from a survey and a map of the picnic location.<br />
<br />
;[http://cs.wwc.edu/KU/PR/Haskell.html Haskell Tutorial]<br />
<br />
;[http://www.lisperati.com/haskell/ Conrad Barski's Haskell tutorial .. with robots]<br />
<br />
;[[Media:Introduction.pdf|Frederick Ross's Haskell introduction]]<br />
<br />
;[http://de.wikibooks.org/wiki/Haskell Dirk's Haskell Tutorial]<br />
:in German for beginners by a beginner. Not so deep, but with a lot examples with very small steps.<br />
<br />
;[http://www.crsr.net/Programming_Languages/SoftwareTools/index.html Software Tools in Haskell]<br />
:A tutorial for advanced readers<br />
<br />
== Motivation for using Haskell ==<br />
<br />
;[http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html Why Functional Programming Matters] <br />
:By [http://www.cse.chalmers.se/~rjmh/ John Hughes], The Computer Journal, Vol. 32, No. 2, 1989, pp. 98 - 107. Also in: David A. Turner (ed.): Research Topics in Functional Programming, Addison-Wesley, 1990, pp. 17 - 42.<BR> Exposes the advantages of functional programming languages. Demonstrates how higher-order functions and lazy evaluation enable new forms of modularization of programs.<br />
<br />
;[[Why Haskell matters]] <br />
:Discussion of the advantages of using Haskell in particular. An excellent article.<br />
<br />
;[http://www.cs.ukc.ac.uk/pubs/1997/224/index.html Higher-order + Polymorphic = Reusable] <br />
:By [http://www.cs.ukc.ac.uk/people/staff/sjt/index.html Simon Thompson]. Unpublished, May 1997.<BR> <STRONG>Abstract:</STRONG> This paper explores how certain ideas in object oriented languages have their correspondents in functional languages. In particular we look at the analogue of the iterators of the C++ standard template library. We also give an example of the use of constructor classes which feature in Haskell 1.3 and Gofer.<br />
<br />
;[http://www-128.ibm.com/developerworks/java/library/j-cb07186.html Explore functional programming with Haskell]<br />
:Introduction to the benefits of functional programming in Haskell by Bruce Tate.<br />
<br />
== Blog articles ==<br />
<br />
There are a large number of tutorials covering diverse Haskell topics<br />
published as blogs. Some of the best of these articles are collected<br />
here:<br />
<br />
;[[Blog articles]]<br />
<br />
==Practical Haskell==<br />
<br />
These tutorials examine using Haskell to writing complex real-world applications<br />
<br />
;[http://research.microsoft.com/%7Esimonpj/Papers/marktoberdorf Tackling the awkward squad: monadic input/output, concurrency, exceptions, and foreign-language calls in Haskell]<br />
:Simon Peyton Jones. Presented at the 2000 Marktoberdorf Summer School. In "Engineering theories of software construction", ed Tony Hoare, Manfred Broy, Ralf Steinbruggen, IOS Press, ISBN 1-58603-1724, 2001, pp47-96. The standard reference for monadic IO in GHC/Haskell. <br><strong>Abstract:</strong>Functional programming may be beautiful, but to write real applications we must grapple with awkward real-world issues: input/output, robustness, concurrency, and interfacing to programs written in other languages.<br />
<br />
;[[Hitchhikers Guide to the Haskell]]<br />
: Tutorial for C/Java/OCaml/... programers by Dmitry Astapov. From the intro: "This text intends to introduce the reader to the practical aspects of Haskell from the very beginning (plans for the first chapters include: I/O, darcs, Parsec, QuickCheck, profiling and debugging, to mention a few)".<br />
<br />
;[http://haskell.org/haskellwiki/IO_inside Haskell I/O inside: Down the Rabbit's Hole]<br />
:By Bulat Ziganshin (2006), a comprehensive tutorial on using IO monad.<br />
<br />
;[http://web.archive.org/web/20060622030538/http://www.reid-consulting-uk.ltd.uk/docs/ffi.html A Guide to Haskell's Foreign Function Interface]<br />
:A guide to using the foreign function interface extension, using the rich set of functions in the Foreign libraries, design issues, and FFI preprocessors.<br />
<br />
;[[Haskell IO for Imperative Programmers]]<br />
:A short introduction to IO from the perspective of an imperative programmer.<br />
<br />
;[[A brief introduction to Haskell|A Brief Introduction to Haskell]]<br />
:A translation of the article, [http://www.cs.jhu.edu/~scott/pl/lectures/caml-intro.html Introduction to OCaml], to Haskell.<br />
<br />
;[[Roll your own IRC bot]]<br />
:This tutorial is designed as a practical guide to writing real world code in Haskell and hopes to intuitively motivate and introduce some of the advanced features of Haskell to the novice programmer, including monad transformers. Our goal is to write a concise, robust and elegant IRC bot in Haskell.<br />
<br />
;[http://haskell.org/gtk2hs/docs/tutorial/glade/ Glade Tutorial (GUI Programming)]<br />
:For the absolute beginner in both Glade and Gtk2Hs. Covers the basics of Glade and how to access a .glade file and widgets in Gtk2Hs. Estimated learning time: 2 hours.<br />
;[http://www.muitovar.com/glade/es-index.html Tutorial de Glade]<br />
:A Spanish translation of the Glade tutorial<br />
<br />
;[http://www.muitovar.com/gtk2hs/index.html Gtk2Hs Tutorial]<br />
: An extensive Gtk2Hs programming guide, based on the GTK+2.0 tutorial by Tony Gale and Ian Main. This tutorial on GUI programming with Gtk2Hs has 22 chapters in 7 sections, plus an appendix on starting drawing with Cairo. A Spanish translation and source code of the examples are also available.<br />
<br />
;Applications of Functional Programming<br />
:Colin Runciman and David Wakeling (ed.), UCL Press, 1995, ISBN 1-85728-377-5 HB. From the cover:<blockquote>This book is unique in showcasing real, non-trivial applications of functional programming using the Haskell language. It presents state-of-the-art work from the FLARE project and will be an invaluable resource for advanced study, research and implementation.</blockquote><br />
<br />
;[[DealingWithBinaryData]] a guide to bytestrings, the various <tt>Get</tt> monads and the <tt>Put</tt> monad.<br />
<br />
;[[Internationalization of Haskell programs]]<br />
:Short tutorial on how to use GNU gettext utility to make applications, written on Haskell, multilingual.<br />
<br />
===Testing===<br />
<br />
;[http://blog.moertel.com/articles/2006/10/31/introductory-haskell-solving-the-sorting-it-out-kata Small overview of QuickCheck]<br />
<br />
;[[Introduction to QuickCheck]]<br />
<br />
==Reference material==<br />
<br />
;[http://haskell.org/haskellwiki/Category:Tutorials A growing list of Haskell tutorials on a diverse range of topics]<br />
:Available on this wiki<br />
<br />
;[http://haskell.org/haskellwiki/Category:How_to "How to"-style tutorials and information]<br />
<br />
;[http://zvon.org/other/haskell/Outputglobal/index.html Haskell Reference] <br />
:By Miloslav Nic.<br />
<br />
;[http://members.chello.nl/hjgtuyl/tourdemonad.html A tour of the Haskell Monad functions]<br />
:By Henk-Jan van Tuyl.<br />
<br />
;[http://www.cse.unsw.edu.au/~en1000/haskell/inbuilt.html Useful Haskell functions]<br />
:An explanation for beginners of many Haskell functions that are predefined in the Haskell Prelude.<br />
<br />
;[http://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/ListDoc/ Haskell's Standard List Functions]<br />
:A tour of the standard Haskell functions, directed by what you want to achieve<br />
<br />
;[http://haskell.org/ghc/docs/latest/html/libraries/ Documentation for the standard libraries]<br />
:Complete documentation of the standard Haskell libraries.<br />
<br />
;[http://www.haskell.org/haskellwiki/Category:Idioms Haskell idioms]<br />
:A collection of articles describing some common Haskell idioms. Often quite advanced.<br />
<br />
;[http://www.haskell.org/haskellwiki/Blow_your_mind Useful idioms]<br />
:A collection of short, useful Haskell idioms.<br />
<br />
;[http://www.haskell.org/haskellwiki/Programming_guidelines Programming guidelines]<br />
:Some Haskell programming and style conventions.<br />
<br />
;[http://www.md.chalmers.se/~rjmh/Combinators/LightningTour/index.htm Lightning Tour of Haskell]<br />
:By John Hughes, as part of a Chalmers programming course<br />
<br />
;[http://www.cs.chalmers.se/~augustss/AFP/manuals/haskeller.dvi.gz The Little Haskeller] <br />
:By Cordelia Hall and John Hughes. 9. November 1993, 26 pages. An introduction using the Chalmers Haskell B interpreter (hbi). Beware that it relies very much on the user interface of hbi which is quite different for other Haskell systems, and the tutorials cover Haskell 1.2 , not Haskell 98.<br />
<br />
;[http://www.cs.uu.nl/people/jeroen/courses/fp-eng.pdf Functional Programming]<br />
:By Jeroen Fokker, 1995. (153 pages, 600 KB). Textbook for learning functional programming with Gofer (an older implementation of Haskell). Here without Chapters&nbsp;6 and&nbsp;7.<br />
<br />
== Comparisons to other languages ==<br />
<br />
Articles constrasting feature of Haskell with other languages.<br />
<br />
;[http://programming.reddit.com/goto?id=nq1k Haskell versus Scheme]<br />
:Mark C. Chu-Carroll, Haskell and Scheme: Which One and Why?<br />
<br />
;[http://wiki.python.org/moin/PythonVsHaskell Comparing Haskell and Python]<br />
:A short overview of similarities and differences between Haskell and Python.<br />
<br />
;[http://programming.reddit.com/goto?id=nwm2 Monads in OCaml]<br />
:Syntax extension for monads in OCaml<br />
<br />
;[http://www.shlomifish.org/lecture/Perl/Haskell/slides/ Haskell for Perl programmers]<br />
:Short intro for perlers<br />
<br />
;[[A_brief_introduction_to_Haskell|Introduction to Haskell]] versus [http://www.cs.jhu.edu/~scott/pl/lectures/caml-intro.html Introduction to OCaml].<br />
<br />
;[http://www.thaiopensource.com/relaxng/derivative.html An algorithm for RELAX NG validation]<br />
:by James Clark (of RELAX NG fame). Describes an algorithm for validating an XML document against a RELAX NG schema, uses Haskell to describe the algorithm. The algorithm in Haskell and Java is then [http://www.donhopkins.com/drupal/node/117 discussed here].<br />
<br />
;[http://mult.ifario.us/articles/2006/10/11/first-steps-with-haskell-for-web-applications Haskell + FastCGI versus Ruby on Rails]<br />
:A short blog entry documenting performance results with ruby on rails and Haskell with fastcgi<br />
<br />
;[http://haskell.org/papers/NSWC/jfp.ps Haskell vs. Ada vs. C++ vs. Awk vs. ..., An Experiment in Software Prototyping Productivity] (postscript)<br />
:Paul Hudak and Mark P. Jones, 16 pages.<blockquote>Description of the results of an experiment in which several conventional programming languages, together with the functional language Haskell, were used to prototype a Naval Surface Warfare Center requirement for Geometric Region Servers. The resulting programs and development metrics were reviewed by a committee chosen by the US Navy. The results indicate that the Haskell prototype took significantly less time to develop and was considerably more concise and easier to understand than the corresponding prototypes written in several different imperative languages, including Ada and C++. </blockquote> <br />
<br />
;[http://www.osl.iu.edu/publications/prints/2003/comparing_generic_programming03.pdf A Comparative Study of Language Support for Generic Programming] (pdf)<br />
:Ronald Garcia, Jaakko Jrvi, Andrew Lumsdaine, Jeremy G. Siek, and Jeremiah Willcock. In Proceedings of the 2003 ACM SIGPLAN conference on Object-oriented programming, systems, languages, and applications (OOPSLA'03), October 2003.<blockquote>An interesting comparison of generic programming support across languages, including: Haskell, SML, C++, Java, C#. Haskell supports all constructs described in the paper -- the only language to do so. </blockquote><br />
<br />
;[http://homepages.inf.ed.ac.uk/wadler/realworld/index.html Functional Programming in the Real World]<br />
:A list of functional programs applied to real-world tasks. The main criterion for being real-world is that the program was written primarily to perform some task, not primarily to experiment with functional programming. Functional is used in the broad sense that includes both `pure' programs (no side effects) and `impure' (some use of side effects). Languages covered include CAML, Clean, Erlang, Haskell, Miranda, Scheme, SML, and others.<br />
<br />
;[http://www.defmacro.org/ramblings/lisp-in-haskell.html Lisp in Haskell]<br />
:Writing A Lisp Interpreter In Haskell, a tutorial<br />
<br />
== Teaching Haskell ==<br />
<br />
;[http://www.cs.ukc.ac.uk/pubs/1997/208/index.html Where do I begin? A problem solving approach to teaching functional programming]<br />
:By [http://www.cs.ukc.ac.uk/people/staff/sjt/index.html Simon Thompson]. In Krzysztof Apt, Pieter Hartel, and Paul Klint, editors, First International Conference on Declarative Programming Languages in Education. Springer-Verlag, September 1997. <br> <STRONG>Abstract:</STRONG> This paper introduces a problem solving method for teaching functional programming, based on Polya's `How To Solve It', an introductory investigation of mathematical method. We first present the language independent version, and then show in particular how it applies to the development of programs in Haskell. The method is illustrated by a sequence of examples and a larger case study. <br />
<br />
;[http://www.cs.ukc.ac.uk/pubs/1995/214/index.html Functional programming through the curriculum]<br />
:By [http://www.cs.ukc.ac.uk/people/staff/sjt/index.html Simon Thompson] and Steve Hill. In Pieter H. Hartel and Rinus Plasmeijer, editors, Functional Programming Languages in Education, LNCS 1022, pages 85-102. Springer-Verlag, December 1995. <br> <STRONG>Abstract:</STRONG> This paper discusses our experience in using a functional language in topics across the computer science curriculum. After examining the arguments for taking a functional approach, we look in detail at four case studies from different areas: programming language semantics, machine architectures, graphics and formal languages. <br />
<br />
;[http://www.cse.unsw.edu.au/~chak/papers/CK02a.html The Risks and Benefits of Teaching Purely Functional Programming in First Year]<br />
:By [http://www.cse.unsw.edu.au/~chak Manuel M. T. Chakravarty] and [http://www.cse.unsw.edu.au/~keller Gabriele Keller]. Journal of Functional Programming 14(1), pp 113-123, 2004. An earlier version of this paper was presented at Functional and Declarative Programming in Education (FDPE02). <br> <strong>Abstract</strong> We argue that teaching purely functional programming as such in freshman courses is detrimental to both the curriculum as well as to promoting the paradigm. Instead, we need to focus on the more general aims of teaching elementary techniques of programming and essential concepts of computing. We support this viewpoint with experience gained during several semesters of teaching large first-year classes (up to 600 students) in Haskell. These classes consisted of computer science students as well as students from other disciplines. We have systematically gathered student feedback by conducting surveys after each semester. This article contributes an approach to the use of modern functional languages in first year courses and, based on this, advocates the use of functional languages in this setting.<br />
<br />
<br />
==Using monads==<br />
<br />
See also the [[Monad]] HaskellWiki page.<br />
<br />
<br />
===Recommended tutorials===<br />
<br />
;[http://mvanier.livejournal.com/3917.html Mike Vanier's monad tutorial]<br />
:Recommended by David Balaban.<br />
<br />
;[[All About Monads]]<br />
:By Jeff Newbern. This tutorial aims to explain the concept of a monad and its application to functional programming in a way that is easy to understand and useful to beginning and intermediate Haskell programmers. Familiarity with the Haskell language is assumed, but no prior experience with monads is required. <br />
<br />
;[[Monads as computation]]<br />
:A tutorial which gives a broad overview to motivate the use of monads as an abstraction in functional programming and describe their basic features. It makes an attempt at showing why they arise naturally from some basic premises about the design of a library.<br />
<br />
;[[Monads as containers]]<br />
:A tutorial describing monads from a rather different perspective: as an abstraction of container-types, rather than an abstraction of types of computation.<br />
<br />
;[http://uebb.cs.tu-berlin.de/~magr/pub/Transformers.en.html Monad Transformers Step by Step]<br />
:By Martin Grabm&uuml;ller. A small tutorial on using monad transformers. In contrast to others found on the web, it concentrates on using them, not on their implementation.<br />
<br />
;[[What a Monad is not]]<br />
<br />
;[http://noordering.wordpress.com/2009/03/31/how-you-shouldnt-use-monad/ How you should(n’t) use Monads]<br />
<br />
;[http://www.sampou.org/haskell/a-a-monads/html/index.html モナドのすべて [All About Monads]]<br />
:A translation of Jeff Newbern's tutorial "All About Monads" into Japanese.<br />
<br />
===Parser===<br />
<br />
;[http://www.haskell.org/sitewiki/images/c/c6/ICMI45-paper-en.pdf The Parser monad and other monad (i.e. a monad with state and I/O string)]. <br />
:The parser monad is used to build modular, flexible, parsers. <br />
<br />
;[http://www.haskell.org/wikiupload/c/c6/ICMI45-paper-en.pdf How to build a monadic interpreter in one day] (pdf)<br />
:By Dan Popa. A small tutorial on how to build a language in one day, using the Parser Monad in the front end and a monad with state and I/O string in the back end. Read it if you are interested in learning: <br />
:# language construction and <br />
:# interpreter construction<br />
<br />
===More tutorials===<br />
<br />
;[http://stefan-klinger.de/files/monadGuide.pdf The Haskell Programmer's Guide to the IO Monad - Don't Panic.] <br />
:By Stefan Klinger. This report scratches the surface of category theory, an abstract branch of algebra, just deep enough to find the monad structure. It seems well written.<br />
<br />
;[http://www-users.mat.uni.torun.pl/~fly/materialy/fp/haskell-doc/Monads.html What the hell are Monads?] <br />
:By Noel Winstanley. A basic introduction to monads, monadic programming and IO. This introduction is presented by means of examples rather than theory, and assumes a little knowledge of Haskell. <br />
<br />
;[http://www.engr.mun.ca/~theo/Misc/haskell_and_monads.htm Monads for the Working Haskell Programmer -- a short tutorial]<br />
:By Theodore Norvell. <br />
<br />
;[http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html You Could Have Invented Monads! (And Maybe You Already Have.)]<br />
:A short tutorial on monads, introduced from a pragmatic approach, with less category theory references <br />
<br />
;[http://www.cs.chalmers.se/~augustss/AFP/monads.html Systematic Design of Monads]<br />
:By John Hughes and Magnus Carlsson. Many useful monads can be designed in a systematic way, by successively adding facilities to a trivial monad. The capabilities that can be added in this way include state, exceptions, backtracking, and output. Here we give a brief description of the trivial monad, each kind of extension, and sketches of some interesting operations that each monad supports.<br />
<br />
;[[Meet Bob The Monadic Lover]]<br />
:By Andrea Rossato. A by-the-author-supposed-to-be funny and short introduction to Monads, with code but without any reference to category theory: what monads look like and what they are useful for, from the perspective of a ... lover. (There is also the slightly more serious [[The Monadic Way]] by the same author.)<br />
<br />
;[http://www.haskell.org/pipermail/haskell-cafe/2006-November/019190.html Monstrous Monads]<br />
:Andrew Pimlott's humourous introduction to monads, using the metaphor of "monsters".<br />
<br />
;[http://strabismicgobbledygook.wordpress.com/2010/03/06/a-state-monad-tutorial/ A State Monad Tutorial]<br />
:A detailed tutorial with simple but practical examples.<br />
<br />
;Computational monads on Reddit, by [http://programming.reddit.com/info/ox6s/comments/coxiv tmoertel] and [http://programming.reddit.com/info/ox6s/comments/coxoh dons].<br />
<br />
;[http://www.loria.fr/~kow/monads/index.html Of monads and space suits]<br />
:By Eric Kow.<br />
<br />
;[[The Monadic Way]]<br />
<br />
;[http://www.alpheccar.org/fr/posts/show/60 Three kind of monads] : sequencing, side effects or containers<br />
<br />
;[[Simple monad examples]]<br />
<br />
;[http://en.wikipedia.org/wiki/Monads_in_functional_programming Article on monads on Wikipedia]<br />
<br />
;[[IO inside]] page<br />
:Explains why I/O in Haskell is implemented with a monad.<br />
<br />
;[http://haskell.org/haskellwiki/Blog_articles#Monads Blog articles]<br />
<br />
;[[Monad Transformers Explained]]<br />
<br />
;[http://www.muitovar.com/monad/moncow.html The Greenhorn's Guide to becoming a Monad Cowboy]<br />
:Covers basics, with simple examples, in a ''for dummies'' style. Includes monad transformers and monadic functions. Estimated learning time 2-3 days.<br />
<br />
;[http://ertes.de/articles/monads.html Understanding Haskell Monads]<br />
<br />
;[http://www.reddit.com/r/programming/comments/64th1/monads_in_python_in_production_code_you_can_and/c02u9mb A very clear explanation by 808140]<br />
<br />
;[[MonadCont under the hood]]<br />
:A detailed description of the ''Cont'' data type and its monadic operations, including the class ''MonadCont''.<br />
<br />
See also [[Research papers/Monads and arrows]]<br />
<br />
==Workshops on advanced functional programming==<br />
<br />
;[http://compilers.iecc.com/comparch/article/95-04-024 Advanced Functional Programming: 1st International Spring School on Advanced Functional Programming Techniques], Bastad, Sweden, May 24 - 30, 1995. Tutorial Text (Lecture Notes in Computer Science) <br />
<br />
;[http://www.cse.ogi.edu/PacSoft/conf/summerschool96.html Advanced Functional Programming: 2nd International School], Olympia, Wa, Usa, August 26-30, 1996 Tutorial Text (Lecture Notes in Computer Science) <br />
<br />
;[http://alfa.di.uminho.pt/~afp98/ Advanced Functional Programming: 3rd International School], AFP'98, Braga, Portugal, September 12-19, 1998, Revised Lectures (Lecture Notes in Computer Science) <br />
<br />
;[http://www.cs.uu.nl/~johanj/afp/afp4/ Advanced Functional Programming: 4th International School], AFP 2002, Oxford, UK, August 19-24, 2002, Revised Lectures (Lecture Notes in Computer Science) <br />
<br />
;[http://www.cs.ut.ee/afp04/ Advanced Functional Programming: 5th International School], AFP 2004, Tartu, Estonia, August 14-21, 2004, Revised Lectures (Lecture Notes in Computer Science) <br />
<br />
More advanced materials available from the [[Conferences|conference proceedings]], and the [[Research papers]] collection.<br />
<br />
<br />
[[Category:Tutorials]]</div>Daghttps://wiki.haskell.org/index.php?title=All_About_Monads&diff=43475All About Monads2011-12-08T00:38:07Z<p>Dag: Categories</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://mauke.dyndns.org/stuff/haskell/All_About_Monads.pdf here].<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 he declares obey they 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 he creates 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> is 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 -> w) -> m a -> m (a,w) <br />
listens f m = do (a,w) <- 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 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 />
</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 />
<thead><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 />
</thead><br />
<tbody><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 />
</tbody><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.<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>Daghttps://wiki.haskell.org/index.php?title=All_About_Monads&diff=43474All About Monads2011-12-07T19:45:01Z<p>Dag: Remove extra empty lines</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://mauke.dyndns.org/stuff/haskell/All_About_Monads.pdf here].<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 he declares obey they 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 he creates 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> is 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 -> w) -> m a -> m (a,w) <br />
listens f m = do (a,w) <- 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 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 />
</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 />
<thead><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 />
</thead><br />
<tbody><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 />
</tbody><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.<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.</div>Daghttps://wiki.haskell.org/index.php?title=All_About_Monads&diff=43473All About Monads2011-12-07T17:55:20Z<p>Dag: Remove all horizontal rulers</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://mauke.dyndns.org/stuff/haskell/All_About_Monads.pdf here].<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 />
<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 />
<br />
<br />
Meet the Monads<br />
<br />
<br />
= Meet the Monads =<br />
<br />
<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 />
<br />
<br />
Doing it with class<br />
<br />
<br />
= Doing it with class =<br />
<br />
<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 />
<br />
<br />
The monad laws<br />
<br />
<br />
= The monad laws =<br />
<br />
<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 he declares obey they 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 he creates 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 />
<br />
<br />
Exercises<br />
<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 />
<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 />
<br />
<br />
Monad support in Haskell<br />
<br />
<br />
= Monad support in Haskell =<br />
<br />
<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 />
<br />
<br />
Part II - Introduction<br />
<br />
<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 />
<br />
<br />
The Identity monad<br />
<br />
<br />
= The Identity monad =<br />
<br />
<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 />
<br />
<br />
The Maybe monad<br />
<br />
<br />
= The Maybe monad =<br />
<br />
<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> is 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 />
<br />
<br />
The Error monad<br />
<br />
<br />
= The Error monad =<br />
<br />
<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 />
<br />
<br />
The List monad<br />
<br />
<br />
= The List monad =<br />
<br />
<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 />
<br />
<br />
The IO monad<br />
<br />
<br />
= The IO monad =<br />
<br />
<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 />
<br />
<br />
The State monad<br />
<br />
<br />
= The State monad =<br />
<br />
<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 />
<br />
<br />
The Reader monad<br />
<br />
<br />
= The Reader monad =<br />
<br />
<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 />
<br />
<br />
The Writer monad<br />
<br />
<br />
= The Writer monad =<br />
<br />
<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 -> w) -> m a -> m (a,w) <br />
listens f m = do (a,w) <- 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 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 />
</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 />
<br />
<br />
The Continuation monad<br />
<br />
<br />
= The Continuation monad =<br />
<br />
<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 />
<br />
<br />
Part III - Introduction<br />
<br />
<br />
= Introduction =<br />
<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 />
<br />
<br />
Combining monads the hard way<br />
<br />
<br />
= Combining monads the hard way =<br />
<br />
<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 />
<br />
<br />
Monad transformers<br />
<br />
<br />
= Monad transformers =<br />
<br />
<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 />
<br />
<br />
Standard monad transformers<br />
<br />
<br />
= Standard monad transformers =<br />
<br />
<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 />
<thead><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 />
</thead><br />
<tbody><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 />
</tbody><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 />
<br />
<br />
Anatomy of a monad transformer<br />
<br />
<br />
= Anatomy of a monad transformer =<br />
<br />
<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 />
<br />
<br />
More examples with monad transformers<br />
<br />
<br />
= More examples with monad transformers =<br />
<br />
<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 />
<br />
<br />
Managing the transformer stack<br />
<br />
<br />
= Managing the transformer stack =<br />
<br />
<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 />
<br />
<br />
Continuing Exploration<br />
<br />
<br />
= Continuing Exploration =<br />
<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 />
<br />
<br />
A physical analogy for monads<br />
<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 />
<br />
<br />
Haskell code examples<br />
<br />
<br />
= Haskell code examples =<br />
<br />
This appendix contains a list of all of the code [[../examples/|examples]] supplied with the tutorial.<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.</div>Daghttps://wiki.haskell.org/index.php?title=All_About_Monads&diff=43472All About Monads2011-12-07T17:41:52Z<p>Dag: Really remove faulty TOCs</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://mauke.dyndns.org/stuff/haskell/All_About_Monads.pdf here].<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 />
<br />
= Introduction =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Meet the Monads<br />
<br />
<br />
= Meet the Monads =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Doing it with class<br />
<br />
<br />
= Doing it with class =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The monad laws<br />
<br />
<br />
= The monad laws =<br />
<br />
<br />
<br />
-----<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 he declares obey they 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 he creates 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 />
<br />
-----<br />
<br />
<br />
Exercises<br />
<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 />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Monad support in Haskell<br />
<br />
<br />
= Monad support in Haskell =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Part II - Introduction<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The Identity monad<br />
<br />
<br />
= The Identity monad =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The Maybe monad<br />
<br />
<br />
= The Maybe monad =<br />
<br />
<br />
<br />
-----<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> is 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 />
<br />
-----<br />
<br />
<br />
The Error monad<br />
<br />
<br />
= The Error monad =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The List monad<br />
<br />
<br />
= The List monad =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The IO monad<br />
<br />
<br />
= The IO monad =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The State monad<br />
<br />
<br />
= The State monad =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The Reader monad<br />
<br />
<br />
= The Reader monad =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The Writer monad<br />
<br />
<br />
= The Writer monad =<br />
<br />
<br />
<br />
-----<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 -> w) -> m a -> m (a,w) <br />
listens f m = do (a,w) <- 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 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 />
</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 />
<br />
-----<br />
<br />
<br />
The Continuation monad<br />
<br />
<br />
= The Continuation monad =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Part III - Introduction<br />
<br />
<br />
= Introduction =<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Combining monads the hard way<br />
<br />
<br />
= Combining monads the hard way =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Monad transformers<br />
<br />
<br />
= Monad transformers =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Standard monad transformers<br />
<br />
<br />
= Standard monad transformers =<br />
<br />
<br />
<br />
-----<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 />
<thead><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 />
</thead><br />
<tbody><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 />
</tbody><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 />
<br />
-----<br />
<br />
<br />
Anatomy of a monad transformer<br />
<br />
<br />
= Anatomy of a monad transformer =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
More examples with monad transformers<br />
<br />
<br />
= More examples with monad transformers =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Managing the transformer stack<br />
<br />
<br />
= Managing the transformer stack =<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Continuing Exploration<br />
<br />
<br />
= Continuing Exploration =<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
A physical analogy for monads<br />
<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 />
<br />
-----<br />
<br />
<br />
Haskell code examples<br />
<br />
<br />
= Haskell code examples =<br />
<br />
This appendix contains a list of all of the code [[../examples/|examples]] supplied with the tutorial.<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 />
<br />
-----</div>Daghttps://wiki.haskell.org/index.php?title=All_About_Monads&diff=43408All About Monads2011-12-07T15:44:56Z<p>Dag: Remove nav tables, use code tags for inline code</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://mauke.dyndns.org/stuff/haskell/All_About_Monads.pdf here].<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 />
<br />
= Introduction =<br />
<br />
* [[#what|What is a monad?]]<br />
* [[#why|Why should I make the effort to understand monads?]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Meet the Monads<br />
<br />
<br />
= Meet the Monads =<br />
<br />
* [[#typeconstructors|Type constructors]]<br />
* [[#maybe|Maybe a monad]]<br />
* [[#list|A list is also a monad]]<br />
* [[#example1|An example]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Doing it with class<br />
<br />
<br />
= Doing it with class =<br />
<br />
* [[#classes|Haskell type classes]]<br />
* [[#monad|The Monad class]]<br />
* [[#example2|Example continued]]<br />
* [[#donotation|Do notation]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The monad laws<br />
<br />
<br />
= The monad laws =<br />
<br />
* [[#laws|The three fundamental laws]]<br />
* [[#fail|Failure IS an option]]<br />
* [[#nowayout|No way out]]<br />
* [[#zero|Zero and Plus]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 he declares obey they 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 he creates 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 />
<br />
-----<br />
<br />
<br />
Exercises<br />
<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 />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Monad support in Haskell<br />
<br />
<br />
= Monad support in Haskell =<br />
<br />
* [[#prelude|In the standard prelude]]<br />
* [[#monad|In the Monad module]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Part II - Introduction<br />
<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The Identity monad<br />
<br />
<br />
= The Identity monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The Maybe monad<br />
<br />
<br />
= The Maybe monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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> is 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 />
<br />
-----<br />
<br />
<br />
The Error monad<br />
<br />
<br />
= The Error monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The List monad<br />
<br />
<br />
= The List monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The IO monad<br />
<br />
<br />
= The IO monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The State monad<br />
<br />
<br />
= The State monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The Reader monad<br />
<br />
<br />
= The Reader monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
The Writer monad<br />
<br />
<br />
= The Writer monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 -> w) -> m a -> m (a,w) <br />
listens f m = do (a,w) <- 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 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 />
</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 />
<br />
-----<br />
<br />
<br />
The Continuation monad<br />
<br />
<br />
= The Continuation monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Part III - Introduction<br />
<br />
<br />
= Introduction =<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Combining monads the hard way<br />
<br />
<br />
= Combining monads the hard way =<br />
<br />
* [[#nested|Nested Monads]]<br />
* [[#combined|Combined Monads]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Monad transformers<br />
<br />
<br />
= Monad transformers =<br />
<br />
* [[#type|Transformer type constructors]]<br />
* [[#lifting|Lifting]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Standard monad transformers<br />
<br />
<br />
= Standard monad transformers =<br />
<br />
* [[#classes|The MonadTrans and MonadIO classes]]<br />
* [[#library|Transformer versions of standard monads]]<br />
<br />
<br />
-----<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 />
<thead><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 />
</thead><br />
<tbody><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 />
</tbody><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 />
<br />
-----<br />
<br />
<br />
Anatomy of a monad transformer<br />
<br />
<br />
= Anatomy of a monad transformer =<br />
<br />
* [[#monad|Combined monad definition]]<br />
* [[#lift|Defining the lifting function]]<br />
* [[#functor|Functors]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
More examples with monad transformers<br />
<br />
<br />
= More examples with monad transformers =<br />
<br />
* [[#example22|WriterT with IO]]<br />
* [[#example23|ReaderT with IO]]<br />
* [[#example24|StateT with List]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Managing the transformer stack<br />
<br />
<br />
= Managing the transformer stack =<br />
<br />
* [[#order|Selecting the correct order]]<br />
* [[#example|An example with multiple transformers]]<br />
* [[#lifting|Heavy lifting]]<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
Continuing Exploration<br />
<br />
<br />
= Continuing Exploration =<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<br />
A physical analogy for monads<br />
<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 />
<br />
-----<br />
<br />
<br />
Haskell code examples<br />
<br />
<br />
= Haskell code examples =<br />
<br />
This appendix contains a list of all of the code [[../examples/|examples]] supplied with the tutorial.<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 />
<br />
-----</div>Daghttps://wiki.haskell.org/index.php?title=All_About_Monads&diff=43378All About Monads2011-12-07T15:22:27Z<p>Dag: Syntax highlighting</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://mauke.dyndns.org/stuff/haskell/All_About_Monads.pdf here].<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 />
-----<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[index.html|Table of Contents]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[meet.html|Meet the Monads]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Introduction =<br />
<br />
* [[#what|What is a monad?]]<br />
* [[#why|Why should I make the effort to understand monads?]]<br />
<br />
<br />
-----<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 <tt>Maybe</tt> 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 <tt>Maybe</tt> type suggests a strategy for combining computations which return <tt>Maybe</tt> values: if a combined computation consists of one computation <tt>B</tt> that depends on the result of another computation <tt>A</tt>, then the combined computation should yield <tt>Nothing</tt> whenever either <tt>A</tt> or <tt>B</tt> yield <tt>Nothing</tt> and the combined computation should yield the result of <tt>B</tt> applied to the result of <tt>A</tt> when both computations succeed.<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[index.html|Table of Contents]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[meet.html|Meet the Monads]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Meet the Monads<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introduction.html|Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[class.html|Doing it with class]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Meet the Monads =<br />
<br />
* [[#typeconstructors|Type constructors]]<br />
* [[#maybe|Maybe a monad]]<br />
* [[#list|A list is also a monad]]<br />
* [[#example1|An example]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<br />
<br />
We will use the <tt>Maybe</tt> type constructor throughout this chapter, so you should familiarize yourself with the definition and usage of [http://www.haskell.org/onlinelibrary/maybe.html <tt>Maybe</tt>] before continuing.<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 <tt>Maybe</tt>:<br />
<br />
<haskell><br />
data Maybe a = Nothing | Just a<br />
</haskell><br />
<tt>Maybe</tt> is a type constructor and <tt>Nothing</tt> and <tt>Just</tt> are data constructors. You can construct a data value by applying the <tt>Just</tt> data constructor to a value:<br />
<br />
<haskell><br />
country = Just "China"<br />
</haskell><br />
In the same way, you can construct a type by applying the <tt>Maybe</tt> 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 <tt>Maybe Int</tt> can be thought of as a <tt>Maybe</tt> container holding an <tt>Int</tt> value (or <tt>Nothing</tt>) and <tt>Maybe String</tt> would be a <tt>Maybe</tt> container holding a <tt>String</tt> value (or <tt>Nothing</tt>). In Haskell, we can also make the type of the container polymorphic, so we could write &quot;<tt>m a</tt>&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 <tt>Maybe a</tt> is the type of all computations that may return a value or <tt>Nothing</tt>. In this way, we can talk about the properties of the container apart from any details of what the container might hold.<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 <tt>m</tt>), a function that builds values of that type (<tt>a -&gt; m a</tt>), and a function that combines values of that type with computations that produce values of that type to produce a new computation for values of that type (<tt>m a -&gt; (a -&gt; m b) -&gt; m b</tt>). Note that the container is the same, but the type of the contents of the container can change. It is customary to call the monad type constructor &quot;<tt>m</tt>&quot; when discussing monads in general. The function that builds values of that type is traditionally called &quot;<tt>return</tt>&quot; and the third function is known as &quot;bind&quot; but is written &quot;<tt>&gt;&gt;=</tt>&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 <tt>return</tt> function creates primitive values of that computation type and <tt>&gt;&gt;=</tt> combines computations of that type together to make more complex computations of that type. Using the container analogy, the type constructor <tt>m</tt> is a container that can hold different values. <tt>m a</tt> is a container holding a value of type <tt>a</tt>. The <tt>return</tt> function puts a value into a monad container. The <tt>&gt;&gt;=</tt> function takes the value from a monad container and passes it to a function to produce a monad container containing a new value, possibly of a different type. The <tt>&gt;&gt;=</tt> 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 <tt>mother</tt> and <tt>father</tt> functions. But since these are cloned sheep, they may not always have both a mother and a father!<br />
<br />
We would represent the possibility of not having a mother or father using the <tt>Maybe</tt> 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 <tt>Nothing</tt> value at any point in the computation will cause <tt>Nothing</tt> to be the final result, and it would be much nicer to implement this notion once in a single place and remove all of the explicit <tt>case</tt> testing scattered all over the code. This will make the code easier to write, easier to read and easier to change. So good programming style would have us create a combinator that captures the behavior we want:<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 <tt>comb</tt> function is entirely polymorphic — it is not specialized for <tt>Sheep</tt> in any way. In fact, ''the combinator captures a general strategy for combining computations that may fail to return a value.'' Thus, we can apply the same combinator to other computations that may fail to return a value, such as database queries or dictionary lookups.<br />
<br />
The happy outcome is that common sense programming practice has led us to create a monad without even realizing it. The <tt>Maybe</tt> type constructor along with the <tt>Just</tt> function (acts like <tt>return</tt>) and our combinator (acts like <tt>&gt;&gt;=</tt>) together form a simple monad for building computations which may not return a value. All that remains to make this monad truly useful is to make it conform to the monad framework built into the Haskell language. That is the subject of the next chapter.<br />
<br />
== A list is also a monad ==<br />
<br />
We have seen that the <tt>Maybe</tt> type constructor is a monad for building computations which may fail to return a value. You may be surprised to know that another common Haskell type constructor, <tt>[]</tt> (for building lists), is also a monad. The List monad allows us to build computations which can return 0, 1, or more values.<br />
<br />
The <tt>return</tt> function for lists simply creates a singleton list (<tt>return x = [x]</tt>). The binding operation for lists creates a new list containing the results of applying the function to all of the values in the original list (<tt>l &gt;&gt;= f = concatMap f l</tt>).<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 <tt>return</tt>, and a combinator function called <tt>bind</tt> or <tt>&gt;&gt;=</tt>. These three elements work together to encapsulate a strategy for combining computations to produce more complex computations.<br />
<br />
Using the <tt>Maybe</tt> type constructor, we saw how good programming practice led us to define a simple monad that could be used to build complex computations out of sequences of computations that could each fail to return a value. The resulting <tt>Maybe</tt> monad encapsulates a strategy for combining computations that may not return values. By codifying the strategy in a monad, we have achieved a degree of modularity and flexibility that is not present when the computations are combined in an ad hoc manner.<br />
<br />
We have also seen that another common Haskell type constructor, <tt>[]</tt>, is a monad. The List monad encapsulates a strategy for combining computations that can return 0, 1, or multiple values.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introduction.html|Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[class.html|Doing it with class]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Doing it with class<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[meet.html|Meet the Monads]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[laws.html|The monad laws]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Doing it with class =<br />
<br />
* [[#classes|Haskell type classes]]<br />
* [[#monad|The Monad class]]<br />
* [[#example2|Example continued]]<br />
* [[#donotation|Do notation]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 <tt>Monad</tt> class that defines the names and signatures of the two monad functions <tt>return</tt> and <tt>&gt;&gt;=</tt>. It is not strictly necessary to make your monads instances of the <tt>Monad</tt> class, but it is a good idea. Haskell has special support for <tt>Monad</tt> instances built into the language and making your monads instances of the <tt>Monad</tt> class will allow you to use these features to write cleaner and more elegant code. Also, making your monads instances of the <tt>Monad</tt> class communicates important information to others who read the code and failing to do so can cause you to use confusing and non-standard function names. It's easy to do and it has many benefits, so just do it!<br />
<br />
The standard <tt>Monad</tt> 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 <tt>Maybe</tt> type constructor fits into the Haskell monad framework as an instance of the <tt>Monad</tt> class.<br />
<br />
Recall that our <tt>Maybe</tt> monad used the <tt>Just</tt> data constructor to fill the role of the monad <tt>return</tt> function and we built a simple combinator to fill the role of the monad <tt>&gt;&gt;=</tt> binding function. We can make its role as a monad explicit by declaring <tt>Maybe</tt> as an instance of the <tt>Monad</tt> class:<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 <tt>Maybe</tt> 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, <tt>Maybe</tt> is defined as an instance of the <tt>Monad</tt> class in the standard prelude, so you don't need to do it yourself. The other monad we have seen so far, the list constructor, is also defined as an instance of the <tt>Monad</tt> class in the standard prelude.<br />
<br />
[[Image:info.png]] When writing functions that work with monads, try to make use of the <tt>Monad</tt> class instead of using a specific monad instance. A function of the type<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 <tt>Maybe</tt> monad.<br />
<br />
== Do notation ==<br />
<br />
Using the standard monadic function names is good, but another advantage of membership in the <tt>Monad</tt> 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 <tt>Monad</tt> 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 <tt>&lt;-</tt> operator. Then using that variable in a subsequent monadic computation automatically performs the binding. The type of the expression to the right of the arrow is a monadic type <tt>m a</tt>. The expression to the left of the arrow is a pattern to be matched against the value ''inside'' the monad. <tt>(x:xs)</tt> would match against <tt>Maybe [1,2,3]</tt>, for example.<br />
<br />
Here is a sample of do notation using the <tt>Maybe</tt> 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 <tt>fathersMaternalGrandmother</tt> 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, <tt>x &lt;- expr1</tt>, becomes<br />
<br />
<haskell><br />
expr1 >>= \x -><br />
</haskell><br />
and every expression without a variable assignment, <tt>expr2</tt> 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 <tt>mothersPaternalGrandfather</tt> 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 <tt>Monad</tt> class and supply definitions of the <tt>return</tt> and <tt>&gt;&gt;=</tt> (pronounced &quot;bind&quot;) functions for the monad.<br />
<br />
A monad that is an instance of the <tt>Monad</tt> 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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[meet.html|Meet the Monads]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[laws.html|The monad laws]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The monad laws<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[class.html|Doing it with class]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[exercises.html|Exercises]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The monad laws =<br />
<br />
* [[#laws|The three fundamental laws]]<br />
* [[#fail|Failure IS an option]]<br />
* [[#nowayout|No way out]]<br />
* [[#zero|Zero and Plus]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 <tt>Monad</tt> instances he declares obey they laws. Haskell's <tt>Monad</tt> class also includes some functions beyond the minimal complete definition that we have not seen yet. Finally, many monads obey additional laws beyond the standard monad laws, and there is an additional Haskell class to support these extended monads.<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 <tt>Monad</tt> class with the correct type signatures. To be a proper monad, the <tt>return</tt> and <tt>&gt;&gt;=</tt> functions must work together according to three laws:<br />
<br />
# <tt>(return x) &gt;&gt;= f == f x</tt><br />
# <tt>m &gt;&gt;= return == m</tt><br />
# <tt>(m &gt;&gt;= f) &gt;&gt;= g == m &gt;&gt;= (\x -&gt; f x &gt;&gt;= g)</tt><br />
<br />
The first law requires that <tt>return</tt> is a left-identity with respect to <tt>&gt;&gt;=</tt>. The second law requires that <tt>return</tt> is a right-identity with respect to <tt>&gt;&gt;=</tt>. The third law is a kind of associativity law for <tt>&gt;&gt;=</tt>. 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 <tt>Monad</tt> class. It is up to the programmer to ensure that any <tt>Monad</tt> instance he creates satisfies the monad laws.<br />
<br />
== Failure IS an option ==<br />
<br />
The definition of the <tt>Monad</tt> class given [[class.html#monad|earlier]] showed only the minimal complete definition. The full definition of the <tt>Monad</tt> class actually includes two additional functions: <tt>fail</tt> and <tt>&gt;&gt;</tt>.<br />
<br />
The default implementation of the <tt>fail</tt> 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 <tt>Maybe</tt> monad, for instance, defines <tt>fail</tt> as:<br />
<br />
<haskell><br />
fail _ = Nothing<br />
</haskell><br />
so that <tt>fail</tt> returns an instance of the <tt>Maybe</tt> monad with meaningful behavior when it is bound with other functions in the <tt>Maybe</tt> monad.<br />
<br />
The <tt>fail</tt> function is not a required part of the mathematical definition of a monad, but it is included in the standard <tt>Monad</tt> class definition because of the role it plays in Haskell's do notation. The <tt>fail</tt> function is called whenever a pattern matching failure occurs in a do block:<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, <tt>fn 0</tt> has the value <tt>Just [2,3]</tt>, but <tt>fn 1</tt> and <tt>fn 2</tt> both have the value <tt>Nothing</tt>.<br />
<br />
The <tt>&gt;&gt;</tt> function is a convenience operator that is used to bind a monadic computation that does not require input from the previous computation in the sequence. It is defined in terms of <tt>&gt;&gt;=</tt>:<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 <tt>Monad</tt> class. That is not an accident. Nothing prevents the monad author from allowing it using functions specific to the monad. For instance, values can be extracted from the <tt>Maybe</tt> monad by pattern matching on <tt>Just x</tt> or using the <tt>fromJust</tt> function.<br />
<br />
By not requiring such a function, the Haskell <tt>Monad</tt> class allows the creation of one-way monads. One-way monads allow values to enter the monad through the <tt>return</tt> function (and sometimes the <tt>fail</tt> function) and they allow computations to be performed within the monad using the bind functions <tt>&gt;&gt;=</tt> and <tt>&gt;&gt;</tt>, but they do not allow values back out of the monad.<br />
<br />
The <tt>IO</tt> monad is a familiar example of a one-way monad in Haskell. Because you can't escape from the <tt>IO</tt> monad, it is impossible to write a function that does a computation in the <tt>IO</tt> monad but whose result type does not include the <tt>IO</tt> type constructor. This means that ''any'' function whose result type does not contain the <tt>IO</tt> type constructor is guaranteed not to use the <tt>IO</tt> monad. Other monads, such as <tt>List</tt> and <tt>Maybe</tt>, do allow values out of the monad. So it is possible to write functions which use these monads internally but return 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 <tt>readChar :: Char</tt>, because it needs to return a different character each time it is called, depending on the input from the user. It is an essential property of Haskell as a pure functional language that all functions return the same value when called twice with the same arguments. But it ''is'' ok to have an I/O function <tt>getChar :: IO Char</tt> in the <tt>IO</tt> monad, because it can only be used in a sequence within the one-way monad. There is no way to get rid of the <tt>IO</tt> type constructor in the signature of any function that uses it, so the <tt>IO</tt> type constructor acts as a kind of tag that identifies all functions that do I/O. Furthermore, such functions are only useful within the <tt>IO</tt> monad. So a 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 <tt>mzero</tt> and an operator <tt>mplus</tt> that obey four additional laws:<br />
<br />
# <tt>mzero &gt;&gt;= f == mzero</tt><br />
# <tt>m &gt;&gt;= (\x -&gt; mzero) == mzero</tt><br />
# <tt>mzero `mplus` m == m</tt><br />
# <tt>m `mplus` mzero == m</tt><br />
<br />
It is easy to remember the laws for <tt>mzero</tt> and <tt>mplus</tt> if you associate <tt>mzero</tt> with 0, <tt>mplus</tt> with +, and <tt>&gt;&gt;=</tt> with × in ordinary arithmetic.<br />
<br />
Monads which have a zero and a plus can be declared as instances of the <tt>MonadPlus</tt> 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 <tt>Maybe</tt> monad as an example, we see that the <tt>Maybe</tt> monad is an instance of <tt>MonadPlus</tt>:<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 <tt>Nothing</tt> as the zero value and says that adding two <tt>Maybe</tt> values together gives the first value that is not <tt>Nothing</tt>. If both input values are <tt>Nothing</tt>, then the result of <tt>mplus</tt> is also <tt>Nothing</tt>.<br />
<br />
The List monad also has a zero and a plus. <tt>mzero</tt> is the empty list and <tt>mplus</tt> is the <tt>++</tt> operator.<br />
<br />
The <tt>mplus</tt> 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 <tt>Maybe</tt>'s <tt>mplus</tt> to define a function, <tt>parent s = (mother s) `mplus` (father s)</tt>, which would return a parent if there is one, and <tt>Nothing</tt> is the sheep has no parents at all. For a sheep with both parents, the function would return one or the other, depending on the exact definition of <tt>mplus</tt> in the <tt>Maybe</tt> monad.<br />
<br />
== Summary ==<br />
<br />
Instances of the <tt>Monad</tt> 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 <tt>return</tt> function is both a left and a right identity and that the binding operator is associative. Failure to satisfy these laws will result in monads that do not behave properly and may cause subtle problems when using do-notation.<br />
<br />
In addition to the <tt>return</tt> and <tt>&gt;&gt;=</tt> functions, the <tt>Monad</tt> class defines another function, <tt>fail</tt>. The <tt>fail</tt> function is not a technical requirement for inclusion as a monad, but it is often useful in practice and it is included in the <tt>Monad</tt> class because it is used in Haskell's 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 <tt>MonadPlus</tt> class for such monads which define the <tt>mzero</tt> value and the <tt>mplus</tt> operator.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[class.html|Doing it with class]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[exercises.html|Exercises]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Exercises<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[laws.html|The monad laws]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[monadfns.html|Monad support in Haskell]]</td><br />
</tr><br />
</tbody><br />
</table><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 />
<br />
-----<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 <tt>maternalGrandfather</tt>, <tt>fathersMaternalGrandmother</tt>, and <tt>mothersPaternalGrandfather</tt> functions in [[../examples/example2.hs|Example 2]] using the monadic operators <tt>return</tt> and <tt>&gt;&gt;=</tt>, 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 <tt>parent</tt> and <tt>grandparent</tt> with signature <tt>Sheep -&gt; Maybe Sheep</tt>. They should return one sheep selected from all sheep matching the description, or <tt>Nothing</tt> if there is no such sheep. Hint: the <tt>mplus</tt> operator is useful here.<br />
<br />
Click [[solution2.html|here]] to see the solution.<br />
<br />
== Exercise 3: Using the List monad ==<br />
<br />
Write functions <tt>parent</tt> and <tt>grandparent</tt> with signature <tt>Sheep -&gt; [Sheep]</tt>. They should return all sheep matching the description, or the empty list if there is no such sheep. Hint: the <tt>mplus</tt> operator in the List monad is useful here. Also the <tt>maybeToList</tt> function in the <tt>Maybe</tt> module can be used to convert a value from the Maybe monad to the List monad.<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 <tt>(Monad m) =&gt;</tt>, <tt>(MonadPlus m) =&gt;</tt>, etc. class constraints.<br />
<br />
Write functions <tt>parent</tt> and <tt>grandparent</tt> with signature <tt>(MonadPlus m) =&gt; Sheep -&gt; m Sheep</tt>. They should be useful in both the Maybe and List monads. How does the functions' behavior differ when used with the List monad versus the Maybe monad? If you need to review the use of type classes and class constraints in Haskell, look [http://www.haskell.org/tutorial/classes.html here].<br />
<br />
Click [[solution4.html|here]] to see the solution.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[laws.html|The monad laws]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[monadfns.html|Monad support in Haskell]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Monad support in Haskell<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[exercises.html|Exercises]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[introII.html|Part II - Introduction]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Monad support in Haskell =<br />
<br />
* [[#prelude|In the standard prelude]]<br />
* [[#monad|In the Monad module]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 <tt>Monad</tt> class as well as a few auxilliary functions for working with monadic data types.<br />
<br />
=== The <tt>Monad</tt> class ===<br />
<br />
We have seen the <tt>Monad</tt> 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 <tt>sequence</tt> function takes a list of monadic computations, executes each one in turn and returns a list of the results. If any of the computations fail, then the whole function fails:<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 <tt>sequence_</tt> function (notice the underscore) has the same behavior as <tt>sequence</tt> but does not return a list of results. It is useful when only the 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 <tt>mapM</tt> function maps a monadic computation over a list of values and returns a list of the results. It is defined in terms of the list <tt>map</tt> function and the <tt>sequence</tt> function above:<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, <tt>mapM_</tt> which is defined using sequence_. <tt>mapM_</tt> operates the same as <tt>mapM</tt>, but it doesn't return the list of values. It is useful when only the 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 <tt>putString</tt> function for the <tt>IO</tt> monad could be defined as:<br />
<br />
<haskell><br />
putString :: [Char] -> IO ()<br />
putString s = mapM_ putChar s<br />
</haskell><br />
<tt>mapM</tt> can be used within a do block in a manner similar to the way the <tt>map</tt> function is normally used on lists. This is a common pattern with monads — a version of a function for use within a monad (i.e., intended for binding) will have a signature similar to the 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 (<tt>=&lt;&lt;</tt>) ===<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;<tt>&gt;&gt;=</tt>&quot;, the reverse binding function is called &quot;<tt>=&lt;&lt;</tt>&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 <tt>Monad</tt> module in the standard Haskell 98 libraries exports a number of facilities for more advanced monadic operations. To access these facilities, simply <tt>import Monad</tt> in your Haskell program.<br />
<br />
Not all of the function in the <tt>Monad</tt> module are discussed here, but you are encouraged to [http://www.haskell.org/onlinelibrary/monad.html explore the module for yourself] when you feel you are ready to see some of the more esoteric monad functions.<br />
<br />
=== The <tt>MonadPlus</tt> class ===<br />
<br />
The <tt>Monad</tt> module defines the <tt>MonadPlus</tt> 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 <tt>mapM</tt> functions are exported in the standard prelude and were described above.<br />
<br />
<tt>foldM</tt> is a monadic version of <tt>foldl</tt> 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 <tt>foldM</tt> 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 <tt>foldM</tt>.<br />
<br />
We can use <tt>foldM</tt> 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 <tt>traceFamily</tt> function uses <tt>foldM</tt> to create a simple way to trace back in the family tree to any depth and in any pattern. In fact, it is probably clearer to write &quot;<tt>traceFamily s [father, mother]</tt>&quot; than it is to use the <tt>paternalGrandmother</tt> function!<br />
<br />
A more typical use of <tt>foldM</tt> 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 <tt>filterM</tt> function works like the list <tt>filter</tt> function inside of a monad. It takes a predicate function which returns a Boolean value in the monad and a list of values. It returns, inside the monad, a list of those values for which the predicate was True.<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 <tt>filterM</tt> can be used within the <tt>IO</tt> 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 />
<tt>zipWithM</tt> is a monadic version of the <tt>zipWith</tt> function on lists. <tt>zipWithM_</tt> behaves the same but discards the output of the function. It is useful when only the 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 <tt>when</tt> function takes a boolean argument and a monadic computation with unit &quot;()&quot; type and performs the computation only when the boolean argument is <tt>True</tt>. The <tt>unless</tt> function does the same, except that it performs the computation ''unless'' the boolean argument is <tt>True</tt>.<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 />
=== <tt>ap</tt> 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 <tt>liftM</tt>, 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. <tt>liftM2</tt> 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 <tt>liftM5</tt> are defined in the <tt>Monad</tt> module.<br />
<br />
To see how the lifting operators allow more concise code, consider a computation in the <tt>Maybe</tt> monad in which you want to use a function <tt>swapNames::String -&gt; String</tt>. 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 <tt>liftM</tt> function, we can use <tt>liftM swapNames</tt> as a function of type <tt>Maybe String -&gt; Maybe String</tt>:<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 <tt>&gt;&gt;=</tt>). 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 <tt>ap</tt> that is sometimes more convenient to use than the lifting functions. <tt>ap</tt> is simply the function application operator (<tt>$</tt>) lifted into the monad:<br />
<br />
<haskell><br />
ap :: (Monad m) => m (a -> b) -> m a -> m b<br />
ap = liftM2 ($)<br />
</haskell><br />
Note that <tt>liftM2 f x y</tt> is equivalent to <tt>return f `ap` x `ap` y</tt>, and so on for functions of more arguments. <tt>ap</tt> is useful when working with higher-order functions and monads.<br />
<br />
The effect of <tt>ap</tt> depends on the strategy of the monad in which it is used. So for example <tt>[(*2),(+3)] `ap` [0,1,2]</tt> is equal to <tt>[0,2,4,3,4,5]</tt> and <tt>(Just (*2)) `ap` (Just 3)</tt> is <tt>Just 6</tt>. Here is a simple example that shows how <tt>ap</tt> can be useful when doing 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 <tt>MonadPlus</tt> ===<br />
<br />
There are two functions in the <tt>Monad</tt> module that are used with monads that have a zero and a plus. The first function is <tt>msum</tt>, which is analogous to the <tt>sum</tt> function on lists of integers. <tt>msum</tt> operates on lists of monadic values and folds the <tt>mplus</tt> operator into the list using the <tt>mzero</tt> element as the initial value:<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, <tt>msum</tt> is equivalent to <tt>concat</tt>. In the <tt>Maybe</tt> monad, <tt>msum</tt> returns the first non-<tt>Nothing</tt> value from a list. Likewise, the behavior in other monads will depend on the exact nature of their <tt>mzero</tt> and <tt>mplus</tt> definitions.<br />
<br />
<tt>msum</tt> allows many recursive functions and folds to be expressed more concisely. In the <tt>Maybe</tt> monad, for example, we can write:<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 <tt>guard</tt> 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 <tt>mzero &gt;&gt;= f == mzero</tt>. So, placing a <tt>guard</tt> function in a sequence of monadic operations will force any execution in which the guard is <tt>False</tt> to be <tt>mzero</tt>. This is similar to the way that guard predicates in a list comprehension cause values that fail the predicate to become <tt>[]</tt>.<br />
<br />
Here is an example demonstrating the use of the <tt>guard</tt> function in the <tt>Maybe</tt> 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 <tt>Monad</tt> class and most common monad functions are in the standard prelude. The <tt>MonadPlus</tt> class and less commonly-used (but still very useful!) functions are defined in the <tt>Monad</tt> module. Many other types in the Haskell libraries are declared as instances of <tt>Monad</tt> and <tt>MonadPlus</tt> in their respective modules.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[exercises.html|Exercises]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[introII.html|Part II - Introduction]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Part II - Introduction<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[monadfns.html|Monad support in Haskell]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[identitymonad.html|The Identity monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
<br />
-----<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 <tt>&gt;&gt;=</tt></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"><tt>Nothing</tt> input gives <tt>Nothing</tt> output<br /><br />
<tt>Just x</tt> input uses <tt>x</tt> 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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[monadfns.html|Monad support in Haskell]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[identitymonad.html|The Identity monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Identity monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introII.html|Part II - Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[maybemonad.html|The Maybe monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Identity monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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. <tt>Identity x &gt;&gt;= f == Identity (f x)</tt><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 <tt>runIdentity</tt> label is used in the type definition because it follows a style of monad definition that explicitly represents monad values as computations. In this style, a monadic computation is built up using the monadic operators and then the value of the computation is extracted using the <tt>run******</tt> function. Because the Identity monad does not do any computation, its definition is trivial. For a better example of this style of monad, see the [[statemonad.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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introII.html|Part II - Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[maybemonad.html|The Maybe monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Maybe monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[identitymonad.html|The Identity monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[errormonad.html|The Error monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Maybe monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which may return <tt>Nothing</tt><br />
<br />
Binding strategy:<br />
<br />
<tt>Nothing</tt> 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 <tt>Nothing</tt>. Complex database queries or dictionary lookups are good examples.<br />
<br />
Zero and plus:<br />
<br />
<tt>Nothing</tt> is the zero. The plus operation returns the first non-<tt>Nothing</tt> value or <tt>Nothing</tt> is both inputs are <tt>Nothing</tt>.<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 <tt>Nothing</tt> by ending the chain early if any step produces <tt>Nothing</tt> as output. It is useful when a computation entails a sequence of steps that depend on one another, and in which some steps may fail to return a value.<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 <tt>Maybe</tt> 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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[identitymonad.html|The Identity monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[errormonad.html|The Error monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Error monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[maybemonad.html|The Maybe monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[listmonad.html|The List monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Error monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 <tt>MonadError</tt>] class is parameterized over the type of error information and the monad type constructor. It is common to use <tt>Either String</tt> as the monad type constructor for an error monad in which error descriptions take the form of strings. In that case and many other common cases the resulting monad is already defined as an instance of the <tt>MonadError</tt> class. You can also define your own error type and/or use a monad type constructor other than <tt>Either String</tt> or <tt>Either IOError</tt>. In these cases you will have to explicitly define instances of the <tt>Error</tt> and/or <tt>MonadError</tt> classes.<br />
<br />
== Definition ==<br />
<br />
The definition of the <tt>MonadError</tt> 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 <tt>MonadError</tt> 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 />
<tt>throwError</tt> is used within a monadic computation to begin exception processing. <tt>catchError</tt> provides a handler function to handle previous errors and return to normal execution. A common idiom is:<br />
<br />
<haskell><br />
do { action1; action2; action3 } `catchError` handler <br />
</haskell><br />
where the <tt>action</tt> functions can call <tt>throwError</tt>. Note that <tt>handler</tt> and the do-block must have the same return type.<br />
<br />
The definition of the <tt>Either e</tt> type constructor as an instance of the <tt>MonadError</tt> class is straightforward. Following convention, <tt>Left</tt> is used for error values and <tt>Right</tt> is used for 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 <tt>Error</tt> data type with the <tt>ErrorMonad</tt>'s <tt>throwError</tt> and <tt>catchError</tt> exception mechanism. The example attempts to parse hexadecimal numbers and throws an exception if an invalid character is encountered. We use a custom <tt>Error</tt> data type to record the location of the parse error. The exception is caught by a calling function and handled by printing an informative error message.<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[maybemonad.html|The Maybe monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[listmonad.html|The List monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The List monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[errormonad.html|The Error monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[iomonad.html|The IO monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The List monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<tt>[]</tt> is the zero and <tt>++</tt> is the plus operation.<br />
<br />
Example type:<br />
<br />
<tt>[a]</tt><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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[errormonad.html|The Error monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[iomonad.html|The IO monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The IO monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[listmonad.html|The List monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[statemonad.html|The State monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The IO monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 <tt>main</tt> function must have type <tt>IO ()</tt>, 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 <tt>IO</tt> module do not perform I/O themselves. They return I/O actions, which describe an I/O operation to be performed. The I/O actions are combined within the IO monad (in a purely functional manner) to create more complex I/O actions, resulting in the final I/O action that is the <tt>main</tt> value of the program.<br />
<br />
The standard prelude and the [http://www.haskell.org/onlinelibrary/io.html <tt>IO</tt> module] define many functions that can be used within the IO monad and any Haskell programmer will undoubtedly be familiar with some of them. This tutorial will only discuss the monadic aspects of the IO monad, not the full range of functions available to perform I/O.<br />
<br />
The <tt>IO</tt> type constructor is a member of the <tt>Monad</tt> class and the <tt>MonadError</tt> class, where errors are of the type <tt>IOError</tt>. <tt>fail</tt> is defined to throw an error built from the string argument. Within the <tt>IO</tt> monad you can use the exception mechanisms from the <tt>Control.Monad.Error</tt> module in the Monad Template Library if you import the module. The same mechanisms have alternative names exported by the <tt>IO</tt> module: <tt>ioError</tt> and <tt>catch</tt>.<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 <tt>IO</tt> monad is incorporated into the Monad Template Library framework as an instance of the <tt>MonadError</tt> 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 <tt>IO</tt> module exports a convenience function called <tt>try</tt> that executes an I/O action and returns <tt>Right result</tt> if the action succeeded or <tt>Left IOError</tt> if an I/O error was caught.<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 <tt>MonadError</tt> class with the <tt>IO</tt> 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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[listmonad.html|The List monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[statemonad.html|The State monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The State monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[iomonad.html|The IO monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[readermonad.html|The Reader monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The State monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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: <tt>State s a</tt> is the type of a value of type <tt>a</tt> inside the State monad with state of type <tt>s</tt>.<br />
<br />
The type constructor <tt>State s</tt> is an instance of the <tt>Monad</tt> class. The <tt>return</tt> function simply creates a state transition function which sets the value but leaves the state unchanged. The binding operator creates a state transition function that applies its 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 <tt>MonadState</tt> class provides a standard but very simple interface for State monads. The <tt>get</tt> function retrieves the state by copying it as the value. The <tt>put</tt> function sets the state of the monad and does not yield a value.<br />
<br />
There are many additional functions provide which perform more complex computations built on top of <tt>get</tt> and put. The most useful one is <tt>gets</tt> which retrieves a function of the state. The others are listed in the [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.State.html documentation] for the State monad library.<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[iomonad.html|The IO monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[readermonad.html|The Reader monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Reader monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[statemonad.html|The State monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[writermonad.html|The Writer monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Reader monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 <tt>(runReader reader)</tt> to an environment value.<br />
<br />
The <tt>return</tt> function creates a <tt>Reader</tt> that ignores the environment and produces the given value. The binding operator produces a <tt>Reader</tt> that uses the environment to extract the value its 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 <tt>MonadReader</tt> class provides a number of convenience functions that are very useful when working with a Reader monad. The <tt>ask</tt> function retrieves the environment and the <tt>local</tt> function executes a computation in a modified environment. The <tt>asks</tt> function is a convenience function that retrieves a function of the current environment, and is typically used with a selector or lookup function.<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 <tt>asks</tt> function to lookup the value of the variable. When a template is included with new variable definitions, we can use the <tt>local</tt> function to resolve the template in a modified environment that contains the additional variable bindings.<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 <tt>t</tt> into a <tt>String</tt>, you simply need to do <tt>runReader (resolve t) env</tt>.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[statemonad.html|The State monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[writermonad.html|The Writer monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Writer monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[readermonad.html|The Reader monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[contmonad.html|The Continuation monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Writer monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 <tt>Monoid</tt> class, which represents a mathematical structure called a monoid in the same way that the <tt>Monad</tt> class represents the monad structure.<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 <tt>mzero</tt> and <tt>mplus</tt> for instances of <tt>MonadPlus</tt>. That is because monads with a zero and plus are monads that are also monoids!<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 <tt>Monoid</tt> class (in Data.Monoid) to provide a standard convention for working with monoids: the identity element is named <tt>mempty</tt> and the operator is named <tt>mappend</tt>.<br />
<br />
The most commonly used standard monoid in Haskell is the list, but functions of type <tt>(a -&gt; a)</tt> 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 <tt>mappend</tt> operation as the output grows. In that case, a data structure that supports fast append operations would be a more appropriate choice.<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 <tt>return</tt> function simply returns the value along with an empty log. Binding executes the bound function using the current value as input, and appends any log output to the existing log.<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 -> w) -> m a -> m (a,w) <br />
listens f m = do (a,w) <- 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 <tt>MonadWriter</tt> class provides a number of convenience functions for working with Writer monads. The simplest and most useful is <tt>tell</tt>, which adds one or more entries to the log. The <tt>listen</tt> function turns a Writer that returns a value <tt>a</tt> and produces output <tt>w</tt> into a Writer that produces a value <tt>(a,w)</tt> and still produces output <tt>w</tt>. This allows the computation to &quot;listen&quot; to the log output generated by a Writer.<br />
<br />
The <tt>pass</tt> function is slightly more complicated. It converts a Writer that produces a value <tt>(a,f)</tt> and output <tt>w</tt> into a Writer that produces a value <tt>a</tt> and output <tt>f w</tt>. This is somewhat cumbersome, so the helper function <tt>censor</tt> is normally used. The <tt>censor</tt> function takes a function and a Writer and produces a new Writer whose output is the same but whose log entry has been modified by the function.<br />
<br />
The <tt>listens</tt> function operates just like <tt>listen</tt> except that the log part of the value is modified by the supplied function.<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 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 />
</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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[readermonad.html|The Reader monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[contmonad.html|The Continuation monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Continuation monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[writermonad.html|The Writer monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: Part III - Introduction</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Continuation monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 <tt>id</tt>) which produces the final result. Since continuations are functions which represent the future of a computation, manipulation of the continuation functions can achieve complex manipulations of the future of the computation, such as interrupting a computation in the middle, aborting a portion of a computation, restarting a computation and interleaving execution of computations. The Continuation monad adapts CPS to the structure of a monad.<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. <tt>Cont r a</tt> is a CPS computation that produces an intermediate result of type <tt>a</tt> within a CPS computation whose final result type is <tt>r</tt>.<br />
<br />
The <tt>return</tt> function simply creates a continuation which passes the value on. The <tt>&gt;&gt;=</tt> 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 <tt>MonadCont</tt> class provides the <tt>callCC</tt> function, which provides an escape continuation mechanism for use with Continuation monads. Escape continuations allow you to abort the current computation and return a value immediately. They achieve a similar effect to <tt>throwError</tt> and catchError within an <tt>Error</tt> monad.<br />
<br />
<tt>callCC</tt> calls a function with the current continuation as its argument (hence the name). The standard idiom used with <tt>callCC</tt> is to provide a 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 <tt>callCC</tt>, the Continuation monad can be used to implement other, more powerful continuation manipulations. These other mechanisms have fairly specialized uses, however — and abuse of them can easily create fiendishly obfuscated code — so they will not be covered here.<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[writermonad.html|The Writer monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: Part III - Introduction</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Part III - Introduction<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[contmonad.html|The Continuation monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[hardway.html|Combining monads the hard way]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Introduction =<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[contmonad.html|The Continuation monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[hardway.html|Combining monads the hard way]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Combining monads the hard way<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introIII.html|Part III - Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[transformers.html|Monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Combining monads the hard way =<br />
<br />
* [[#nested|Nested Monads]]<br />
* [[#combined|Combined Monads]]<br />
<br />
<br />
-----<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 <tt>Cont (IO String) a</tt> if we need to perform I/O within the computation in the Continuation monad. We could use a monad of type <tt>State (Either Err a) a</tt> to combine the features of the State and Error monads in a single computation.<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 <tt>Int</tt> and <tt>String</tt> values are now of type <tt>IO Int</tt> and <tt>IO String</tt>. We can't extract values from the IO monad — it's a 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 <tt>toIO</tt> 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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introIII.html|Part III - Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[transformers.html|Monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Monad transformers<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[hardway.html|Combining monads the hard way]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[standardxformers.html|Standard monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Monad transformers =<br />
<br />
* [[#type|Transformer type constructors]]<br />
* [[#lifting|Lifting]]<br />
<br />
<br />
-----<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 <tt>Reader r a</tt> is the type of values of type <tt>a</tt> within a Reader monad with environment of type <tt>r</tt>. The type constructor <tt>Reader r</tt> is an instance of the <tt>Monad</tt> class, and the <tt>runReader::(r-&gt;a)</tt> function performs a computation in the Reader monad and returns the result of type <tt>a</tt>.<br />
<br />
A transformer version of the Reader monad, called <tt>ReaderT</tt>, exists which adds a monad type constructor as an addition parameter. <tt>ReaderT r m a</tt> is the type of values of the combined monad in which Reader is the base monad and <tt>m</tt> is the inner monad. <tt>ReaderT r m</tt> is an instance of the monad class, and the <tt>runReaderT::(r -&gt; m a)</tt> function performs a computation in the combined monad and returns a result of type <tt>m a</tt>.<br />
<br />
Using the transformer versions of the monads, we can produce combined monads very simply. <tt>ReaderT r IO</tt> is a combined Reader+IO monad. We can also generate the non-transformer version of a monad from the transformer version by applying it to the Identity monad. So <tt>ReaderT r Identity</tt> is the same monad as <tt>Reader r</tt>.<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 <tt>liftM</tt> family of functions which are used to lift non-monadic functions into a monad. Each monad transformer provides a <tt>lift</tt> function that is used to lift a monadic computation into a combined monad. Many transformers also provide a <tt>liftIO</tt> function, which is a version of <tt>lift</tt> that is optimized for lifting computations in the <tt>IO</tt> monad. To see this in action, we will continue to develop our previous example in the Continuation monad.<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 <tt>ContT</tt>, the transformer version of <tt>Cont</tt>, with the original version to see how unobtrusive the changes become when using the monad transformer.<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[hardway.html|Combining monads the hard way]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[standardxformers.html|Standard monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Standard monad transformers<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[transformers.html|Monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[xformeranatomy.html|Anatomy of a monad transformer]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Standard monad transformers =<br />
<br />
* [[#classes|The MonadTrans and MonadIO classes]]<br />
* [[#library|Transformer versions of standard monads]]<br />
<br />
<br />
-----<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 <tt>MonadTrans</tt> class is defined in [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Trans.html Control.Monad.Trans] and provides the single function <tt>lift</tt>. The <tt>lift</tt> function lifts a monadic computation in the inner monad into the combined monad.<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 <tt>MonadIO</tt> class, which defines the <tt>liftIO</tt> 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 <tt>ContT</tt> transformer turns continuations of the form <tt>(a-&gt;r)-&gt;r</tt> into continuations of the form <tt>(a-&gt;m r)-&gt;m r</tt>. The <tt>StateT</tt> transformer is different. It turns state transformer functions of the form <tt>s-&gt;(a,s)</tt> into state transformer functions of the form <tt>s-&gt;m (a,s)</tt>. In general, there is no magic formula to create a transformer version of a monad — the form of each transformer depends on what makes sense in the context of its non-transformer type.<br />
<br />
<table><br />
<thead><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 />
</thead><br />
<tbody><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"><tt>Either e a</tt></td><br />
<td align="left"><tt>m (Either e a)</tt></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"><tt>s -&gt; (a,s)</tt></td><br />
<td align="left"><tt>s -&gt; m (a,s)</tt></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"><tt>r -&gt; a</tt></td><br />
<td align="left"><tt>r -&gt; m a</tt></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"><tt>(a,w)</tt></td><br />
<td align="left"><tt>m (a,w)</tt></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"><tt>(a -&gt; r) -&gt; r</tt></td><br />
<td align="left"><tt>(a -&gt; m r) -&gt; m r</tt></td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
[[Image:info.png]] Order is important when combining monads. <tt>StateT s (Error e)</tt> is different than <tt>ErrorT e (State s)</tt>. The first produces a combined type of <tt>s -&gt; Error e (a,s)</tt>, in which the computation can either return a new state or generate an error. The second combination produces a combined type of <tt>s -&gt; (Error e a,s)</tt>, in which the computation always returns a new state, and the value can be an error or a normal value.<br /><br />
<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[transformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[xformeranatomy.html|Anatomy of a monad transformer]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Anatomy of a monad transformer<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[standardxformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[xformerexamples.html|More examples with monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Anatomy of a monad transformer =<br />
<br />
* [[#monad|Combined monad definition]]<br />
* [[#lift|Defining the lifting function]]<br />
* [[#functor|Functors]]<br />
<br />
<br />
-----<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, <tt>StateT</tt>. Studying this transformer will build insight into the transformer mechanism that you can call upon when using monad transformers in your code. You might want to review the section on the [[statemonad.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 />
<tt>State s</tt> is an instance of both the <tt>Monad</tt> class and the <tt>MonadState s</tt> class, so <tt>StateT s m</tt> should also be members of the <tt>Monad</tt> and <tt>MonadState s</tt> classes. Furthermore, if <tt>m</tt> is an instance of <tt>MonadPlus</tt>, <tt>StateT s m</tt> should also be a member of <tt>MonadPlus</tt>.<br />
<br />
To define <tt>StateT s m</tt> as a <tt>Monad</tt> 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|<tt>State s</tt>]]. Our definition of <tt>return</tt> makes use of the <tt>return</tt> function of the inner monad, and the binding operator uses a do-block to perform a computation in the inner monad.<br />
<br />
We also want to declare all combined monads that use the <tt>StateT</tt> transformer to be instaces of the <tt>MonadState</tt> class, so we will have to give definitions for <tt>get</tt> and <tt>put</tt>:<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 <tt>StateT</tt> is used with an instance of <tt>MonadPlus</tt> to be instances of <tt>MonadPlus</tt>:<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 <tt>StateT s</tt> an instance of the <tt>MonadTrans</tt> class by providing a <tt>lift</tt> function:<br />
<br />
<haskell><br />
instance MonadTrans (StateT s) where<br />
lift c = StateT $ \s -> c >>= (\x -> return (x,s))<br />
</haskell><br />
The <tt>lift</tt> function creates a <tt>StateT</tt> state transformation function that binds the computation in the inner monad to a function that packages the result with the input state. The result is that a function that returns a list (i.e., a computation in the List monad) can be lifted into <tt>StateT s []</tt>, where it becomes a function that returns a <tt>StateT (s -&gt; [(a,s)])</tt>. 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 <tt>StateT</tt> to a different monad will produce different semantics for the <tt>lift</tt> 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 <tt>fmap :: (a-&gt;b) -&gt; f a -&gt; f b</tt>. 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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[standardxformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[xformerexamples.html|More examples with monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
More examples with monad transformers<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[xformeranatomy.html|Anatomy of a monad transformer]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[stacking.html|Managing the transformer stack]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= More examples with monad transformers =<br />
<br />
* [[#example22|WriterT with IO]]<br />
* [[#example23|ReaderT with IO]]<br />
* [[#example24|StateT with List]]<br />
<br />
<br />
-----<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 <tt>StateT</tt> 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 <tt>tryAllValues</tt> will fork the solution space, assigning the named variable to be <tt>&quot;male&quot;</tt> in one fork and <tt>&quot;female&quot;</tt> in the other. The forks which produce inconsistent variable assignments are eliminated (using the <tt>guard</tt> function). The call to <tt>getFinalVars</tt> applies <tt>guard</tt> again to eliminate inconsistent variable assignments and returns the remaining assignments as the value of the computation.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[xformeranatomy.html|Anatomy of a monad transformer]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[stacking.html|Managing the transformer stack]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Managing the transformer stack<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[xformerexamples.html|More examples with monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[beyond.html|Continuing Exploration]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Managing the transformer stack =<br />
<br />
* [[#order|Selecting the correct order]]<br />
* [[#example|An example with multiple transformers]]<br />
* [[#lifting|Heavy lifting]]<br />
<br />
<br />
-----<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 <tt>MonadError</tt> and <tt>MonadState</tt>, but should you apply <tt>StateT</tt> to the <tt>Error</tt> monad or <tt>ErrorT</tt> to the <tt>State</tt> monad?<br />
<br />
The decision depends on the exact semantics you want for your combined monad. Applying <tt>StateT</tt> to the <tt>Error</tt> monad gives a state transformer function of type <tt>s -&gt; Error e (a,s)</tt>. Applying <tt>ErrorT</tt> to the <tt>State</tt> monad gives a state transformer function of type <tt>s -&gt; (Error e a,s)</tt>. Which order to choose depends on the role of errors in your computation. If an error means no state could be produced, you would apply <tt>StateT</tt> to <tt>Error</tt>. If an error means no value could be produced, but the state remains valid, then you would apply <tt>ErrorT</tt> to <tt>State</tt>.<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 <tt>WriterT</tt> 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. <tt>StateT s (WriterT w [])</tt> yields a type like: <tt>s -&gt; [((a,s),w)]</tt>. <tt>WriterT w (StateT s [])</tt> yields a type like: <tt>s -&gt; [((a,w),s)]</tt>. 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 <tt>MonadState</tt> and <tt>MonadWriter</tt>, so we can freely mix use of <tt>get</tt>, <tt>put</tt>, and <tt>tell</tt> in our monadic computations.<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 <tt>guard</tt> function. Instead, we only create branches that correspond to allowed queen positions. We use the added logging facility to log the number of possible choices at each step and the position in which the queen was placed.<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 <tt>lift</tt> function from the <tt>MonadTrans</tt> class comes into its own. The <tt>lift</tt> function gives us the ability to write our code in a clear, modular, reusable manner and then lift the computations into the combined monad as needed.<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 <tt>logString</tt> computation into the combined monad when we use it.<br />
<br />
[[Image:info.png]] You may need to use the compiler flags <tt>-fglasgow-exts</tt> with GHC or the equivalent flags with your Haskell compiler to use this technique. The issue is that <tt>m</tt> in the constraint above is a type constructor, not a type, and this is not supported in standard Haskell 98. <br /><br />
<br />
<br />
When using lifting with complex transformer stacks, you may find yourself composing multiple lifts, like <tt>lift . lift . lift $ f x</tt>. This can become hard to follow, and if the transformer stack changes (perhaps you add <tt>ErrorT</tt> into the mix) the lifting may need to be changed all over the code. A good practice to prevent this is to declare helper functions with informative names to do the lifting:<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[xformerexamples.html|More examples with monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[beyond.html|Continuing Exploration]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Continuing Exploration<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[stacking.html|Managing the transformer stack]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[analogy.html|Appendix I - A physical analogy for monads]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Continuing Exploration =<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[stacking.html|Managing the transformer stack]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[analogy.html|Appendix I - A physical analogy for monads]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
A physical analogy for monads<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[standardxformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[examples.html|Appendix II - Haskell code examples]]</td><br />
</tr><br />
</tbody><br />
</table><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 <tt>Tray</tt> 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 <tt>Tray</tt> monad as a disguised version of the <tt>Maybe</tt> 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 <tt>fail</tt> routine to produce an empty tray. The <tt>fail</tt> routine takes an argument describing the failure, but our <tt>Tray</tt> type ignores this and simply produces an empty tray. This empty tray travels down the assembly line and the combiner machines allow it to bypass the remaining worker machines. It eventually reaches the end of the assembly line, where it is brought to you, the quality control engineer. It is your job to figure out which machine failed, but all you have to go on is an empty tray.<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 <tt>fail</tt> routine in your <tt>Tray</tt> monad. Because your assembly line is organized around a monadic approach, it is easy for you to add this functionality to your assembly line without changing your worker machines.<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 <tt>Tray2</tt> monad as a disguised version of the <tt>Error</tt> monad that is a standard part of the Haskell 98 libraries.<br /><br />
<br />
<br />
Replacing the <tt>Tray</tt> monad with the <tt>Tray2</tt> monad instantly upgrades your assembly line. Now when a failure occurs, the tray that is brought to the quality control engineer contains a failure report detailing the exact cause of the failure!<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[standardxformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[examples.html|Appendix II - Haskell code examples]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Haskell code examples<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[analogy.html|Appendix I - A physical analogy for monads]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left"></td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Haskell code examples =<br />
<br />
This appendix contains a list of all of the code [[../examples/|examples]] supplied with the tutorial.<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 <tt>Monad</tt> class (in this case, <tt>Maybe</tt> 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 <tt>foldM</tt> 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 <tt>foldM</tt> function within a do-block. It combines dictionary values read from different files into a single dictionary using the <tt>foldM</tt> 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 <tt>filterM</tt> 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 <tt>liftM</tt> 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 <tt>liftM2</tt>. 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 <tt>ap</tt>. It folds <tt>ap</tt> through a list of <tt>Maybe (a-&gt;a)</tt> 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 <tt>msum</tt> 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 <tt>guard</tt> in the Maybe monad to select only the records from a list that satisfy a predicate (equivalent to <tt>filter</tt>).<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 <tt>Maybe</tt> monad to build complex queries from simpler queries that may fail to return a result. The specific example used is looking up mail preferences for someone based on either their full name or a nickname.<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 <tt>Either</tt> type constructor as an <tt>Error</tt> monad with a custom error type. The example parses hexadecimal digits and uses the exception handling mechanism of the <tt>Error</tt> monad to provide informative error messages in the event of a parse failure.<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 <tt>fail</tt> calls due to pattern matching failures and the use of <tt>catcherror</tt>.<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 <tt>StateT</tt> 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 <tt>StateT</tt> and <tt>WriterT</tt> 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 <tt>lift</tt> function and the necessity of managing its use in complex transformer stacks.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[analogy.html|Apendix I - A physical analogy for monads]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left"></td><br />
</tr><br />
</tbody><br />
</table></div>Daghttps://wiki.haskell.org/index.php?title=User_talk:Geheimdienst&diff=43376User talk:Geheimdienst2011-12-07T00:13:50Z<p>Dag: All About Monads</p>
<hr />
<div>== All About Monads ==<br />
<br />
Hello, we spoke on IRC about porting All About Monads to the wiki. I emailed the author and got permission, and have started experimenting [https://github.com/dag/all-about-monads in a GitHub repo] and you can preview the result on the [[All About Monads]] page. If you're interested in helping out with this effort, it would be surely appreciated.<br />
<br />
--[[User:Dag|Dag]] 00:13, 7 December 2011 (UTC)</div>Daghttps://wiki.haskell.org/index.php?title=All_About_Monads&diff=43375All About Monads2011-12-07T00:08:47Z<p>Dag: It has begun.</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://mauke.dyndns.org/stuff/haskell/All_About_Monads.pdf here].<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 />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[index.html|Table of Contents]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[meet.html|Meet the Monads]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Introduction =<br />
<br />
* [[#what|What is a monad?]]<br />
* [[#why|Why should I make the effort to understand monads?]]<br />
<br />
<br />
-----<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 <tt>Maybe</tt> type in Haskell:<br />
<br />
<pre>data Maybe a = Nothing | Just a</pre><br />
which represents the type of computations which may fail to return a result. The <tt>Maybe</tt> type suggests a strategy for combining computations which return <tt>Maybe</tt> values: if a combined computation consists of one computation <tt>B</tt> that depends on the result of another computation <tt>A</tt>, then the combined computation should yield <tt>Nothing</tt> whenever either <tt>A</tt> or <tt>B</tt> yield <tt>Nothing</tt> and the combined computation should yield the result of <tt>B</tt> applied to the result of <tt>A</tt> when both computations succeed.<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[index.html|Table of Contents]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[meet.html|Meet the Monads]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Meet the Monads<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introduction.html|Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[class.html|Doing it with class]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Meet the Monads =<br />
<br />
* [[#typeconstructors|Type constructors]]<br />
* [[#maybe|Maybe a monad]]<br />
* [[#list|A list is also a monad]]<br />
* [[#example1|An example]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<br />
<br />
We will use the <tt>Maybe</tt> type constructor throughout this chapter, so you should familiarize yourself with the definition and usage of [http://www.haskell.org/onlinelibrary/maybe.html <tt>Maybe</tt>] before continuing.<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 <tt>Maybe</tt>:<br />
<br />
<pre> data Maybe a = Nothing | Just a</pre><br />
<tt>Maybe</tt> is a type constructor and <tt>Nothing</tt> and <tt>Just</tt> are data constructors. You can construct a data value by applying the <tt>Just</tt> data constructor to a value:<br />
<br />
<pre> country = Just &quot;China&quot;</pre><br />
In the same way, you can construct a type by applying the <tt>Maybe</tt> type constructor to a type:<br />
<br />
<pre> lookupAge :: DB -&gt; String -&gt; Maybe Int</pre><br />
Polymorphic types are like containers that are capable of holding values of many different types. So <tt>Maybe Int</tt> can be thought of as a <tt>Maybe</tt> container holding an <tt>Int</tt> value (or <tt>Nothing</tt>) and <tt>Maybe String</tt> would be a <tt>Maybe</tt> container holding a <tt>String</tt> value (or <tt>Nothing</tt>). In Haskell, we can also make the type of the container polymorphic, so we could write &quot;<tt>m a</tt>&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 <tt>Maybe a</tt> is the type of all computations that may return a value or <tt>Nothing</tt>. In this way, we can talk about the properties of the container apart from any details of what the container might hold.<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 <tt>m</tt>), a function that builds values of that type (<tt>a -&gt; m a</tt>), and a function that combines values of that type with computations that produce values of that type to produce a new computation for values of that type (<tt>m a -&gt; (a -&gt; m b) -&gt; m b</tt>). Note that the container is the same, but the type of the contents of the container can change. It is customary to call the monad type constructor &quot;<tt>m</tt>&quot; when discussing monads in general. The function that builds values of that type is traditionally called &quot;<tt>return</tt>&quot; and the third function is known as &quot;bind&quot; but is written &quot;<tt>&gt;&gt;=</tt>&quot;. The signatures of the functions are:<br />
<br />
<pre>-- the type of monad m<br />
data m a = ... <br />
<br />
-- return is a type constructor that creates monad instances <br />
return :: a -&gt; 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 />
(&gt;&gt;=) :: m a -&gt; (a -&gt; m b) -&gt; m b</pre><br />
Roughly speaking, the monad type constructor defines a type of computation, the <tt>return</tt> function creates primitive values of that computation type and <tt>&gt;&gt;=</tt> combines computations of that type together to make more complex computations of that type. Using the container analogy, the type constructor <tt>m</tt> is a container that can hold different values. <tt>m a</tt> is a container holding a value of type <tt>a</tt>. The <tt>return</tt> function puts a value into a monad container. The <tt>&gt;&gt;=</tt> function takes the value from a monad container and passes it to a function to produce a monad container containing a new value, possibly of a different type. The <tt>&gt;&gt;=</tt> 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 <tt>mother</tt> and <tt>father</tt> functions. But since these are cloned sheep, they may not always have both a mother and a father!<br />
<br />
We would represent the possibility of not having a mother or father using the <tt>Maybe</tt> type constructor in our Haskell code:<br />
<br />
<pre>type Sheep = ...<br />
<br />
father :: Sheep -&gt; Maybe Sheep<br />
father = ...<br />
<br />
mother :: Sheep -&gt; Maybe Sheep<br />
mother = ...</pre><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 />
<pre>maternalGrandfather :: Sheep -&gt; Maybe Sheep<br />
maternalGrandfather s = case (mother s) of<br />
Nothing -&gt; Nothing<br />
Just m -&gt; father m</pre><br />
and so on for the other grandparent combinations.<br />
<br />
It gets even worse if we want to find great grandparents:<br />
<br />
<pre>mothersPaternalGrandfather :: Sheep -&gt; Maybe Sheep<br />
mothersPaternalGrandfather s = case (mother s) of<br />
Nothing -&gt; Nothing<br />
Just m -&gt; case (father m) of<br />
Nothing -&gt; Nothing<br />
Just gf -&gt; father gf</pre><br />
Aside from being ugly, unclear, and difficult to maintain, this is just too much work. It is clear that a <tt>Nothing</tt> value at any point in the computation will cause <tt>Nothing</tt> to be the final result, and it would be much nicer to implement this notion once in a single place and remove all of the explicit <tt>case</tt> testing scattered all over the code. This will make the code easier to write, easier to read and easier to change. So good programming style would have us create a combinator that captures the behavior we want:<br />
<br />
Code available in [[../examples/example1.hs|example1.hs]]<br />
<br />
<pre>-- comb is a combinator for sequencing operations that return Maybe<br />
comb :: Maybe a -&gt; (a -&gt; Maybe b) -&gt; 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 -&gt; Maybe Sheep<br />
mothersPaternalGrandfather s = (Just s) `comb` mother `comb` father `comb` father </pre><br />
The combinator is a huge success! The code is much cleaner and easier to write, understand and modify. Notice also that the <tt>comb</tt> function is entirely polymorphic — it is not specialized for <tt>Sheep</tt> in any way. In fact, ''the combinator captures a general strategy for combining computations that may fail to return a value.'' Thus, we can apply the same combinator to other computations that may fail to return a value, such as database queries or dictionary lookups.<br />
<br />
The happy outcome is that common sense programming practice has led us to create a monad without even realizing it. The <tt>Maybe</tt> type constructor along with the <tt>Just</tt> function (acts like <tt>return</tt>) and our combinator (acts like <tt>&gt;&gt;=</tt>) together form a simple monad for building computations which may not return a value. All that remains to make this monad truly useful is to make it conform to the monad framework built into the Haskell language. That is the subject of the next chapter.<br />
<br />
== A list is also a monad ==<br />
<br />
We have seen that the <tt>Maybe</tt> type constructor is a monad for building computations which may fail to return a value. You may be surprised to know that another common Haskell type constructor, <tt>[]</tt> (for building lists), is also a monad. The List monad allows us to build computations which can return 0, 1, or more values.<br />
<br />
The <tt>return</tt> function for lists simply creates a singleton list (<tt>return x = [x]</tt>). The binding operation for lists creates a new list containing the results of applying the function to all of the values in the original list (<tt>l &gt;&gt;= f = concatMap f l</tt>).<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 <tt>return</tt>, and a combinator function called <tt>bind</tt> or <tt>&gt;&gt;=</tt>. These three elements work together to encapsulate a strategy for combining computations to produce more complex computations.<br />
<br />
Using the <tt>Maybe</tt> type constructor, we saw how good programming practice led us to define a simple monad that could be used to build complex computations out of sequences of computations that could each fail to return a value. The resulting <tt>Maybe</tt> monad encapsulates a strategy for combining computations that may not return values. By codifying the strategy in a monad, we have achieved a degree of modularity and flexibility that is not present when the computations are combined in an ad hoc manner.<br />
<br />
We have also seen that another common Haskell type constructor, <tt>[]</tt>, is a monad. The List monad encapsulates a strategy for combining computations that can return 0, 1, or multiple values.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introduction.html|Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[class.html|Doing it with class]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Doing it with class<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[meet.html|Meet the Monads]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[laws.html|The monad laws]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Doing it with class =<br />
<br />
* [[#classes|Haskell type classes]]<br />
* [[#monad|The Monad class]]<br />
* [[#example2|Example continued]]<br />
* [[#donotation|Do notation]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 <tt>Monad</tt> class that defines the names and signatures of the two monad functions <tt>return</tt> and <tt>&gt;&gt;=</tt>. It is not strictly necessary to make your monads instances of the <tt>Monad</tt> class, but it is a good idea. Haskell has special support for <tt>Monad</tt> instances built into the language and making your monads instances of the <tt>Monad</tt> class will allow you to use these features to write cleaner and more elegant code. Also, making your monads instances of the <tt>Monad</tt> class communicates important information to others who read the code and failing to do so can cause you to use confusing and non-standard function names. It's easy to do and it has many benefits, so just do it!<br />
<br />
The standard <tt>Monad</tt> class definition in Haskell looks something like this:<br />
<br />
<pre>class Monad m where<br />
(&gt;&gt;=) :: m a -&gt; (a -&gt; m b) -&gt; m b<br />
return :: a -&gt; m a</pre><br />
== Example continued ==<br />
<br />
Continuing the [[meet.html#example1|previous example]], we will now see how the <tt>Maybe</tt> type constructor fits into the Haskell monad framework as an instance of the <tt>Monad</tt> class.<br />
<br />
Recall that our <tt>Maybe</tt> monad used the <tt>Just</tt> data constructor to fill the role of the monad <tt>return</tt> function and we built a simple combinator to fill the role of the monad <tt>&gt;&gt;=</tt> binding function. We can make its role as a monad explicit by declaring <tt>Maybe</tt> as an instance of the <tt>Monad</tt> class:<br />
<br />
<pre>instance Monad Maybe where<br />
Nothing &gt;&gt;= f = Nothing<br />
(Just x) &gt;&gt;= f = f x<br />
return = Just</pre><br />
Once we have defined <tt>Maybe</tt> as an instance of the Monad class, we can use the standard monad operators to build the complex computations:<br />
<br />
<pre>-- we can use monadic operations to build complicated sequences<br />
maternalGrandfather :: Sheep -&gt; Maybe Sheep<br />
maternalGrandfather s = (return s) &gt;&gt;= mother &gt;&gt;= father<br />
<br />
fathersMaternalGrandmother :: Sheep -&gt; Maybe Sheep<br />
fathersMaternalGrandmother s = (return s) &gt;&gt;= father &gt;&gt;= mother &gt;&gt;= mother </pre><br />
In Haskell, <tt>Maybe</tt> is defined as an instance of the <tt>Monad</tt> class in the standard prelude, so you don't need to do it yourself. The other monad we have seen so far, the list constructor, is also defined as an instance of the <tt>Monad</tt> class in the standard prelude.<br />
<br />
[[Image:info.png]] When writing functions that work with monads, try to make use of the <tt>Monad</tt> class instead of using a specific monad instance. A function of the type<br />
<br />
<pre>doSomething :: (Monad m) =&gt; a -&gt; m b</pre><br />
is much more flexible than one of the type<br />
<br />
<pre>doSomething :: a -&gt; Maybe b</pre><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 <tt>Maybe</tt> monad.<br />
<br />
== Do notation ==<br />
<br />
Using the standard monadic function names is good, but another advantage of membership in the <tt>Monad</tt> 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 <tt>Monad</tt> 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 <tt>&lt;-</tt> operator. Then using that variable in a subsequent monadic computation automatically performs the binding. The type of the expression to the right of the arrow is a monadic type <tt>m a</tt>. The expression to the left of the arrow is a pattern to be matched against the value ''inside'' the monad. <tt>(x:xs)</tt> would match against <tt>Maybe [1,2,3]</tt>, for example.<br />
<br />
Here is a sample of do notation using the <tt>Maybe</tt> monad:<br />
<br />
Code available in [[../examples/example2.hs|example2.hs]]<br />
<br />
<pre>-- we can also use do-notation to build complicated sequences<br />
mothersPaternalGrandfather :: Sheep -&gt; Maybe Sheep<br />
mothersPaternalGrandfather s = do m &lt;- mother s<br />
gf &lt;- father m<br />
father gf</pre><br />
Compare this to <tt>fathersMaternalGrandmother</tt> 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 />
<pre>mothersPaternalGrandfather s = do { m &lt;- mother s; gf &lt;- father m; father gf }</pre><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, <tt>x &lt;- expr1</tt>, becomes<br />
<br />
<pre>expr1 &gt;&gt;= \x -&gt;</pre><br />
and every expression without a variable assignment, <tt>expr2</tt> becomes<br />
<br />
<pre>expr2 &gt;&gt;= \_ -&gt;</pre><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 <tt>mothersPaternalGrandfather</tt> above would be translated to:<br />
<br />
<pre>mothersPaternalGrandfather s = mother s &gt;&gt;= \m -&gt;<br />
father m &gt;&gt;= \gf -&gt;<br />
father gf</pre><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 <tt>Monad</tt> class and supply definitions of the <tt>return</tt> and <tt>&gt;&gt;=</tt> (pronounced &quot;bind&quot;) functions for the monad.<br />
<br />
A monad that is an instance of the <tt>Monad</tt> 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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[meet.html|Meet the Monads]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[laws.html|The monad laws]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The monad laws<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[class.html|Doing it with class]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[exercises.html|Exercises]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The monad laws =<br />
<br />
* [[#laws|The three fundamental laws]]<br />
* [[#fail|Failure IS an option]]<br />
* [[#nowayout|No way out]]<br />
* [[#zero|Zero and Plus]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 <tt>Monad</tt> instances he declares obey they laws. Haskell's <tt>Monad</tt> class also includes some functions beyond the minimal complete definition that we have not seen yet. Finally, many monads obey additional laws beyond the standard monad laws, and there is an additional Haskell class to support these extended monads.<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 <tt>Monad</tt> class with the correct type signatures. To be a proper monad, the <tt>return</tt> and <tt>&gt;&gt;=</tt> functions must work together according to three laws:<br />
<br />
# <tt>(return x) &gt;&gt;= f == f x</tt><br />
# <tt>m &gt;&gt;= return == m</tt><br />
# <tt>(m &gt;&gt;= f) &gt;&gt;= g == m &gt;&gt;= (\x -&gt; f x &gt;&gt;= g)</tt><br />
<br />
The first law requires that <tt>return</tt> is a left-identity with respect to <tt>&gt;&gt;=</tt>. The second law requires that <tt>return</tt> is a right-identity with respect to <tt>&gt;&gt;=</tt>. The third law is a kind of associativity law for <tt>&gt;&gt;=</tt>. 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 <tt>Monad</tt> class. It is up to the programmer to ensure that any <tt>Monad</tt> instance he creates satisfies the monad laws.<br />
<br />
== Failure IS an option ==<br />
<br />
The definition of the <tt>Monad</tt> class given [[class.html#monad|earlier]] showed only the minimal complete definition. The full definition of the <tt>Monad</tt> class actually includes two additional functions: <tt>fail</tt> and <tt>&gt;&gt;</tt>.<br />
<br />
The default implementation of the <tt>fail</tt> function is:<br />
<br />
<pre>fail s = error s</pre><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 <tt>Maybe</tt> monad, for instance, defines <tt>fail</tt> as:<br />
<br />
<pre>fail _ = Nothing</pre><br />
so that <tt>fail</tt> returns an instance of the <tt>Maybe</tt> monad with meaningful behavior when it is bound with other functions in the <tt>Maybe</tt> monad.<br />
<br />
The <tt>fail</tt> function is not a required part of the mathematical definition of a monad, but it is included in the standard <tt>Monad</tt> class definition because of the role it plays in Haskell's do notation. The <tt>fail</tt> function is called whenever a pattern matching failure occurs in a do block:<br />
<br />
<pre>fn :: Int -&gt; Maybe [Int]<br />
fn idx = do let l = [Just [1,2,3], Nothing, Just [], Just [7..20]]<br />
(x:xs) &lt;- l!!idx -- a pattern match failure will call &quot;fail&quot;<br />
return xs</pre><br />
So in the code above, <tt>fn 0</tt> has the value <tt>Just [2,3]</tt>, but <tt>fn 1</tt> and <tt>fn 2</tt> both have the value <tt>Nothing</tt>.<br />
<br />
The <tt>&gt;&gt;</tt> function is a convenience operator that is used to bind a monadic computation that does not require input from the previous computation in the sequence. It is defined in terms of <tt>&gt;&gt;=</tt>:<br />
<br />
<pre>(&gt;&gt;) :: m a -&gt; m b -&gt; m b<br />
m &gt;&gt; k = m &gt;&gt;= (\_ -&gt; k)</pre><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 <tt>Monad</tt> class. That is not an accident. Nothing prevents the monad author from allowing it using functions specific to the monad. For instance, values can be extracted from the <tt>Maybe</tt> monad by pattern matching on <tt>Just x</tt> or using the <tt>fromJust</tt> function.<br />
<br />
By not requiring such a function, the Haskell <tt>Monad</tt> class allows the creation of one-way monads. One-way monads allow values to enter the monad through the <tt>return</tt> function (and sometimes the <tt>fail</tt> function) and they allow computations to be performed within the monad using the bind functions <tt>&gt;&gt;=</tt> and <tt>&gt;&gt;</tt>, but they do not allow values back out of the monad.<br />
<br />
The <tt>IO</tt> monad is a familiar example of a one-way monad in Haskell. Because you can't escape from the <tt>IO</tt> monad, it is impossible to write a function that does a computation in the <tt>IO</tt> monad but whose result type does not include the <tt>IO</tt> type constructor. This means that ''any'' function whose result type does not contain the <tt>IO</tt> type constructor is guaranteed not to use the <tt>IO</tt> monad. Other monads, such as <tt>List</tt> and <tt>Maybe</tt>, do allow values out of the monad. So it is possible to write functions which use these monads internally but return 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 <tt>readChar :: Char</tt>, because it needs to return a different character each time it is called, depending on the input from the user. It is an essential property of Haskell as a pure functional language that all functions return the same value when called twice with the same arguments. But it ''is'' ok to have an I/O function <tt>getChar :: IO Char</tt> in the <tt>IO</tt> monad, because it can only be used in a sequence within the one-way monad. There is no way to get rid of the <tt>IO</tt> type constructor in the signature of any function that uses it, so the <tt>IO</tt> type constructor acts as a kind of tag that identifies all functions that do I/O. Furthermore, such functions are only useful within the <tt>IO</tt> monad. So a 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 <tt>mzero</tt> and an operator <tt>mplus</tt> that obey four additional laws:<br />
<br />
# <tt>mzero &gt;&gt;= f == mzero</tt><br />
# <tt>m &gt;&gt;= (\x -&gt; mzero) == mzero</tt><br />
# <tt>mzero `mplus` m == m</tt><br />
# <tt>m `mplus` mzero == m</tt><br />
<br />
It is easy to remember the laws for <tt>mzero</tt> and <tt>mplus</tt> if you associate <tt>mzero</tt> with 0, <tt>mplus</tt> with +, and <tt>&gt;&gt;=</tt> with × in ordinary arithmetic.<br />
<br />
Monads which have a zero and a plus can be declared as instances of the <tt>MonadPlus</tt> class in Haskell:<br />
<br />
<pre>class (Monad m) =&gt; MonadPlus m where<br />
mzero :: m a<br />
mplus :: m a -&gt; m a -&gt; m a</pre><br />
Continuing to use the <tt>Maybe</tt> monad as an example, we see that the <tt>Maybe</tt> monad is an instance of <tt>MonadPlus</tt>:<br />
<br />
<pre>instance MonadPlus Maybe where<br />
mzero = Nothing<br />
Nothing `mplus` x = x<br />
x `mplus` _ = x</pre><br />
This identifies <tt>Nothing</tt> as the zero value and says that adding two <tt>Maybe</tt> values together gives the first value that is not <tt>Nothing</tt>. If both input values are <tt>Nothing</tt>, then the result of <tt>mplus</tt> is also <tt>Nothing</tt>.<br />
<br />
The List monad also has a zero and a plus. <tt>mzero</tt> is the empty list and <tt>mplus</tt> is the <tt>++</tt> operator.<br />
<br />
The <tt>mplus</tt> 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 <tt>Maybe</tt>'s <tt>mplus</tt> to define a function, <tt>parent s = (mother s) `mplus` (father s)</tt>, which would return a parent if there is one, and <tt>Nothing</tt> is the sheep has no parents at all. For a sheep with both parents, the function would return one or the other, depending on the exact definition of <tt>mplus</tt> in the <tt>Maybe</tt> monad.<br />
<br />
== Summary ==<br />
<br />
Instances of the <tt>Monad</tt> 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 <tt>return</tt> function is both a left and a right identity and that the binding operator is associative. Failure to satisfy these laws will result in monads that do not behave properly and may cause subtle problems when using do-notation.<br />
<br />
In addition to the <tt>return</tt> and <tt>&gt;&gt;=</tt> functions, the <tt>Monad</tt> class defines another function, <tt>fail</tt>. The <tt>fail</tt> function is not a technical requirement for inclusion as a monad, but it is often useful in practice and it is included in the <tt>Monad</tt> class because it is used in Haskell's 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 <tt>MonadPlus</tt> class for such monads which define the <tt>mzero</tt> value and the <tt>mplus</tt> operator.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[class.html|Doing it with class]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[exercises.html|Exercises]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Exercises<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[laws.html|The monad laws]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[monadfns.html|Monad support in Haskell]]</td><br />
</tr><br />
</tbody><br />
</table><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 />
<br />
-----<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 <tt>maternalGrandfather</tt>, <tt>fathersMaternalGrandmother</tt>, and <tt>mothersPaternalGrandfather</tt> functions in [[../examples/example2.hs|Example 2]] using the monadic operators <tt>return</tt> and <tt>&gt;&gt;=</tt>, 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 <tt>parent</tt> and <tt>grandparent</tt> with signature <tt>Sheep -&gt; Maybe Sheep</tt>. They should return one sheep selected from all sheep matching the description, or <tt>Nothing</tt> if there is no such sheep. Hint: the <tt>mplus</tt> operator is useful here.<br />
<br />
Click [[solution2.html|here]] to see the solution.<br />
<br />
== Exercise 3: Using the List monad ==<br />
<br />
Write functions <tt>parent</tt> and <tt>grandparent</tt> with signature <tt>Sheep -&gt; [Sheep]</tt>. They should return all sheep matching the description, or the empty list if there is no such sheep. Hint: the <tt>mplus</tt> operator in the List monad is useful here. Also the <tt>maybeToList</tt> function in the <tt>Maybe</tt> module can be used to convert a value from the Maybe monad to the List monad.<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 <tt>(Monad m) =&gt;</tt>, <tt>(MonadPlus m) =&gt;</tt>, etc. class constraints.<br />
<br />
Write functions <tt>parent</tt> and <tt>grandparent</tt> with signature <tt>(MonadPlus m) =&gt; Sheep -&gt; m Sheep</tt>. They should be useful in both the Maybe and List monads. How does the functions' behavior differ when used with the List monad versus the Maybe monad? If you need to review the use of type classes and class constraints in Haskell, look [http://www.haskell.org/tutorial/classes.html here].<br />
<br />
Click [[solution4.html|here]] to see the solution.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[laws.html|The monad laws]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[monadfns.html|Monad support in Haskell]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Monad support in Haskell<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[exercises.html|Exercises]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[introII.html|Part II - Introduction]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Monad support in Haskell =<br />
<br />
* [[#prelude|In the standard prelude]]<br />
* [[#monad|In the Monad module]]<br />
* [[#summary|Summary]]<br />
<br />
<br />
-----<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 <tt>Monad</tt> class as well as a few auxilliary functions for working with monadic data types.<br />
<br />
=== The <tt>Monad</tt> class ===<br />
<br />
We have seen the <tt>Monad</tt> class before:<br />
<br />
<pre>class Monad m where<br />
(&gt;&gt;=) :: m a -&gt; (a -&gt; m b) -&gt; m b<br />
(&gt;&gt;) :: m a -&gt; m b -&gt; m b<br />
return :: a -&gt; m a<br />
fail :: String -&gt; m a<br />
<br />
-- Minimal complete definition:<br />
-- (&gt;&gt;=), return<br />
m &gt;&gt; k = m &gt;&gt;= \_ -&gt; k<br />
fail s = error s</pre><br />
=== The sequencing functions ===<br />
<br />
The <tt>sequence</tt> function takes a list of monadic computations, executes each one in turn and returns a list of the results. If any of the computations fail, then the whole function fails:<br />
<br />
<pre>sequence :: Monad m =&gt; [m a] -&gt; m [a] <br />
sequence = foldr mcons (return [])<br />
where mcons p q = p &gt;&gt;= \x -&gt; q &gt;&gt;= \y -&gt; return (x:y)</pre><br />
The <tt>sequence_</tt> function (notice the underscore) has the same behavior as <tt>sequence</tt> but does not return a list of results. It is useful when only the side-effects of the monadic computations are important.<br />
<br />
<pre>sequence_ :: Monad m =&gt; [m a] -&gt; m () <br />
sequence_ = foldr (&gt;&gt;) (return ())</pre><br />
=== The mapping functions ===<br />
<br />
The <tt>mapM</tt> function maps a monadic computation over a list of values and returns a list of the results. It is defined in terms of the list <tt>map</tt> function and the <tt>sequence</tt> function above:<br />
<br />
<pre>mapM :: Monad m =&gt; (a -&gt; m b) -&gt; [a] -&gt; m [b] <br />
mapM f as = sequence (map f as)</pre><br />
There is also a version with an underscore, <tt>mapM_</tt> which is defined using sequence_. <tt>mapM_</tt> operates the same as <tt>mapM</tt>, but it doesn't return the list of values. It is useful when only the side-effects of the monadic computation are important.<br />
<br />
<pre>mapM_ :: Monad m =&gt; (a -&gt; m b) -&gt; [a] -&gt; m () <br />
mapM_ f as = sequence_ (map f as)</pre><br />
As a simple example of the use the mapping functions, a <tt>putString</tt> function for the <tt>IO</tt> monad could be defined as:<br />
<br />
<pre>putString :: [Char] -&gt; IO ()<br />
putString s = mapM_ putChar s</pre><br />
<tt>mapM</tt> can be used within a do block in a manner similar to the way the <tt>map</tt> function is normally used on lists. This is a common pattern with monads — a version of a function for use within a monad (i.e., intended for binding) will have a signature similar to the non-monadic version but the function outputs will be within the monad:<br />
<br />
<pre>-- compare the non-monadic and monadic signatures<br />
map :: (a -&gt; b) -&gt; [a] -&gt; [b]<br />
mapM :: Monad m =&gt; (a -&gt; m b) -&gt; [a] -&gt; m [b] </pre><br />
=== The reverse binder function (<tt>=&lt;&lt;</tt>) ===<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;<tt>&gt;&gt;=</tt>&quot;, the reverse binding function is called &quot;<tt>=&lt;&lt;</tt>&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 />
<pre>(=&lt;&lt;) :: Monad m =&gt; (a -&gt; m b) -&gt; m a -&gt; m b<br />
f =&lt;&lt; x = x &gt;&gt;= f</pre><br />
== In the Monad module ==<br />
<br />
The <tt>Monad</tt> module in the standard Haskell 98 libraries exports a number of facilities for more advanced monadic operations. To access these facilities, simply <tt>import Monad</tt> in your Haskell program.<br />
<br />
Not all of the function in the <tt>Monad</tt> module are discussed here, but you are encouraged to [http://www.haskell.org/onlinelibrary/monad.html explore the module for yourself] when you feel you are ready to see some of the more esoteric monad functions.<br />
<br />
=== The <tt>MonadPlus</tt> class ===<br />
<br />
The <tt>Monad</tt> module defines the <tt>MonadPlus</tt> class for monads with a zero element and a plus operator:<br />
<br />
<pre>class Monad m =&gt; MonadPlus m where<br />
mzero :: m a<br />
mplus :: m a -&gt; m a -&gt; m a</pre><br />
=== Monadic versions of list functions ===<br />
<br />
Several functions are provided which generalize standard list-processing functions to monads. The <tt>mapM</tt> functions are exported in the standard prelude and were described above.<br />
<br />
<tt>foldM</tt> is a monadic version of <tt>foldl</tt> in which monadic computations built from a list are bound left-to-right. The definition is:<br />
<br />
<pre>foldM :: (Monad m) =&gt; (a -&gt; b -&gt; m a) -&gt; a -&gt; [b] -&gt; m a<br />
foldM f a [] = return a<br />
foldM f a (x:xs) = f a x &gt;&gt;= \y -&gt; foldM f y xs</pre><br />
but it is easier to understand the operation of <tt>foldM</tt> if you consider its effect in terms of a do block:<br />
<br />
<pre>-- this is not valid Haskell code, it is just for illustration<br />
foldM f a1 [x1,x2,...,xn] = do a2 &lt;- f a1 x1<br />
a3 &lt;- f a2 x2<br />
...<br />
f an xn</pre><br />
Right-to-left binding is achieved by reversing the input list before calling <tt>foldM</tt>.<br />
<br />
We can use <tt>foldM</tt> to create a more poweful query function in our sheep cloning example:<br />
<br />
Code available in [[../examples/example3.hs|example3.hs]]<br />
<br />
<pre>-- traceFamily is a generic function to find an ancestor<br />
traceFamily :: Sheep -&gt; [ (Sheep -&gt; Maybe Sheep) ] -&gt; 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]</pre><br />
The <tt>traceFamily</tt> function uses <tt>foldM</tt> to create a simple way to trace back in the family tree to any depth and in any pattern. In fact, it is probably clearer to write &quot;<tt>traceFamily s [father, mother]</tt>&quot; than it is to use the <tt>paternalGrandmother</tt> function!<br />
<br />
A more typical use of <tt>foldM</tt> is within a do block:<br />
<br />
Code available in [[../examples/example4.hs|example4.hs]]<br />
<br />
<pre>-- 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 -&gt; Entry -&gt; 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 -&gt; Handle -&gt; IO Dict<br />
addDataFromFile dict hdl = do contents &lt;- hGetContents hdl<br />
entries &lt;- 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 &lt;- getArgs<br />
handles &lt;- mapM openForReading files<br />
dict &lt;- foldM addDataFromFile emptyFM handles<br />
print (fmToList dict)</pre><br />
The <tt>filterM</tt> function works like the list <tt>filter</tt> function inside of a monad. It takes a predicate function which returns a Boolean value in the monad and a list of values. It returns, inside the monad, a list of those values for which the predicate was True.<br />
<br />
<pre>filterM :: Monad m =&gt; (a -&gt; m Bool) -&gt; [a] -&gt; m [a]<br />
filterM p [] = return []<br />
filterM p (x:xs) = do b &lt;- p x<br />
ys &lt;- filterM p xs<br />
return (if b then (x:ys) else ys)</pre><br />
Here is an example showing how <tt>filterM</tt> can be used within the <tt>IO</tt> monad to select only the directories from a list:<br />
<br />
Code available in [[../examples/example5.hs|example5.hs]]<br />
<br />
<pre>import Monad<br />
import Directory<br />
import System<br />
<br />
-- NOTE: doesDirectoryExist has type FilePath -&gt; IO Bool<br />
<br />
-- this program prints only the directories named on the command line<br />
main :: IO ()<br />
main = do names &lt;- getArgs<br />
dirs &lt;- filterM doesDirectoryExist names<br />
mapM_ putStrLn dirs</pre><br />
<tt>zipWithM</tt> is a monadic version of the <tt>zipWith</tt> function on lists. <tt>zipWithM_</tt> behaves the same but discards the output of the function. It is useful when only the side-effects of the monadic computation matter.<br />
<br />
<pre>zipWithM ::(Monad m) =&gt; (a -&gt; b -&gt; m c) -&gt; [a] -&gt; [b] -&gt; m [c]<br />
zipWithM f xs ys = sequence (zipWith f xs ys)<br />
<br />
zipWithM_ ::(Monad m) =&gt; (a -&gt; b -&gt; m c) -&gt; [a] -&gt; [b] -&gt; m ()<br />
zipWithM_ f xs ys = sequence_ (zipWith f xs ys)</pre><br />
=== Conditional monadic computations ===<br />
<br />
There are two functions provided for conditionally executing monadic computations. The <tt>when</tt> function takes a boolean argument and a monadic computation with unit &quot;()&quot; type and performs the computation only when the boolean argument is <tt>True</tt>. The <tt>unless</tt> function does the same, except that it performs the computation ''unless'' the boolean argument is <tt>True</tt>.<br />
<br />
<pre>when :: (Monad m) =&gt; Bool -&gt; m () -&gt; m ()<br />
when p s = if p then s else return ()<br />
<br />
unless :: (Monad m) =&gt; Bool -&gt; m () -&gt; m ()<br />
unless p s = when (not p) s</pre><br />
=== <tt>ap</tt> 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 <tt>liftM</tt>, which lifts a function of a single argument into a monad.<br />
<br />
<pre>liftM :: (Monad m) =&gt; (a -&gt; b) -&gt; (m a -&gt; m b)<br />
liftM f = \a -&gt; do { a' &lt;- a; return (f a') }</pre><br />
Lifting operators are also provided for functions with more arguments. <tt>liftM2</tt> lifts functions of two arguments:<br />
<br />
<pre>liftM2 :: (Monad m) =&gt; (a -&gt; b -&gt; c) -&gt; (m a -&gt; m b -&gt; m c)<br />
liftM2 f = \a b -&gt; do { a' &lt;- a; b' &lt;- b; return (f a' b') }</pre><br />
The same pattern is applied to give the definitions to lift functions of more arguments. Functions up to <tt>liftM5</tt> are defined in the <tt>Monad</tt> module.<br />
<br />
To see how the lifting operators allow more concise code, consider a computation in the <tt>Maybe</tt> monad in which you want to use a function <tt>swapNames::String -&gt; String</tt>. You could do:<br />
<br />
<pre>getName :: String -&gt; Maybe String<br />
getName name = do let db = [(&quot;John&quot;, &quot;Smith, John&quot;), (&quot;Mike&quot;, &quot;Caine, Michael&quot;)]<br />
tempName &lt;- lookup name db<br />
return (swapNames tempName)</pre><br />
But making use of the <tt>liftM</tt> function, we can use <tt>liftM swapNames</tt> as a function of type <tt>Maybe String -&gt; Maybe String</tt>:<br />
<br />
Code available in [[../examples/example6.hs|example6.hs]]<br />
<br />
<pre>getName :: String -&gt; Maybe String<br />
getName name = do let db = [(&quot;John&quot;, &quot;Smith, John&quot;), (&quot;Mike&quot;, &quot;Caine, Michael&quot;)]<br />
liftM swapNames (lookup name db)</pre><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 <tt>&gt;&gt;=</tt>). Imagine how you might implement this function without lifting the operator:<br />
<br />
Code available in [[../examples/example7.hs|example7.hs]]<br />
<br />
<pre>-- 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 -&gt; a -&gt; a) -&gt; [[a]] -&gt; [a]<br />
allCombinations fn [] = []<br />
allCombinations fn (l:ls) = foldl (liftM2 fn) l ls</pre><br />
There is a related function called <tt>ap</tt> that is sometimes more convenient to use than the lifting functions. <tt>ap</tt> is simply the function application operator (<tt>$</tt>) lifted into the monad:<br />
<br />
<pre>ap :: (Monad m) =&gt; m (a -&gt; b) -&gt; m a -&gt; m b<br />
ap = liftM2 ($)</pre><br />
Note that <tt>liftM2 f x y</tt> is equivalent to <tt>return f `ap` x `ap` y</tt>, and so on for functions of more arguments. <tt>ap</tt> is useful when working with higher-order functions and monads.<br />
<br />
The effect of <tt>ap</tt> depends on the strategy of the monad in which it is used. So for example <tt>[(*2),(+3)] `ap` [0,1,2]</tt> is equal to <tt>[0,2,4,3,4,5]</tt> and <tt>(Just (*2)) `ap` (Just 3)</tt> is <tt>Just 6</tt>. Here is a simple example that shows how <tt>ap</tt> can be useful when doing higher-order computations:<br />
<br />
Code available in [[../examples/example8.hs|example8.hs]]<br />
<br />
<pre>-- lookup the commands and fold ap into the command list to<br />
-- compute a result.<br />
main :: IO ()<br />
main = do let fns = [(&quot;double&quot;,(2*)), (&quot;halve&quot;,(`div`2)),<br />
(&quot;square&quot;,(\x-&gt;x*x)), (&quot;negate&quot;, negate),<br />
(&quot;incr&quot;,(+1)), (&quot;decr&quot;,(+(-1)))<br />
]<br />
args &lt;- getArgs<br />
let val = read (args!!0)<br />
cmds = map ((flip lookup) fns) (words (args!!1))<br />
print $ foldl (flip ap) (Just val) cmds</pre><br />
=== Functions for use with <tt>MonadPlus</tt> ===<br />
<br />
There are two functions in the <tt>Monad</tt> module that are used with monads that have a zero and a plus. The first function is <tt>msum</tt>, which is analogous to the <tt>sum</tt> function on lists of integers. <tt>msum</tt> operates on lists of monadic values and folds the <tt>mplus</tt> operator into the list using the <tt>mzero</tt> element as the initial value:<br />
<br />
<pre>msum :: MonadPlus m =&gt; [m a] -&gt; m a<br />
msum xs = foldr mplus mzero xs</pre><br />
In the List monad, <tt>msum</tt> is equivalent to <tt>concat</tt>. In the <tt>Maybe</tt> monad, <tt>msum</tt> returns the first non-<tt>Nothing</tt> value from a list. Likewise, the behavior in other monads will depend on the exact nature of their <tt>mzero</tt> and <tt>mplus</tt> definitions.<br />
<br />
<tt>msum</tt> allows many recursive functions and folds to be expressed more concisely. In the <tt>Maybe</tt> monad, for example, we can write:<br />
<br />
Code available in [[../examples/example9.hs|example9.hs]]<br />
<br />
<pre>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 -&gt; EnvironmentStack -&gt; Maybe Value<br />
lookupVar var stack = msum $ map (lookup var) stack</pre><br />
instead of:<br />
<br />
<pre>lookupVar :: Variable -&gt; EnvironmentStack -&gt; Maybe Value<br />
lookupVar var [] = Nothing<br />
lookupVar var (e:es) = let val = lookup var e<br />
in maybe (lookupVar var es) Just val</pre><br />
The second function for use with monads with a zero and a plus is the <tt>guard</tt> function:<br />
<br />
<pre>guard :: MonadPlus m =&gt; Bool -&gt; m ()<br />
guard p = if p then return () else mzero</pre><br />
The trick to understanding this function is to recall the law for monads with zero and plus that states <tt>mzero &gt;&gt;= f == mzero</tt>. So, placing a <tt>guard</tt> function in a sequence of monadic operations will force any execution in which the guard is <tt>False</tt> to be <tt>mzero</tt>. This is similar to the way that guard predicates in a list comprehension cause values that fail the predicate to become <tt>[]</tt>.<br />
<br />
Here is an example demonstrating the use of the <tt>guard</tt> function in the <tt>Maybe</tt> monad.<br />
<br />
Code available in [[../examples/example10.hs|example10.hs]]<br />
<br />
<pre>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 -&gt; DB -&gt; [Record]<br />
getYoungerThan limit db = mapMaybe (\r -&gt; do { guard (age r &lt; limit); return r }) db</pre><br />
== Summary ==<br />
<br />
Haskell provides a number of functions which are useful for working with monads in the standard libraries. The <tt>Monad</tt> class and most common monad functions are in the standard prelude. The <tt>MonadPlus</tt> class and less commonly-used (but still very useful!) functions are defined in the <tt>Monad</tt> module. Many other types in the Haskell libraries are declared as instances of <tt>Monad</tt> and <tt>MonadPlus</tt> in their respective modules.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[exercises.html|Exercises]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[introII.html|Part II - Introduction]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Part II - Introduction<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[monadfns.html|Monad support in Haskell]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[identitymonad.html|The Identity monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
<br />
-----<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 <tt>&gt;&gt;=</tt></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"><tt>Nothing</tt> input gives <tt>Nothing</tt> output<br /><br />
<tt>Just x</tt> input uses <tt>x</tt> 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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[monadfns.html|Monad support in Haskell]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[identitymonad.html|The Identity monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Identity monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introII.html|Part II - Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[maybemonad.html|The Maybe monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Identity monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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. <tt>Identity x &gt;&gt;= f == Identity (f x)</tt><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 />
<pre>newtype Identity a = Identity { runIdentity :: a } <br />
<br />
instance Monad Identity where<br />
return a = Identity a -- i.e. return = id <br />
(Identity x) &gt;&gt;= f = f x -- i.e. x &gt;&gt;= f = f x </pre><br />
The <tt>runIdentity</tt> label is used in the type definition because it follows a style of monad definition that explicitly represents monad values as computations. In this style, a monadic computation is built up using the monadic operators and then the value of the computation is extracted using the <tt>run******</tt> function. Because the Identity monad does not do any computation, its definition is trivial. For a better example of this style of monad, see the [[statemonad.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 />
<pre>-- derive the State monad using the StateT monad transformer<br />
type State s a = StateT s Identity a</pre><br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introII.html|Part II - Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[maybemonad.html|The Maybe monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Maybe monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[identitymonad.html|The Identity monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[errormonad.html|The Error monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Maybe monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<br />
<br />
== Overview ==<br />
<br />
Computation type:<br />
<br />
Computations which may return <tt>Nothing</tt><br />
<br />
Binding strategy:<br />
<br />
<tt>Nothing</tt> 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 <tt>Nothing</tt>. Complex database queries or dictionary lookups are good examples.<br />
<br />
Zero and plus:<br />
<br />
<tt>Nothing</tt> is the zero. The plus operation returns the first non-<tt>Nothing</tt> value or <tt>Nothing</tt> is both inputs are <tt>Nothing</tt>.<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 <tt>Nothing</tt> by ending the chain early if any step produces <tt>Nothing</tt> as output. It is useful when a computation entails a sequence of steps that depend on one another, and in which some steps may fail to return a value.<br />
<br />
[[Image:info.png]] If you ever find yourself writing code like this:<br /><br />
<br />
<br />
<pre>case ... of<br />
Nothing -&gt; Nothing<br />
Just x -&gt; case ... of<br />
Nothing -&gt; Nothing<br />
Just y -&gt; ...</pre><br />
you should consider using the monadic properties of <tt>Maybe</tt> to improve the code.<br />
<br />
== Definition ==<br />
<br />
<pre>data Maybe a = Nothing | Just a<br />
<br />
instance Monad Maybe where<br />
return = Just<br />
fail = Nothing<br />
Nothing &gt;&gt;= f = Nothing<br />
(Just x) &gt;&gt;= f = f x<br />
<br />
instance MonadPlus Maybe where<br />
mzero = Nothing<br />
Nothing `mplus` x = x<br />
x `mplus` _ = x</pre><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 />
<pre>data MailPref = HTML | Plain<br />
data MailSystem = ...<br />
<br />
getMailPrefs :: MailSystem -&gt; String -&gt; Maybe MailPref<br />
getMailPrefs sys name =<br />
do let nameDB = fullNameDB sys<br />
nickDB = nickNameDB sys<br />
prefDB = prefsDB sys<br />
addr &lt;- (lookup name nameDB) `mplus` (lookup name nickDB)<br />
lookup addr prefDB</pre><br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[identitymonad.html|The Identity monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[errormonad.html|The Error monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Error monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[maybemonad.html|The Maybe monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[listmonad.html|The List monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Error monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 <tt>MonadError</tt>] class is parameterized over the type of error information and the monad type constructor. It is common to use <tt>Either String</tt> as the monad type constructor for an error monad in which error descriptions take the form of strings. In that case and many other common cases the resulting monad is already defined as an instance of the <tt>MonadError</tt> class. You can also define your own error type and/or use a monad type constructor other than <tt>Either String</tt> or <tt>Either IOError</tt>. In these cases you will have to explicitly define instances of the <tt>Error</tt> and/or <tt>MonadError</tt> classes.<br />
<br />
== Definition ==<br />
<br />
The definition of the <tt>MonadError</tt> 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 <tt>MonadError</tt> class.<br />
<br />
<pre>class Error a where<br />
noMsg :: a<br />
strMsg :: String -&gt; a<br />
<br />
class (Monad m) =&gt; MonadError e m | m -&gt; e where<br />
throwError :: e -&gt; m a<br />
catchError :: m a -&gt; (e -&gt; m a) -&gt; m a</pre><br />
<tt>throwError</tt> is used within a monadic computation to begin exception processing. <tt>catchError</tt> provides a handler function to handle previous errors and return to normal execution. A common idiom is:<br />
<br />
<pre>do { action1; action2; action3 } `catchError` handler </pre><br />
where the <tt>action</tt> functions can call <tt>throwError</tt>. Note that <tt>handler</tt> and the do-block must have the same return type.<br />
<br />
The definition of the <tt>Either e</tt> type constructor as an instance of the <tt>MonadError</tt> class is straightforward. Following convention, <tt>Left</tt> is used for error values and <tt>Right</tt> is used for non-error (right) values.<br />
<br />
<br />
<br />
<pre>instance MonadError (Either e) where <br />
throwError = Left <br />
(Left e) `catchError` handler = handler e <br />
a `catchError` _ = a </pre><br />
== Example ==<br />
<br />
Here is an example that demonstrates the use of a custom <tt>Error</tt> data type with the <tt>ErrorMonad</tt>'s <tt>throwError</tt> and <tt>catchError</tt> exception mechanism. The example attempts to parse hexadecimal numbers and throws an exception if an invalid character is encountered. We use a custom <tt>Error</tt> data type to record the location of the parse error. The exception is caught by a calling function and handled by printing an informative error message.<br />
<br />
Code available in [[../examples/example12.hs|example12.hs]]<br />
<br />
<pre>-- 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 &quot;Parse Error&quot;<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 -&gt; Int -&gt; ParseMonad Integer<br />
parseHexDigit c idx = if isHexDigit c then<br />
return (toInteger (digitToInt c))<br />
else<br />
throwError (Err idx (&quot;Invalid character '&quot; ++ [c] ++ &quot;'&quot;))<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 -&gt; ParseMonad Integer<br />
parseHex s = parseHex' s 0 1<br />
where parseHex' [] val _ = return val<br />
parseHex' (c:cs) val idx = do d &lt;- 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 -&gt; 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 -&gt; String<br />
convert s = let (Right str) = do {n &lt;- parseHex s; toString n} `catchError` printError<br />
in str<br />
where printError e = return $ &quot;At index &quot; ++ (show (location e)) ++ &quot;:&quot; ++ (reason e)</pre><br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[maybemonad.html|The Maybe monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[listmonad.html|The List monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The List monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[errormonad.html|The Error monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[iomonad.html|The IO monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The List monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<tt>[]</tt> is the zero and <tt>++</tt> is the plus operation.<br />
<br />
Example type:<br />
<br />
<tt>[a]</tt><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 />
<pre>instance Monad [] where<br />
m &gt;&gt;= f = concatMap f m<br />
return x = [x]<br />
fail s = []<br />
<br />
instance MonadPlus [] where<br />
mzero = []<br />
mplus = (++)</pre><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 />
<pre>-- 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 -&gt; Char -&gt; [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 -&gt; Char -&gt; [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 -&gt; Char -&gt; [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 -&gt; Char -&gt; [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 -&gt; [Parsed]<br />
parseArg s = do init &lt;- (return (Hex 0)) `mplus` (return (Digit 0)) `mplus` (return (Word &quot;&quot;))<br />
foldM parse init s</pre><br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[errormonad.html|The Error monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[iomonad.html|The IO monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The IO monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[listmonad.html|The List monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[statemonad.html|The State monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The IO monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 <tt>main</tt> function must have type <tt>IO ()</tt>, 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 <tt>IO</tt> module do not perform I/O themselves. They return I/O actions, which describe an I/O operation to be performed. The I/O actions are combined within the IO monad (in a purely functional manner) to create more complex I/O actions, resulting in the final I/O action that is the <tt>main</tt> value of the program.<br />
<br />
The standard prelude and the [http://www.haskell.org/onlinelibrary/io.html <tt>IO</tt> module] define many functions that can be used within the IO monad and any Haskell programmer will undoubtedly be familiar with some of them. This tutorial will only discuss the monadic aspects of the IO monad, not the full range of functions available to perform I/O.<br />
<br />
The <tt>IO</tt> type constructor is a member of the <tt>Monad</tt> class and the <tt>MonadError</tt> class, where errors are of the type <tt>IOError</tt>. <tt>fail</tt> is defined to throw an error built from the string argument. Within the <tt>IO</tt> monad you can use the exception mechanisms from the <tt>Control.Monad.Error</tt> module in the Monad Template Library if you import the module. The same mechanisms have alternative names exported by the <tt>IO</tt> module: <tt>ioError</tt> and <tt>catch</tt>.<br />
<br />
<pre>instance Monad IO where<br />
return a = ... -- function from a -&gt; IO a<br />
m &gt;&gt;= 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 -&gt; IO a<br />
ioError = ...<br />
<br />
userError :: String -&gt; IOError<br />
userError = ...<br />
<br />
catch :: IO a -&gt; (IOError -&gt; IO a) -&gt; IO a <br />
catch = ...<br />
<br />
try :: IO a -&gt; IO (Either IOError a)<br />
try f = catch (do r &lt;- f<br />
return (Right r))<br />
(return . Left)</pre><br />
The <tt>IO</tt> monad is incorporated into the Monad Template Library framework as an instance of the <tt>MonadError</tt> class.<br />
<br />
<pre>instance Error IOError where<br />
...<br />
<br />
instance MonadError IO where<br />
throwError = ioError<br />
catchError = catch</pre><br />
The <tt>IO</tt> module exports a convenience function called <tt>try</tt> that executes an I/O action and returns <tt>Right result</tt> if the action succeeded or <tt>Left IOError</tt> if an I/O error was caught.<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 <tt>MonadError</tt> class with the <tt>IO</tt> monad.<br />
<br />
Code available in [[../examples/example14.hs|example14.hs]]<br />
<br />
<pre>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 -&gt; String -&gt; Char -&gt; 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 -&gt; String -&gt; String -&gt; String<br />
translateString set1 set2 str = map (translate set1 set2) str<br />
<br />
usage :: IOError -&gt; IO ()<br />
usage e = do putStrLn &quot;Usage: ex14 set1 set2&quot;<br />
putStrLn &quot;Translates characters in set1 on stdin to the corresponding&quot;<br />
putStrLn &quot;characters from set2 and writes the translation to stdout.&quot;<br />
<br />
-- translates stdin to stdout based on commandline arguments<br />
main :: IO ()<br />
main = (do [set1,set2] &lt;- getArgs<br />
contents &lt;- hGetContents stdin<br />
putStr $ translateString set1 set2 contents)<br />
`catchError` usage</pre><br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[listmonad.html|The List monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[statemonad.html|The State monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The State monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[iomonad.html|The IO monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[readermonad.html|The Reader monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The State monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<pre>data MyType = MT Int Bool Char Int deriving Show<br />
<br />
makeRandomValue :: StdGen -&gt; (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)</pre><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 />
<pre>newtype State s a = State { runState :: (s -&gt; (a,s)) } <br />
<br />
instance Monad (State s) where <br />
return a = State $ \s -&gt; (a,s)<br />
(State x) &gt;&gt;= f = State $ \s -&gt; let (v,s') = x s in runState (f v) s' </pre><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: <tt>State s a</tt> is the type of a value of type <tt>a</tt> inside the State monad with state of type <tt>s</tt>.<br />
<br />
The type constructor <tt>State s</tt> is an instance of the <tt>Monad</tt> class. The <tt>return</tt> function simply creates a state transition function which sets the value but leaves the state unchanged. The binding operator creates a state transition function that applies its right-hand argument to the value and new state from its left-hand argument.<br />
<br />
<pre>class MonadState m s | m -&gt; s where <br />
get :: m s<br />
put :: s -&gt; m ()<br />
<br />
instance MonadState (State s) s where <br />
get = State $ \s -&gt; (s,s) <br />
put s = State $ \_ -&gt; ((),s) </pre><br />
The <tt>MonadState</tt> class provides a standard but very simple interface for State monads. The <tt>get</tt> function retrieves the state by copying it as the value. The <tt>put</tt> function sets the state of the monad and does not yield a value.<br />
<br />
There are many additional functions provide which perform more complex computations built on top of <tt>get</tt> and put. The most useful one is <tt>gets</tt> which retrieves a function of the state. The others are listed in the [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.State.html documentation] for the State monad library.<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 />
<pre>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) =&gt; State StdGen a<br />
getAny = do g &lt;- get<br />
(x,g') &lt;- 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) =&gt; (a,a) -&gt; State StdGen a<br />
getOne bounds = do g &lt;- get<br />
(x,g') &lt;- 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 -&gt; (MyType, StdGen)<br />
makeRandomValueST = runState (do n &lt;- getOne (1,100)<br />
b &lt;- getAny<br />
c &lt;- getOne ('a','z')<br />
m &lt;- getOne (-n,n)<br />
return (MT n b c m))</pre><br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[iomonad.html|The IO monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[readermonad.html|The Reader monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Reader monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[statemonad.html|The State monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[writermonad.html|The Writer monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Reader monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 />
<pre>newtype Reader e a = Reader { runReader :: (e -&gt; a) }<br />
<br />
instance Monad (Reader e) where <br />
return a = Reader $ \e -&gt; a <br />
(Reader r) &gt;&gt;= f = Reader $ \e -&gt; f (r e) e </pre><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 <tt>(runReader reader)</tt> to an environment value.<br />
<br />
The <tt>return</tt> function creates a <tt>Reader</tt> that ignores the environment and produces the given value. The binding operator produces a <tt>Reader</tt> that uses the environment to extract the value its left-hand side and then applies the bound function to that value in the same environment.<br />
<br />
<pre>class MonadReader e m | m -&gt; e where <br />
ask :: m e<br />
local :: (e -&gt; e) -&gt; m a -&gt; m a <br />
<br />
instance MonadReader (Reader e) where <br />
ask = Reader id <br />
local f c = Reader $ \e -&gt; runReader c (f e) <br />
<br />
asks :: (MonadReader e m) =&gt; (e -&gt; a) -&gt; m a <br />
asks sel = ask &gt;&gt;= return . sel</pre><br />
The <tt>MonadReader</tt> class provides a number of convenience functions that are very useful when working with a Reader monad. The <tt>ask</tt> function retrieves the environment and the <tt>local</tt> function executes a computation in a modified environment. The <tt>asks</tt> function is a convenience function that retrieves a function of the current environment, and is typically used with a selector or lookup function.<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 <tt>asks</tt> function to lookup the value of the variable. When a template is included with new variable definitions, we can use the <tt>local</tt> function to resolve the template in a modified environment that contains the additional variable bindings.<br />
<br />
Code available in [[../examples/example16.hs|example16.hs]]<br />
<br />
<pre>-- 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 -&gt; Environment -&gt; Maybe String<br />
lookupVar name env = lookup name (variables env)<br />
<br />
-- lookup a template from the environment<br />
lookupTemplate :: String -&gt; Environment -&gt; 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)] -&gt; Environment -&gt; Environment<br />
addDefs defs env = env {variables = defs ++ (variables env)}<br />
<br />
-- resolve a Definition and produce a (name,value) pair<br />
resolveDef :: Definition -&gt; Reader Environment (String,String)<br />
resolveDef (D t d) = do name &lt;- resolve t<br />
value &lt;- resolve d<br />
return (name,value)<br />
<br />
-- resolve a template into a string<br />
resolve :: Template -&gt; Reader Environment (String)<br />
resolve (T s) = return s<br />
resolve (V t) = do varName &lt;- resolve t<br />
varValue &lt;- asks (lookupVar varName)<br />
return $ maybe &quot;&quot; id varValue<br />
resolve (Q t) = do tmplName &lt;- resolve t<br />
body &lt;- asks (lookupTemplate tmplName)<br />
return $ maybe &quot;&quot; show body <br />
resolve (I t ds) = do tmplName &lt;- resolve t<br />
body &lt;- asks (lookupTemplate tmplName)<br />
case body of<br />
Just t' -&gt; do defs &lt;- mapM resolveDef ds<br />
local (addDefs defs) (resolve t')<br />
Nothing -&gt; return &quot;&quot;<br />
resolve (C ts) = (liftM concat) (mapM resolve ts)</pre><br />
To use the Reader monad to resolve a template <tt>t</tt> into a <tt>String</tt>, you simply need to do <tt>runReader (resolve t) env</tt>.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[statemonad.html|The State monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[writermonad.html|The Writer monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Writer monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[readermonad.html|The Reader monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[contmonad.html|The Continuation monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Writer monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 <tt>Monoid</tt> class, which represents a mathematical structure called a monoid in the same way that the <tt>Monad</tt> class represents the monad structure.<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 <tt>mzero</tt> and <tt>mplus</tt> for instances of <tt>MonadPlus</tt>. That is because monads with a zero and plus are monads that are also monoids!<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 <tt>Monoid</tt> class (in Data.Monoid) to provide a standard convention for working with monoids: the identity element is named <tt>mempty</tt> and the operator is named <tt>mappend</tt>.<br />
<br />
The most commonly used standard monoid in Haskell is the list, but functions of type <tt>(a -&gt; a)</tt> 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 <tt>mappend</tt> operation as the output grows. In that case, a data structure that supports fast append operations would be a more appropriate choice.<br />
<br />
<pre>newtype Writer w a = Writer { runWriter :: (a,w) } <br />
<br />
instance (Monoid w) =&gt; Monad (Writer w) where <br />
return a = Writer (a,mempty) <br />
(Writer (a,w)) &gt;&gt;= f = let (a',w') = runWriter $ f a in Writer (a',w `mappend` w')</pre><br />
The Writer monad maintains a (value,log) pair, where the log type must be a monoid. The <tt>return</tt> function simply returns the value along with an empty log. Binding executes the bound function using the current value as input, and appends any log output to the existing log.<br />
<br />
<pre>class (Monoid w, Monad m) =&gt; MonadWriter w m | m -&gt; w where <br />
pass :: m (a,w -&gt; w) -&gt; m a <br />
listen :: m a -&gt; m (a,w) <br />
tell :: w -&gt; m () <br />
<br />
instance (Monoid w) =&gt; 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) =&gt; (w -&gt; w) -&gt; m a -&gt; m (a,w) <br />
listens f m = do (a,w) &lt;- m; return (a,f w)<br />
<br />
censor :: (MonadWriter w m) =&gt; (w -&gt; w) -&gt; m a -&gt; m a <br />
censor f m = pass $ do a &lt;- m; return (a,f)</pre><br />
The <tt>MonadWriter</tt> class provides a number of convenience functions for working with Writer monads. The simplest and most useful is <tt>tell</tt>, which adds one or more entries to the log. The <tt>listen</tt> function turns a Writer that returns a value <tt>a</tt> and produces output <tt>w</tt> into a Writer that produces a value <tt>(a,w)</tt> and still produces output <tt>w</tt>. This allows the computation to &quot;listen&quot; to the log output generated by a Writer.<br />
<br />
The <tt>pass</tt> function is slightly more complicated. It converts a Writer that produces a value <tt>(a,f)</tt> and output <tt>w</tt> into a Writer that produces a value <tt>a</tt> and output <tt>f w</tt>. This is somewhat cumbersome, so the helper function <tt>censor</tt> is normally used. The <tt>censor</tt> function takes a function and a Writer and produces a new Writer whose output is the same but whose log entry has been modified by the function.<br />
<br />
The <tt>listens</tt> function operates just like <tt>listen</tt> except that the log part of the value is modified by the supplied function.<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 />
<pre>-- 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 -&gt; Writer [Entry] ()<br />
logMsg s = tell [Log 1 s]<br />
<br />
-- this handles one packet<br />
filterOne :: [Rule] -&gt; Packet -&gt; Writer [Entry] (Maybe Packet)<br />
filterOne rules packet = do rule &lt;- return (match rules packet)<br />
case rule of<br />
Nothing -&gt; do logMsg (&quot;DROPPING UNMATCHED PACKET: &quot; ++ (show packet))<br />
return Nothing<br />
(Just r) -&gt; do when (logIt r) (logMsg (&quot;MATCH: &quot; ++ (show r) ++ &quot; &lt;=&gt; &quot; ++ (show packet)))<br />
case r of<br />
(Rule Accept _ _) -&gt; return (Just packet)<br />
(Rule Reject _ _) -&gt; return Nothing</pre><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 />
<pre>-- 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] -&gt; [Entry] -&gt; 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) =&gt; a -&gt; (a -&gt; a -&gt; Writer a a) -&gt; [b] -&gt; (b -&gt; Writer a c) -&gt; Writer a [c]<br />
groupSame initial merge [] _ = do tell initial<br />
return []<br />
groupSame initial merge (x:xs) fn = do (result,output) &lt;- return (runWriter (fn x))<br />
new &lt;- merge initial output<br />
rest &lt;- 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] -&gt; [Packet] -&gt; Writer [Entry] [Packet]<br />
filterAll rules packets = do tell [Log 1 &quot;STARTING PACKET FILTER&quot;]<br />
out &lt;- groupSame [] mergeEntries packets (filterOne rules)<br />
tell [Log 1 &quot;STOPPING PACKET FILTER&quot;]<br />
return (catMaybes out)</pre><br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[readermonad.html|The Reader monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[contmonad.html|The Continuation monad]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
The Continuation monad<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[writermonad.html|The Writer monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: Part III - Introduction</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= The Continuation monad =<br />
<br />
* [[#overview|Overview]]<br />
* [[#motivation|Motivation]]<br />
* [[#definition|Definition]]<br />
* [[#example|Example]]<br />
<br />
<br />
-----<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 <tt>id</tt>) which produces the final result. Since continuations are functions which represent the future of a computation, manipulation of the continuation functions can achieve complex manipulations of the future of the computation, such as interrupting a computation in the middle, aborting a portion of a computation, restarting a computation and interleaving execution of computations. The Continuation monad adapts CPS to the structure of a monad.<br />
<br />
== Definition ==<br />
<br />
<pre>newtype Cont r a = Cont { runCont :: ((a -&gt; r) -&gt; r) } -- r is the final result type of the whole computation <br />
<br />
instance Monad (Cont r) where <br />
return a = Cont $ \k -&gt; k a -- i.e. return a = \k -&gt; k a <br />
(Cont c) &gt;&gt;= f = Cont $ \k -&gt; c (\a -&gt; runCont (f a) k) -- i.e. c &gt;&gt;= f = \k -&gt; c (\a -&gt; f a k) </pre><br />
The Continuation monad represents computations in continuation-passing style. <tt>Cont r a</tt> is a CPS computation that produces an intermediate result of type <tt>a</tt> within a CPS computation whose final result type is <tt>r</tt>.<br />
<br />
The <tt>return</tt> function simply creates a continuation which passes the value on. The <tt>&gt;&gt;=</tt> operator adds the bound function into the continuation chain.<br />
<br />
<pre>class (Monad m) =&gt; MonadCont m where <br />
callCC :: ((a -&gt; m b) -&gt; m a) -&gt; m a <br />
<br />
instance MonadCont (Cont r) where <br />
callCC f = Cont $ \k -&gt; runCont (f (\a -&gt; Cont $ \_ -&gt; k a)) k</pre><br />
The <tt>MonadCont</tt> class provides the <tt>callCC</tt> function, which provides an escape continuation mechanism for use with Continuation monads. Escape continuations allow you to abort the current computation and return a value immediately. They achieve a similar effect to <tt>throwError</tt> and catchError within an <tt>Error</tt> monad.<br />
<br />
<tt>callCC</tt> calls a function with the current continuation as its argument (hence the name). The standard idiom used with <tt>callCC</tt> is to provide a 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 <tt>callCC</tt>, the Continuation monad can be used to implement other, more powerful continuation manipulations. These other mechanisms have fairly specialized uses, however — and abuse of them can easily create fiendishly obfuscated code — so they will not be covered here.<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 />
<pre>{- We use the continuation monad to perform &quot;escapes&quot; 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 />
&gt;= 2000000 sum of digits of (n/2) digits of (n/2)<br />
-} <br />
fun :: Int -&gt; String<br />
fun n = (`runCont` id) $ do<br />
str &lt;- callCC $ \exit1 -&gt; do -- define &quot;exit1&quot;<br />
when (n &lt; 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' &lt;- callCC $ \exit2 -&gt; do -- define &quot;exit2&quot;<br />
when ((length ns) &lt; 3) (exit2 (length ns))<br />
when ((length ns) &lt; 5) (exit2 n)<br />
when ((length ns) &lt; 7) $ do let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns') --escape 2 levels<br />
return $ sum ns<br />
return $ &quot;(ns = &quot; ++ (show ns) ++ &quot;) &quot; ++ (show n')<br />
return $ &quot;Answer: &quot; ++ str</pre><br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[writermonad.html|The Writer monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: Part III - Introduction</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Part III - Introduction<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[contmonad.html|The Continuation monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[hardway.html|Combining monads the hard way]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Introduction =<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[contmonad.html|The Continuation monad]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[hardway.html|Combining monads the hard way]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Combining monads the hard way<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introIII.html|Part III - Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[transformers.html|Monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Combining monads the hard way =<br />
<br />
* [[#nested|Nested Monads]]<br />
* [[#combined|Combined Monads]]<br />
<br />
<br />
-----<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 />
<pre>fun :: IO String<br />
fun = do n &lt;- (readLn::IO Int) -- this is an IO monad block<br />
return $ (`runCont` id) $ do -- this is a Cont monad block<br />
str &lt;- callCC $ \exit1 -&gt; do<br />
when (n &lt; 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' &lt;- callCC $ \exit2 -&gt; do<br />
when ((length ns) &lt; 3) (exit2 (length ns))<br />
when ((length ns) &lt; 5) (exit2 n)<br />
when ((length ns) &lt; 7) $ do let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns')<br />
return $ sum ns<br />
return $ &quot;(ns = &quot; ++ (show ns) ++ &quot;) &quot; ++ (show n')<br />
return $ &quot;Answer: &quot; ++ str</pre><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 <tt>Cont (IO String) a</tt> if we need to perform I/O within the computation in the Continuation monad. We could use a monad of type <tt>State (Either Err a) a</tt> to combine the features of the State and Error monads in a single computation.<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 <tt>Int</tt> and <tt>String</tt> values are now of type <tt>IO Int</tt> and <tt>IO String</tt>. We can't extract values from the IO monad — it's a 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 <tt>toIO</tt> 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 />
<pre>toIO :: a -&gt; IO a<br />
toIO x = return x<br />
<br />
fun :: IO String<br />
fun = do n &lt;- (readLn::IO Int) -- this is an IO monad block<br />
convert n<br />
<br />
convert :: Int -&gt; IO String<br />
convert n = (`runCont` id) $ do -- this is a Cont monad block<br />
str &lt;- callCC $ \exit1 -&gt; do -- str has type IO String<br />
when (n &lt; 10) (exit1 $ toIO (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' &lt;- callCC $ \exit2 -&gt; do -- n' has type IO Int<br />
when ((length ns) &lt; 3) (exit2 (toIO (length ns)))<br />
when ((length ns) &lt; 5) (exit2 $ do putStrLn &quot;Enter a number:&quot;<br />
x &lt;- (readLn::IO Int)<br />
return x)<br />
when ((length ns) &lt; 7) $ do let ns' = map intToDigit (reverse ns)<br />
exit1 $ toIO (dropWhile (=='0') ns')<br />
return (toIO (sum ns))<br />
return $ do num &lt;- n' -- this is an IO monad block<br />
return $ &quot;(ns = &quot; ++ (show ns) ++ &quot;) &quot; ++ (show num)<br />
return $ do s &lt;- str -- this is an IO monad block<br />
return $ &quot;Answer: &quot; ++ s</pre><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 />
<pre>fun = do n &lt;- (readLn::IO Int)<br />
return $ (`runCont` id) $ do<br />
str &lt;- callCC $ \exit1 -&gt; do<br />
when (n &lt; 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' &lt;- callCC $ \exit2 -&gt; do<br />
when ((length ns) &lt; 3) (exit2 (length ns))<br />
when ((length ns) &lt; 5) (exit2 n)<br />
when ((length ns) &lt; 7) $ do<br />
let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns')<br />
return $ sum ns<br />
return $ &quot;(ns = &quot; ++ (show ns) ++ &quot;) &quot; ++ (show n')<br />
return $ &quot;Answer: &quot; ++ str</pre><br />
<pre>convert n = (`runCont` id) $ do<br />
str &lt;- callCC $ \exit1 -&gt; do<br />
when (n &lt; 10) (exit1 $ toIO (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' &lt;- callCC $ \exit2 -&gt; do<br />
when ((length ns) &lt; 3) (exit2 (toIO (length ns)))<br />
when ((length ns) &lt; 5) (exit2 $ do<br />
putStrLn &quot;Enter a number:&quot;<br />
x &lt;- (readLn::IO Int)<br />
return x)<br />
when ((length ns) &lt; 7) $ do<br />
let ns' = map intToDigit (reverse ns)<br />
exit1 $ toIO (dropWhile (=='0') ns')<br />
return (toIO (sum ns))<br />
return $ do num &lt;- n'<br />
return $ &quot;(ns = &quot; ++ (show ns) ++ &quot;) &quot; ++ (show num)<br />
return $ do s &lt;- str<br />
return $ &quot;Answer: &quot; ++ s</pre><br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[introIII.html|Part III - Introduction]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[transformers.html|Monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Monad transformers<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[hardway.html|Combining monads the hard way]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[standardxformers.html|Standard monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Monad transformers =<br />
<br />
* [[#type|Transformer type constructors]]<br />
* [[#lifting|Lifting]]<br />
<br />
<br />
-----<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 <tt>Reader r a</tt> is the type of values of type <tt>a</tt> within a Reader monad with environment of type <tt>r</tt>. The type constructor <tt>Reader r</tt> is an instance of the <tt>Monad</tt> class, and the <tt>runReader::(r-&gt;a)</tt> function performs a computation in the Reader monad and returns the result of type <tt>a</tt>.<br />
<br />
A transformer version of the Reader monad, called <tt>ReaderT</tt>, exists which adds a monad type constructor as an addition parameter. <tt>ReaderT r m a</tt> is the type of values of the combined monad in which Reader is the base monad and <tt>m</tt> is the inner monad. <tt>ReaderT r m</tt> is an instance of the monad class, and the <tt>runReaderT::(r -&gt; m a)</tt> function performs a computation in the combined monad and returns a result of type <tt>m a</tt>.<br />
<br />
Using the transformer versions of the monads, we can produce combined monads very simply. <tt>ReaderT r IO</tt> is a combined Reader+IO monad. We can also generate the non-transformer version of a monad from the transformer version by applying it to the Identity monad. So <tt>ReaderT r Identity</tt> is the same monad as <tt>Reader r</tt>.<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 <tt>liftM</tt> family of functions which are used to lift non-monadic functions into a monad. Each monad transformer provides a <tt>lift</tt> function that is used to lift a monadic computation into a combined monad. Many transformers also provide a <tt>liftIO</tt> function, which is a version of <tt>lift</tt> that is optimized for lifting computations in the <tt>IO</tt> monad. To see this in action, we will continue to develop our previous example in the Continuation monad.<br />
<br />
Code available in [[../examples/example21.hs|example21.hs]]<br />
<br />
<pre>fun :: IO String<br />
fun = (`runContT` return) $ do<br />
n &lt;- liftIO (readLn::IO Int)<br />
str &lt;- callCC $ \exit1 -&gt; do -- define &quot;exit1&quot;<br />
when (n &lt; 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' &lt;- callCC $ \exit2 -&gt; do -- define &quot;exit2&quot;<br />
when ((length ns) &lt; 3) (exit2 (length ns))<br />
when ((length ns) &lt; 5) $ do liftIO $ putStrLn &quot;Enter a number:&quot;<br />
x &lt;- liftIO (readLn::IO Int)<br />
exit2 x<br />
when ((length ns) &lt; 7) $ do let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns') --escape 2 levels<br />
return $ sum ns<br />
return $ &quot;(ns = &quot; ++ (show ns) ++ &quot;) &quot; ++ (show n')<br />
return $ &quot;Answer: &quot; ++ str</pre><br />
Compare this function using <tt>ContT</tt>, the transformer version of <tt>Cont</tt>, with the original version to see how unobtrusive the changes become when using the monad transformer.<br />
<br />
Nested monads from example 19<br />
<br />
Monads combined with a transformer from example 21<br />
<br />
<pre>fun = do n &lt;- (readLn::IO Int)<br />
return $ (`runCont` id) $ do<br />
str &lt;- callCC $ \exit1 -&gt; do<br />
when (n &lt; 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' &lt;- callCC $ \exit2 -&gt; do<br />
when ((length ns) &lt; 3) (exit2 (length ns))<br />
when ((length ns) &lt; 5) (exit2 n)<br />
when ((length ns) &lt; 7) $ do<br />
let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns')<br />
return $ sum ns<br />
return $ &quot;(ns = &quot; ++ (show ns) ++ &quot;) &quot; ++ (show n')<br />
return $ &quot;Answer: &quot; ++ str</pre><br />
<pre>fun = (`runContT` return) $ do<br />
n &lt;- liftIO (readLn::IO Int)<br />
str &lt;- callCC $ \exit1 -&gt; do<br />
when (n &lt; 10) (exit1 (show n))<br />
let ns = map digitToInt (show (n `div` 2))<br />
n' &lt;- callCC $ \exit2 -&gt; do<br />
when ((length ns) &lt; 3) (exit2 (length ns))<br />
when ((length ns) &lt; 5) $ do<br />
liftIO $ putStrLn &quot;Enter a number:&quot;<br />
x &lt;- liftIO (readLn::IO Int)<br />
exit2 x<br />
when ((length ns) &lt; 7) $ do<br />
let ns' = map intToDigit (reverse ns)<br />
exit1 (dropWhile (=='0') ns')<br />
return $ sum ns<br />
return $ &quot;(ns = &quot; ++ (show ns) ++ &quot;) &quot; ++ (show n')<br />
return $ &quot;Answer: &quot; ++ str</pre><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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[hardway.html|Combining monads the hard way]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[standardxformers.html|Standard monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Standard monad transformers<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[transformers.html|Monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[xformeranatomy.html|Anatomy of a monad transformer]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Standard monad transformers =<br />
<br />
* [[#classes|The MonadTrans and MonadIO classes]]<br />
* [[#library|Transformer versions of standard monads]]<br />
<br />
<br />
-----<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 <tt>MonadTrans</tt> class is defined in [http://www.haskell.org/ghc/docs/latest/html/base/Control.Monad.Trans.html Control.Monad.Trans] and provides the single function <tt>lift</tt>. The <tt>lift</tt> function lifts a monadic computation in the inner monad into the combined monad.<br />
<br />
<pre>class MonadTrans t where<br />
lift :: (Monad m) =&gt; m a -&gt; t m a</pre><br />
Monads which provide optimized support for lifting IO operations are defined as members of the <tt>MonadIO</tt> class, which defines the <tt>liftIO</tt> function.<br />
<br />
<pre>class (Monad m) =&gt; MonadIO m where<br />
liftIO :: IO a -&gt; m a</pre><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 <tt>ContT</tt> transformer turns continuations of the form <tt>(a-&gt;r)-&gt;r</tt> into continuations of the form <tt>(a-&gt;m r)-&gt;m r</tt>. The <tt>StateT</tt> transformer is different. It turns state transformer functions of the form <tt>s-&gt;(a,s)</tt> into state transformer functions of the form <tt>s-&gt;m (a,s)</tt>. In general, there is no magic formula to create a transformer version of a monad — the form of each transformer depends on what makes sense in the context of its non-transformer type.<br />
<br />
<table><br />
<thead><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 />
</thead><br />
<tbody><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"><tt>Either e a</tt></td><br />
<td align="left"><tt>m (Either e a)</tt></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"><tt>s -&gt; (a,s)</tt></td><br />
<td align="left"><tt>s -&gt; m (a,s)</tt></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"><tt>r -&gt; a</tt></td><br />
<td align="left"><tt>r -&gt; m a</tt></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"><tt>(a,w)</tt></td><br />
<td align="left"><tt>m (a,w)</tt></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"><tt>(a -&gt; r) -&gt; r</tt></td><br />
<td align="left"><tt>(a -&gt; m r) -&gt; m r</tt></td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
[[Image:info.png]] Order is important when combining monads. <tt>StateT s (Error e)</tt> is different than <tt>ErrorT e (State s)</tt>. The first produces a combined type of <tt>s -&gt; Error e (a,s)</tt>, in which the computation can either return a new state or generate an error. The second combination produces a combined type of <tt>s -&gt; (Error e a,s)</tt>, in which the computation always returns a new state, and the value can be an error or a normal value.<br /><br />
<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[transformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[xformeranatomy.html|Anatomy of a monad transformer]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Anatomy of a monad transformer<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[standardxformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[xformerexamples.html|More examples with monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Anatomy of a monad transformer =<br />
<br />
* [[#monad|Combined monad definition]]<br />
* [[#lift|Defining the lifting function]]<br />
* [[#functor|Functors]]<br />
<br />
<br />
-----<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, <tt>StateT</tt>. Studying this transformer will build insight into the transformer mechanism that you can call upon when using monad transformers in your code. You might want to review the section on the [[statemonad.html|State monad]] before continuing.<br />
<br />
== Combined monad definition ==<br />
<br />
Just as the State monad was built upon the definition<br />
<br />
<pre>newtype State s a = State { runState :: (s -&gt; (a,s)) }</pre><br />
the StateT transformer is built upon the definition<br />
<br />
<pre>newtype StateT s m a = StateT { runStateT :: (s -&gt; m (a,s)) }</pre><br />
<tt>State s</tt> is an instance of both the <tt>Monad</tt> class and the <tt>MonadState s</tt> class, so <tt>StateT s m</tt> should also be members of the <tt>Monad</tt> and <tt>MonadState s</tt> classes. Furthermore, if <tt>m</tt> is an instance of <tt>MonadPlus</tt>, <tt>StateT s m</tt> should also be a member of <tt>MonadPlus</tt>.<br />
<br />
To define <tt>StateT s m</tt> as a <tt>Monad</tt> instance:<br />
<br />
<pre>newtype StateT s m a = StateT { runStateT :: (s -&gt; m (a,s)) }<br />
<br />
instance (Monad m) =&gt; Monad (StateT s m) where<br />
return a = StateT $ \s -&gt; return (a,s)<br />
(StateT x) &gt;&gt;= f = StateT $ \s -&gt; do (v,s') &lt;- x s -- get new value, state<br />
(StateT x') &lt;- return $ f v -- apply bound function to get new state transformation fn<br />
x' s' -- apply the state transformation fn to the new state</pre><br />
Compare this to the definition for [[statemonad.html#definition|<tt>State s</tt>]]. Our definition of <tt>return</tt> makes use of the <tt>return</tt> function of the inner monad, and the binding operator uses a do-block to perform a computation in the inner monad.<br />
<br />
We also want to declare all combined monads that use the <tt>StateT</tt> transformer to be instaces of the <tt>MonadState</tt> class, so we will have to give definitions for <tt>get</tt> and <tt>put</tt>:<br />
<br />
<pre>instance (Monad m) =&gt; MonadState s (StateT s m) where<br />
get = StateT $ \s -&gt; return (s,s)<br />
put s = StateT $ \_ -&gt; return ((),s)</pre><br />
Finally, we want to declare all combined monads in which <tt>StateT</tt> is used with an instance of <tt>MonadPlus</tt> to be instances of <tt>MonadPlus</tt>:<br />
<br />
<pre>instance (MonadPlus m) =&gt; MonadPlus (StateT s m) where<br />
mzero = StateT $ \s -&gt; mzero<br />
(StateT x1) `mplus` (StateT x2) = StateT $ \s -&gt; (x1 s) `mplus` (x2 s)</pre><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 <tt>StateT s</tt> an instance of the <tt>MonadTrans</tt> class by providing a <tt>lift</tt> function:<br />
<br />
<pre>instance MonadTrans (StateT s) where<br />
lift c = StateT $ \s -&gt; c &gt;&gt;= (\x -&gt; return (x,s))</pre><br />
The <tt>lift</tt> function creates a <tt>StateT</tt> state transformation function that binds the computation in the inner monad to a function that packages the result with the input state. The result is that a function that returns a list (i.e., a computation in the List monad) can be lifted into <tt>StateT s []</tt>, where it becomes a function that returns a <tt>StateT (s -&gt; [(a,s)])</tt>. 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 <tt>StateT</tt> to a different monad will produce different semantics for the <tt>lift</tt> 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 <tt>fmap :: (a-&gt;b) -&gt; f a -&gt; f b</tt>. 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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[standardxformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[xformerexamples.html|More examples with monad transformers]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
More examples with monad transformers<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[xformeranatomy.html|Anatomy of a monad transformer]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[stacking.html|Managing the transformer stack]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= More examples with monad transformers =<br />
<br />
* [[#example22|WriterT with IO]]<br />
* [[#example23|ReaderT with IO]]<br />
* [[#example24|StateT with List]]<br />
<br />
<br />
-----<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 />
<pre>-- 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) ++ &quot; | &quot; ++ 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 -&gt; LogWriter ()<br />
logMsg s = do t &lt;- liftIO getClockTime<br />
tell [Log t s]<br />
<br />
-- this handles one packet<br />
filterOne :: [Rule] -&gt; Packet -&gt; LogWriter (Maybe Packet)<br />
filterOne rules packet = do rule &lt;- return (match rules packet)<br />
case rule of<br />
Nothing -&gt; do logMsg (&quot;DROPPING UNMATCHED PACKET: &quot; ++ (show packet))<br />
return Nothing<br />
(Just r) -&gt; do when (logIt r) (logMsg (&quot;MATCH: &quot; ++ (show r) ++ &quot; &lt;=&gt; &quot; ++ (show packet)))<br />
case r of<br />
(Rule Accept _ _) -&gt; return (Just packet)<br />
(Rule Reject _ _) -&gt; 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] -&gt; [Packet] -&gt; LogWriter [Packet]<br />
filterAll rules packets = do logMsg &quot;STARTING PACKET FILTER&quot;<br />
out &lt;- mapM (filterOne rules) packets<br />
logMsg &quot;STOPPING PACKET FILTER&quot;<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 &lt;- getArgs<br />
ruleData &lt;- readFile (args!!0)<br />
packetData &lt;- readFile (args!!1)<br />
let rules = (read ruleData)::[Rule]<br />
packets = (read packetData)::[Packet]<br />
(out,log) &lt;- runWriterT (filterAll rules packets)<br />
putStrLn &quot;ACCEPTED PACKETS&quot;<br />
putStr (unlines (map show out))<br />
putStrLn &quot;\n\nFIREWALL LOG&quot;<br />
putStr (unlines (map show log))</pre><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 <tt>StateT</tt> 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 />
<pre>-- 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 -&gt; Value -&gt; Predicate<br />
isNot var value = Not (Is var value)<br />
<br />
-- if a is true, then b must also be true<br />
implies :: Predicate -&gt; Predicate -&gt; Predicate<br />
implies a b = Not (a `And` (Not b))<br />
<br />
-- exclusive or<br />
orElse :: Predicate -&gt; Predicate -&gt; 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 -&gt; Variables -&gt; Maybe Bool<br />
check (Is var value) vars = do val &lt;- lookup var vars<br />
return (val == value)<br />
check (Equal v1 v2) vars = do val1 &lt;- lookup v1 vars<br />
val2 &lt;- lookup v2 vars<br />
return (val1 == val2)<br />
check (And p1 p2) vars = liftM2 (&amp;&amp;) (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)</pre><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 />
<pre>-- 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 -&gt; NDS (Maybe Value)<br />
getVar v = do vs &lt;- gets vars<br />
return $ lookup v vs<br />
<br />
-- set a variable<br />
setVar :: Var -&gt; Value -&gt; NDS ()<br />
setVar v x = do st &lt;- get<br />
vs' &lt;- 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 -&gt; NDS Bool<br />
isConsistent partial = do cs &lt;- gets constraints<br />
vs &lt;- gets vars<br />
let results = map (\p-&gt;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 &lt;- 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 -&gt; ProblemState -&gt; 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 -&gt; ProblemState -&gt; [a]<br />
getAllSolutions c i = evalStateT c i</pre><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 />
<pre>-- if a male says something, it must be true<br />
said :: Var -&gt; Predicate -&gt; Predicate<br />
said v p = (v `Is` &quot;male&quot;) `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 -&gt; Predicate -&gt; Predicate -&gt; Predicate<br />
saidBoth v p1 p2 = And ((v `Is` &quot;male&quot;) `implies` (p1 `And` p2))<br />
((v `Is` &quot;female&quot;) `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 -&gt; Predicate -&gt; 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 -&gt; NDS ()<br />
tryAllValues var = do (setVar var &quot;male&quot;) `mplus` (setVar var &quot;female&quot;)<br />
c &lt;- isConsistent True<br />
guard c</pre><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 />
<pre>-- 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 &quot;parent1&quot; &quot;parent2&quot;),<br />
&quot;parent1&quot; `said` (&quot;child&quot; `said` (&quot;child&quot; `Is` &quot;male&quot;)),<br />
saidBoth &quot;parent2&quot; (&quot;child&quot; `Is` &quot;female&quot;)<br />
(&quot;child&quot; `lied` (&quot;child&quot; `Is` &quot;male&quot;)) ]<br />
problem = PS variables constraints<br />
print $ (`getSolution` problem) $ do tryAllValues &quot;parent1&quot;<br />
tryAllValues &quot;parent2&quot;<br />
tryAllValues &quot;child&quot;<br />
getFinalVars</pre><br />
Each call to <tt>tryAllValues</tt> will fork the solution space, assigning the named variable to be <tt>&quot;male&quot;</tt> in one fork and <tt>&quot;female&quot;</tt> in the other. The forks which produce inconsistent variable assignments are eliminated (using the <tt>guard</tt> function). The call to <tt>getFinalVars</tt> applies <tt>guard</tt> again to eliminate inconsistent variable assignments and returns the remaining assignments as the value of the computation.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[xformeranatomy.html|Anatomy of a monad transformer]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[stacking.html|Managing the transformer stack]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Managing the transformer stack<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[xformerexamples.html|More examples with monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[beyond.html|Continuing Exploration]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Managing the transformer stack =<br />
<br />
* [[#order|Selecting the correct order]]<br />
* [[#example|An example with multiple transformers]]<br />
* [[#lifting|Heavy lifting]]<br />
<br />
<br />
-----<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 <tt>MonadError</tt> and <tt>MonadState</tt>, but should you apply <tt>StateT</tt> to the <tt>Error</tt> monad or <tt>ErrorT</tt> to the <tt>State</tt> monad?<br />
<br />
The decision depends on the exact semantics you want for your combined monad. Applying <tt>StateT</tt> to the <tt>Error</tt> monad gives a state transformer function of type <tt>s -&gt; Error e (a,s)</tt>. Applying <tt>ErrorT</tt> to the <tt>State</tt> monad gives a state transformer function of type <tt>s -&gt; (Error e a,s)</tt>. Which order to choose depends on the role of errors in your computation. If an error means no state could be produced, you would apply <tt>StateT</tt> to <tt>Error</tt>. If an error means no value could be produced, but the state remains valid, then you would apply <tt>ErrorT</tt> to <tt>State</tt>.<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 <tt>WriterT</tt> 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. <tt>StateT s (WriterT w [])</tt> yields a type like: <tt>s -&gt; [((a,s),w)]</tt>. <tt>WriterT w (StateT s [])</tt> yields a type like: <tt>s -&gt; [((a,w),s)]</tt>. 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 <tt>MonadState</tt> and <tt>MonadWriter</tt>, so we can freely mix use of <tt>get</tt>, <tt>put</tt>, and <tt>tell</tt> in our monadic computations.<br />
<br />
Code available in [[../examples/example25.hs|example25.hs]]<br />
<br />
<pre>-- 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-&gt;Pos A r) [1..8]<br />
rank8 = map (\f-&gt;Pos f 8) [A .. H]<br />
rank1 = map (\f-&gt;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 -&gt; NQueensProblem -&gt; 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 -&gt; NDS ()<br />
addQueen p = do (Board b) &lt;- gets board<br />
rs &lt;- gets ranks<br />
fs &lt;- gets files<br />
as &lt;- gets asc<br />
ds &lt;- 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 [&quot;Added Queen at &quot; ++ (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 -&gt; NDS Bool<br />
inDiags p = do let (a,d) = getDiags p<br />
as &lt;- gets asc<br />
ds &lt;- gets desc<br />
return $ (elem a as) &amp;&amp; (elem d ds)<br />
<br />
-- add a Queen to the board in all allowed positions<br />
addQueens :: NDS ()<br />
addQueens = do rs &lt;- gets ranks<br />
fs &lt;- gets files<br />
allowed &lt;- filterM inDiags [Pos f r | f &lt;- fs, r &lt;- rs]<br />
tell [show (length allowed) ++ &quot; possible choices&quot;]<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 &lt;- 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) -&gt; do putStr $ show b -- show the solution<br />
putStr $ unlines l -- show the log<br />
Nothing -&gt; putStrLn &quot;No solution&quot;</pre><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 <tt>guard</tt> function. Instead, we only create branches that correspond to allowed queen positions. We use the added logging facility to log the number of possible choices at each step and the position in which the queen was placed.<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 <tt>lift</tt> function from the <tt>MonadTrans</tt> class comes into its own. The <tt>lift</tt> function gives us the ability to write our code in a clear, modular, reusable manner and then lift the computations into the combined monad as needed.<br />
<br />
Instead of writing brittle code like:<br />
<br />
<pre>logString :: String -&gt; StateT MyState (WriterT [String] []) Int<br />
logString s = ...</pre><br />
we can write clearer, more flexible code like:<br />
<br />
<pre>logString :: (MonadWriter [String] m) =&gt; String -&gt; m Int<br />
logString s = ...</pre><br />
and then lift the <tt>logString</tt> computation into the combined monad when we use it.<br />
<br />
[[Image:info.png]] You may need to use the compiler flags <tt>-fglasgow-exts</tt> with GHC or the equivalent flags with your Haskell compiler to use this technique. The issue is that <tt>m</tt> in the constraint above is a type constructor, not a type, and this is not supported in standard Haskell 98. <br /><br />
<br />
<br />
When using lifting with complex transformer stacks, you may find yourself composing multiple lifts, like <tt>lift . lift . lift $ f x</tt>. This can become hard to follow, and if the transformer stack changes (perhaps you add <tt>ErrorT</tt> into the mix) the lifting may need to be changed all over the code. A good practice to prevent this is to declare helper functions with informative names to do the lifting:<br />
<br />
<pre>liftListToState = lift . lift . lift</pre><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 />
<pre>-- 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 -&gt; [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) =&gt; Int -&gt; m Int<br />
logVal n = do tell [&quot;logVal: &quot; ++ (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) =&gt; m b -&gt; m Int<br />
getLogLength c = do (_,l) &lt;- listen $ c<br />
return (length (concat l))<br />
<br />
-- log a string value and return 0<br />
logString :: (MonadWriter [String] m) =&gt; String -&gt; m Int<br />
logString s = do tell [&quot;logString: &quot; ++ s]<br />
return 0<br />
<br />
{- Here is a computation that requires a WriterT [String] [] -}<br />
<br />
-- &quot;Fork&quot; the computation and log each list item in a different branch.<br />
logEach :: (Show a) =&gt; [a] -&gt; WriterT [String] [] a<br />
logEach xs = do x &lt;- lift xs<br />
tell [&quot;logEach: &quot; ++ (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) =&gt; Int -&gt; m ()<br />
addVal n = do x &lt;- 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 -&gt; NDS ()<br />
setVal n = do x &lt;- lift $ logVal n<br />
put x<br />
<br />
-- &quot;Fork&quot; 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 -&gt; NDS ()<br />
addDigits n = do x &lt;- get<br />
y &lt;- lift . lift $ getDigits n<br />
setVal (x+y)<br />
<br />
{- an equivalent construction is:<br />
addDigits :: Int -&gt; NDS ()<br />
addDigits n = do x &lt;- get<br />
msum (map (\i-&gt;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] -&gt; 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 &lt;- lift $ getLogLength $ logString &quot;hello&quot;<br />
addDigits x<br />
x &lt;- lift $ logEach [1,3,5]<br />
lift $ logVal x<br />
liftListToNDS $ getDigits 287<br />
</pre><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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[xformerexamples.html|More examples with monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[beyond.html|Continuing Exploration]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Continuing Exploration<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[stacking.html|Managing the transformer stack]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[analogy.html|Appendix I - A physical analogy for monads]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Continuing Exploration =<br />
<br />
<br />
-----<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 />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[stacking.html|Managing the transformer stack]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[analogy.html|Appendix I - A physical analogy for monads]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
A physical analogy for monads<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[standardxformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[examples.html|Appendix II - Haskell code examples]]</td><br />
</tr><br />
</tbody><br />
</table><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 />
<pre>-- 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 -&gt; Tray Chopsticks<br />
makeChopsticks w = ...<br />
<br />
-- worker function 2: polishes chopsticks<br />
polishChopsticks :: Chopsticks -&gt; Tray Chopsticks<br />
polishChopsticks c = ...<br />
<br />
-- worker function 3: wraps chopsticks<br />
wrapChopsticks :: Chopsticks -&gt; Tray Wrapper Chopsticks<br />
wrapChopsticks c = ...</pre><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 <tt>Tray</tt> monad as:<br />
<br />
<pre>-- 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 &gt;&gt;= _ = Empty<br />
(Contains x) &gt;&gt;= worker = worker x<br />
return = Contains<br />
fail _ = Empty </pre><br />
[[Image:info.png]] You may recognize the <tt>Tray</tt> monad as a disguised version of the <tt>Maybe</tt> monad that is a standard part of Haskell 98 library. <br /><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 />
<pre>assemblyLine :: Wood -&gt; Tray Wrapped Chopsticks<br />
assemblyLine w = (return w) &gt;&gt;= makeChopsticks &gt;&gt;= polishChopsticks &gt;&gt;= wrapChopsticks</pre><br />
or using the built in Haskell &quot;do&quot; notation for monads:<br />
<br />
<pre>assemblyLine :: Wood -&gt; Tray Wrapped Chopsticks<br />
assemblyLine w = do c &lt;- makeChopsticks w<br />
c' &lt;- polishChopsticks c<br />
c'' &lt;- wrapChopsticks c'<br />
return c''</pre><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 <tt>fail</tt> routine to produce an empty tray. The <tt>fail</tt> routine takes an argument describing the failure, but our <tt>Tray</tt> type ignores this and simply produces an empty tray. This empty tray travels down the assembly line and the combiner machines allow it to bypass the remaining worker machines. It eventually reaches the end of the assembly line, where it is brought to you, the quality control engineer. It is your job to figure out which machine failed, but all you have to go on is an empty tray.<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 <tt>fail</tt> routine in your <tt>Tray</tt> monad. Because your assembly line is organized around a monadic approach, it is easy for you to add this functionality to your assembly line without changing your worker machines.<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 />
<pre>-- 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) &gt;&gt;= _ = Failed reason<br />
(Contains x) &gt;&gt;= worker = worker x<br />
return = Contains<br />
fail reason = Failed reason</pre><br />
[[Image:info.png]] You may recognize the <tt>Tray2</tt> monad as a disguised version of the <tt>Error</tt> monad that is a standard part of the Haskell 98 libraries.<br /><br />
<br />
<br />
Replacing the <tt>Tray</tt> monad with the <tt>Tray2</tt> monad instantly upgrades your assembly line. Now when a failure occurs, the tray that is brought to the quality control engineer contains a failure report detailing the exact cause of the failure!<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[standardxformers.html|Standard monad transformers]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left">Next: [[examples.html|Appendix II - Haskell code examples]]</td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
Haskell code examples<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[analogy.html|Appendix I - A physical analogy for monads]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left"></td><br />
</tr><br />
</tbody><br />
</table><br />
<br />
= Haskell code examples =<br />
<br />
This appendix contains a list of all of the code [[../examples/|examples]] supplied with the tutorial.<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 <tt>Monad</tt> class (in this case, <tt>Maybe</tt> 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 <tt>foldM</tt> 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 <tt>foldM</tt> function within a do-block. It combines dictionary values read from different files into a single dictionary using the <tt>foldM</tt> 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 <tt>filterM</tt> 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 <tt>liftM</tt> 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 <tt>liftM2</tt>. 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 <tt>ap</tt>. It folds <tt>ap</tt> through a list of <tt>Maybe (a-&gt;a)</tt> 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 <tt>msum</tt> 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 <tt>guard</tt> in the Maybe monad to select only the records from a list that satisfy a predicate (equivalent to <tt>filter</tt>).<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 <tt>Maybe</tt> monad to build complex queries from simpler queries that may fail to return a result. The specific example used is looking up mail preferences for someone based on either their full name or a nickname.<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 <tt>Either</tt> type constructor as an <tt>Error</tt> monad with a custom error type. The example parses hexadecimal digits and uses the exception handling mechanism of the <tt>Error</tt> monad to provide informative error messages in the event of a parse failure.<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 <tt>fail</tt> calls due to pattern matching failures and the use of <tt>catcherror</tt>.<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 <tt>StateT</tt> 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 <tt>StateT</tt> and <tt>WriterT</tt> 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 <tt>lift</tt> function and the necessity of managing its use in complex transformer stacks.<br />
<br />
<br />
-----<br />
<br />
<table><br />
<tbody><br />
<tr class="odd"><br />
<td align="left">Prev: [[analogy.html|Apendix I - A physical analogy for monads]]</td><br />
<td align="left">TOC: [[index.html|Contents]]</td><br />
<td align="left"></td><br />
</tr><br />
</tbody><br />
</table></div>Daghttps://wiki.haskell.org/index.php?title=All_About_Monads&diff=43374All About Monads2011-12-06T20:00:59Z<p>Dag: Update link</p>
<hr />
<div>[http://mauke.dyndns.org/stuff/haskell/All_About_Monads.pdf A comprehensive guide to the theory and practice of monadic programming in Haskell] (PDF)</div>Daghttps://wiki.haskell.org/index.php?title=Talk:Typeclassopedia&diff=43261Talk:Typeclassopedia2011-11-28T16:37:30Z<p>Dag: /* Diagram in SVG? */</p>
<hr />
<div>== Adding Exercises ==<br />
<br />
I'd like to add a bunch of explicit, typographically distinguished exercises to the text. For example, the [[Wikibooks:Haskell|Haskell wikibook]] typesets exercises in a centered box. I don't know a lot about wiki markup -- does anyone have ideas on a good way to do this?<br />
<br />
[[User:Byorgey|Byorgey]] 16:09, 26 November 2011 (UTC)<br />
<br />
<br />
https://en.wikibooks.org/wiki/Template:Exercises If you look at the source, it doesn't seem too complicated to copy over - only calls 1 or 2 other templates an those may not be important. --[[User:Gwern|Gwern]] 16:20, 26 November 2011 (UTC)<br />
<br />
That works great, thanks! [[User:Byorgey|Byorgey]] 17:34, 26 November 2011 (UTC)<br />
<br />
== §6.4 Other monoidal classes ==<br />
<br />
This section states that instances of Alternative/MonadPlus/ArrowPlus are sometimes the same as the Monoid instance, and sometimes different. It would be helpful (imo) if it was explained why this is: whether it would be better if instances of Alternative/MonadPlus/ArrowPlus were the same as the Monoid instance, and that sometimes they are not due to accidents of history; or whether sometimes these instances should be different, and giving guidance as to when those times are.<br />
<br />
--[[User:Dave4420|Dave4420]] 17:16, 26 November 2011 (UTC)<br />
<br />
Hmm, where does it say that? [[User:Byorgey|Byorgey]] 17:40, 26 November 2011 (UTC)<br />
<br />
Search for <blockquote>A<br />
simple example of a <code>MonadPlus</code> instance is <code>[]</code>, which is exactly the<br />
same as the <code>Monoid</code> instance for <code>[]</code>: the empty list represents<br />
failure, and list concatenation represents choice. In general,<br />
however, a <code>MonadPlus</code> instance for a type need not be the same as its<br />
<code>Monoid</code> instance; <code>Maybe</code> is an example of such a type.</blockquote>--[[User:Dave4420|Dave4420]] 09:54, 27 November 2011 (UTC)<br />
<br />
:Ah, I see now. I think it's mostly due to history. Many of these types could have many different <code>Monoid</code> instances. I'll put in some additional discussion. --[[User:Byorgey|Byorgey]] 03:44, 28 November 2011 (UTC)<br />
<br />
== References/bibliography ==<br />
<br />
I'm not entirely happy about the situation with citations. Although I like having inline links, a bunch of information is lost by just giving a link rather than a full bibliography entry. I plan to add more citations so just linking to the old .bib file is insufficient. What would be the best way to maintain the actual citation/bibliography info? Is it as easy as copying over some wikipedia citation templates? --[[User:Byorgey|Byorgey]] 18:46, 26 November 2011 (UTC)<br />
<br />
== &lt;code&gt; vs &lt;hask&gt; tags ==<br />
<br />
I'd like to standardize on using &lt;haskell&gt; tags to surround code blocks, but &lt;code&gt; tags to surround inline code. My reasons:<br />
# &lt;hask&gt; tags seem to break a lot of things (e.g. they cannot be used inside links, etc.)<br />
# The formatting with &lt;hask&gt; tags is inconsistent: <hask>Monad</hask> and <hask>Applicative</hask> are different colors, <hask>&&&</hask> does not look right, etc. Even if the formatting were ''consistent'' it would still be ''distracting'': having different sorts of things be different colors helps when reading a code block, because it gives you some visual structure. Having different-colored things in the middle of paragraphs, on the other hand, only serves to distract one's attention when trying to read.<br />
<br />
== Broken sidebar ==<br />
<br />
[[Typeclassopedia#Further_reading_3]] has a broken sidebar and I can't figure out how to fix it. --[[User:Dag|Dag]] 02:05, 27 November 2011 (UTC)<br />
<br />
:The problem was that the sidebar content contained an = symbol. See [http://en.wikipedia.org/wiki/Help:Template#Usage_hints_and_workarounds]. The solution is to either surround each = with double curly braces like <nowiki>{{=}}</nowiki>, or to prefix the content with 1= (like <nowiki>{{note|1=...}}</nowiki>) to treat it as a named rather than anonymous argument to the template. I've also had to watch out for this when typesetting exercises containing things like <code>(>>=)</code>. --[[User:Byorgey|Byorgey]] 06:25, 27 November 2011 (UTC)<br />
<br />
== Diagram in SVG? ==<br />
<br />
If HaskellWiki has the [http://www.mediawiki.org/wiki/SVG SVG support] properly configured and the diagram exists in SVG form, perhaps replace the PNG and let MediaWiki convert it into PNGs of appropriate sizes on the fly? --[[User:Dag|Dag]] 12:10, 27 November 2011 (UTC)<br />
<br />
:Hmm, I just tried this and it ended up looking worse. Maybe I was Doing It Wrong? At any rate, an SVG version is now here: [http://haskell.org/haskellwiki/Image:Typeclassopedia-diagram.svg] so others can play with it if they wish. --[[User:Byorgey|Byorgey]] 03:25, 28 November 2011 (UTC)<br />
<br />
::You can specify a width to scale to:<br />
::[[Image:Typeclassopedia-diagram.svg|600px]]<br />
::--[[User:Dag|Dag]] 16:37, 28 November 2011 (UTC)</div>Daghttps://wiki.haskell.org/index.php?title=Web/Libraries/CSS&diff=43248Web/Libraries/CSS2011-11-27T20:17:01Z<p>Dag: /* CSS */ fix messed up table</p>
<hr />
<div>[[Category:Web|*]]<br />
{{Web infobox}}<br />
<br />
== Factor CSS ==<br />
<br />
This tool takes a CSS stylesheet on input and produces an almost equivalent stylesheet on output, but with rulesets split, combined, and reordered to "factor out" common declarations. This helps reveal shared components. The resulting stylesheet may also be smaller.<br />
<br />
{| class="wikitable"<br />
! Home page:<br />
| http://zamez.org/factorcss<br />
|-<br />
! Package & repositories<br />
| [http://zamez.org/source/factorcss/ VS/SVN](?)<br />
|}<br />
<br />
== Cassius ==<br />
Part of hamlet- see [[Web/Libraries/Templating]].<br />
Insert haskell values into your stylesheets.<br />
<br />
== CSS ==<br />
<br />
Minimal monadic CSS DSL.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Chris Done<br />
|-<br />
! Documentation:<br />
| [https://github.com/chrisdone/css/blob/master/README.md README]<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/css Hackage] - [https://github.com/chrisdone/css Github]<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Web/Libraries/CSS&diff=43247Web/Libraries/CSS2011-11-27T20:16:34Z<p>Dag: Added listing of CSS package</p>
<hr />
<div>[[Category:Web|*]]<br />
{{Web infobox}}<br />
<br />
== Factor CSS ==<br />
<br />
This tool takes a CSS stylesheet on input and produces an almost equivalent stylesheet on output, but with rulesets split, combined, and reordered to "factor out" common declarations. This helps reveal shared components. The resulting stylesheet may also be smaller.<br />
<br />
{| class="wikitable"<br />
! Home page:<br />
| http://zamez.org/factorcss<br />
|-<br />
! Package & repositories<br />
| [http://zamez.org/source/factorcss/ VS/SVN](?)<br />
|}<br />
<br />
== Cassius ==<br />
Part of hamlet- see [[Web/Libraries/Templating]].<br />
Insert haskell values into your stylesheets.<br />
<br />
== CSS ==<br />
<br />
Minimal monadic CSS DSL.<br />
<br />
{| class="wikitable"<br />
! License:<br />
| BSD3<br />
|-<br />
! Author:<br />
| Chris Done<br />
! Documentation:<br />
| [https://github.com/chrisdone/css/blob/master/README.md README]<br />
|-<br />
! Package & repositories<br />
| [http://hackage.haskell.org/package/css Hackage] - [https://github.com/chrisdone/css Github]<br />
|}</div>Daghttps://wiki.haskell.org/index.php?title=Talk:Typeclassopedia&diff=43244Talk:Typeclassopedia2011-11-27T12:10:54Z<p>Dag: /* Diagram in SVG? */</p>
<hr />
<div>== Adding Exercises ==<br />
<br />
I'd like to add a bunch of explicit, typographically distinguished exercises to the text. For example, the [[Wikibooks:Haskell|Haskell wikibook]] typesets exercises in a centered box. I don't know a lot about wiki markup -- does anyone have ideas on a good way to do this?<br />
<br />
[[User:Byorgey|Byorgey]] 16:09, 26 November 2011 (UTC)<br />
<br />
<br />
https://en.wikibooks.org/wiki/Template:Exercises If you look at the source, it doesn't seem too complicated to copy over - only calls 1 or 2 other templates an those may not be important. --[[User:Gwern|Gwern]] 16:20, 26 November 2011 (UTC)<br />
<br />
That works great, thanks! [[User:Byorgey|Byorgey]] 17:34, 26 November 2011 (UTC)<br />
<br />
== §6.4 Other monoidal classes ==<br />
<br />
This section states that instances of Alternative/MonadPlus/ArrowPlus are sometimes the same as the Monoid instance, and sometimes different. It would be helpful (imo) if it was explained why this is: whether it would be better if instances of Alternative/MonadPlus/ArrowPlus were the same as the Monoid instance, and that sometimes they are not due to accidents of history; or whether sometimes these instances should be different, and giving guidance as to when those times are.<br />
<br />
--[[User:Dave4420|Dave4420]] 17:16, 26 November 2011 (UTC)<br />
<br />
Hmm, where does it say that? [[User:Byorgey|Byorgey]] 17:40, 26 November 2011 (UTC)<br />
<br />
Search for <blockquote>A<br />
simple example of a <code>MonadPlus</code> instance is <code>[]</code>, which is exactly the<br />
same as the <code>Monoid</code> instance for <code>[]</code>: the empty list represents<br />
failure, and list concatenation represents choice. In general,<br />
however, a <code>MonadPlus</code> instance for a type need not be the same as its<br />
<code>Monoid</code> instance; <code>Maybe</code> is an example of such a type.</blockquote>--[[User:Dave4420|Dave4420]] 09:54, 27 November 2011 (UTC)<br />
<br />
== References/bibliography ==<br />
<br />
I'm not entirely happy about the situation with citations. Although I like having inline links, a bunch of information is lost by just giving a link rather than a full bibliography entry. I plan to add more citations so just linking to the old .bib file is insufficient. What would be the best way to maintain the actual citation/bibliography info? Is it as easy as copying over some wikipedia citation templates? --[[User:Byorgey|Byorgey]] 18:46, 26 November 2011 (UTC)<br />
<br />
== &lt;code&gt; vs &lt;hask&gt; tags ==<br />
<br />
I'd like to standardize on using &lt;haskell&gt; tags to surround code blocks, but &lt;code&gt; tags to surround inline code. My reasons:<br />
# &lt;hask&gt; tags seem to break a lot of things (e.g. they cannot be used inside links, etc.)<br />
# The formatting with &lt;hask&gt; tags is inconsistent: <hask>Monad</hask> and <hask>Applicative</hask> are different colors, <hask>&&&</hask> does not look right, etc. Even if the formatting were ''consistent'' it would still be ''distracting'': having different sorts of things be different colors helps when reading a code block, because it gives you some visual structure. Having different-colored things in the middle of paragraphs, on the other hand, only serves to distract one's attention when trying to read.<br />
<br />
== Broken sidebar ==<br />
<br />
[[Typeclassopedia#Further_reading_3]] has a broken sidebar and I can't figure out how to fix it. --[[User:Dag|Dag]] 02:05, 27 November 2011 (UTC)<br />
<br />
:The problem was that the sidebar content contained an = symbol. See [http://en.wikipedia.org/wiki/Help:Template#Usage_hints_and_workarounds]. The solution is to either surround each = with double curly braces like <nowiki>{{=}}</nowiki>, or to prefix the content with 1= (like <nowiki>{{note|1=...}}</nowiki>) to treat it as a named rather than anonymous argument to the template. I've also had to watch out for this when typesetting exercises containing things like <code>(>>=)</code>. --[[User:Byorgey|Byorgey]] 06:25, 27 November 2011 (UTC)<br />
<br />
== Diagram in SVG? ==<br />
<br />
If HaskellWiki has the [http://www.mediawiki.org/wiki/SVG SVG support] properly configured and the diagram exists in SVG form, perhaps replace the PNG and let MediaWiki convert it into PNGs of appropriate sizes on the fly? --[[User:Dag|Dag]] 12:10, 27 November 2011 (UTC)</div>Dag