https://wiki.haskell.org/api.php?action=feedcontributions&user=Ysangkok&feedformat=atomHaskellWiki - User contributions [en]2020-09-25T16:10:18ZUser contributionsMediaWiki 1.27.4https://wiki.haskell.org/index.php?title=IRC_channel&diff=63419IRC channel2020-09-02T18:25:31Z<p>Ysangkok: /* Projects using haskell */ remove perl6, project renamed to raku, haskell implementation no longer active, not relevant for haskellers anymore</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 1046<br />
concurrent users, making the channel consistently<br />
[https://netsplit.de/channels/details.php?room=%23haskell&net=freenode one of the most popular]<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 />
{| border="0" <br />
|+ '''#haskell visualized'''<br />
|-<br />
| [[Image:Haskell-current.png|thumb|The social graph, Jan 2008]]<br />
| [[Image:Irc-raw.png|thumb|Daily traffic since 2004]]<br />
|-<br />
| [[Image:Nick-activity.png|thumb|Growth]]<br />
| [[Image:Haskell-wordle-irc.png|thumb|Noun map]]<br />
|}<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://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 fact that the community<br />
is quite tight knit &mdash; we know each other &mdash; 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. New Haskell users should feel entirely comfortable asking questions.<br />
<br />
* Helpful answers should be encouraged with <code>name++</code> karma points, in public, as a reward for providing a good answer.<br />
<br />
* Avoid getting frustrated by negative comments and ambiguous questions. Approach them by asking for details (i.e. [http://en.wikipedia.org/wiki/Socratic_method Socratic questioning]), rather than challenging the competence of the writer (ad hominem). As the channel grows, we see a diverse range of people with different programming backgrounds getting accustomed to Haskell. Be patient and take satisfaction from spreading knowledge.<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 />
== Related channels ==<br />
<br />
In addition to the main Haskell channel there are also:<br />
<br />
=== Language/Country specific ===<br />
<br />
The Freenode staff have asked us to consolidate language channels into the "#haskell-" namespace rather than have them continue on in the "#haskell." namespace. Eventually the language channels below listed with "#haskell." will have to move.<br />
<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #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<br />
| French speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.hr<br />
| Croatian speakers<br />
|-<br />
| #haskell-id<br />
| Indonesian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell-it <br />
| Italian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.jp <br />
| Japanese speakers<br />
|-<br />
| #haskell.scandinavian<br />
| Scandinavian speakers<br />
|-<br />
| #haskell-kr<br />
| Korean speakers<br />
|-<br />
| #haskell.no <br />
| Norwegian speakers<br />
|-<br />
| #haskell.pt<br />
| Portuguese speakers<br />
|-<br />
| #haskell-pl<br />
| Polish 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-ro<br />
| Romanian speakers.<br />
|-<br />
| #haskell.se <br />
| Swedish speakers<br />
|-<br />
| #haskell.tw<br />
| Chinese speakers (mainly in Taiwan)<br />
|-<br />
| #haskell.vn<br />
| Vietnamese speakers<br />
|-<br />
| #chicagohaskell<br />
| [http://chicagohaskell.com Chicago Haskell] programmers group<br />
|}<br />
<br />
=== Platform-specific ===<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #haskell-beginners<br />
| Haskell people focused on teaching and learning Haskell, not just beginners.<br />
|-<br />
| #haskell-offtopic<br />
| Haskell people talking about anything except Haskell itself (no TLS required)<br />
|-<br />
| #haskell-blah <br />
| Haskell people talking about anything except Haskell itself (TLS required)<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-apple<br />
| projects that target iOS or OS X using Haskell. <br />
|-<br />
| #haskell-lisp<br />
| [[Haskell Lisp]] - projects that are creating Lisps written in Haskell, or Haskell implementations written in Lisps. <br />
|-<br />
| #haskell-llvm<br />
| For projects using Haskell and LLVM<br />
|-<br />
| #haskell-overflow<br />
| Overflow conversations<br />
|-<br />
| #haskell-web<br />
| Friendly, practical discussion of haskell web app/framework/server development<br />
|-<br />
| #haskell-robotics<br />
| Discussion about the use of Haskell for robotics applications.<br />
|-<br />
| #arch-haskell <br />
| [[Arch Linux]]/ specific Haskell conversations<br />
|-<br />
| #fedora-haskell<br />
| [https://fedoraproject.org/wiki/Haskell Fedora] Haskell SIG<br />
|-<br />
| #gentoo-haskell <br />
| [[Gentoo]]/Linux specific Haskell conversations<br />
|}<br />
<br />
=== Projects using haskell ===<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel <br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #darcs <br />
| [[Darcs]] revision control system<br />
|-<br />
| #diagrams<br />
| [[Diagrams]] EDSL<br />
|-<br />
| #hackage<br />
| Haskell's software distribution infrastructure<br />
|-<br />
| #haskell-lens<br />
| [[Lens]] discussions<br />
|-<br />
| #haskell-stack<br />
| [https://github.com/commercialhaskell/stack/tree/master/doc Stack] discussions<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 />
| #snowdrift <br />
| [https://snowdrift.coop Snowdrift.coop] Yesod-based web platform for funding free/libre/open works, welcomes Haskell volunteer devs including beginners<br />
|-<br />
| #snapframework<br />
| [http://snapframework.com/ Snap] web framework<br />
|-<br />
| #xmonad<br />
| [http://xmonad.org Xmonad] tiling window manager<br />
|-<br />
| #yesod<br />
| [http://yesodweb.com Yesod] web framework<br />
|-<br />
| #yampa<br />
| [https://wiki.haskell.org/Yampa Yampa] Arrowized FRP<br />
|}<br />
<br />
== Logs ==<br />
<br />
'''Logs''' are kept at http://tunes.org/~nef/logs/haskell/<br />
<br />
<!-- anywhere else? http://ircbrowse.net/browse/haskell 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. The bot is operated by IRC user <code>int-e</code> and provides many useful services for visitors to the IRC channel. You can interact with it in a private chat or publicly in any channel where it appears (#haskell and a number of others). 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"<br />
! Command<br />
! Usage<br />
|-<br />
| @help<br />
| display help to other commands, but help text is not available for all commands.<br />
|-<br />
| @where TOPIC (aliases: @what, @url) <br> @where ? <br> @where+ TOPIC NEWTEXT <br> @where+ TOPIC<br />
| show brief info about some TOPIC <br> list some useful topics (paste, cabalstackhelp, ...) <br> set/update a topic (check for collisions first with @where TOPIC) <br> delete a topic <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 />
| @tell <nick> <msg> -- same as @ask<br />
| Next time <nick> speaks in channel they will be notified they have a message pending and how to receive it.<br />
|}<br />
<br />
See also:<br />
* http://silicon.int-e.eu/lambdabot/State/where - @where db snapshot, updated every few minutes<br />
* https://github.com/simonmichael/lambdabot-where - git repo and .tsv version of the @where db, updated occasionally<br />
<br />
=== yahb ===<br />
If lambdabot doesn't cut it for you, there is a bot called yahb which runs your request in an actual GHCi prompt, so you can use IO.<br />
<br />
Try e.g. <tt>% readFile "/proc/self/environ"</tt><br />
<br />
=== hackage ===<br />
The hackage bot, when running, 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>Ysangkokhttps://wiki.haskell.org/index.php?title=Template:Standard_class&diff=63418Template:Standard class2020-09-02T18:19:34Z<p>Ysangkok: downloads.haskell.org requires specifying library version (even though "latest" can be used for the ghc version). since uses of this template do not specify the version of library linked, use hackage.haskell.org instead, where an URL without version works</p>
<hr />
<div>{| border=1 align=right cellpadding=4 cellspacing=0 style="margin: 0 0 1em 1em; background: white; border: 1px #aaa solid; border-collapse: collapse;"<br />
|+ style="height:3em"| <big><big>{{{1}}}&nbsp;class&nbsp;([[{{{package}}} package|{{{package}}}]])</big></big><br />
|-<br />
| <TT>import [https://hackage.haskell.org/package/{{{package}}}/docs/{{{module-doc}}}.html#t%3A{{{1}}} {{{module}}}]</TT><br />
|}<br />
<br />
[[Category:Standard classes]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Monad/ST&diff=63417Monad/ST2020-09-02T17:38:36Z<p>Ysangkok: fix link to control.monad.st</p>
<hr />
<div>{{Standard class|ST|module=Control.Monad.ST|module-doc=Control-Monad-ST|package=base}}<br />
<br />
The ST monad provides support for ''strict'' state threads.<br />
<br />
<br />
==A discussion on the Haskell irc ==<br />
From #haskell (see 13:05:37 in the [http://tunes.org/~nef/logs/haskell/07.02.07 log] ):<br />
<br />
* TuringTest: ST lets you implement algorithms that are much more efficient with mutable memory used internally. But the whole "thread" of computation cannot exchange mutable state with the outside world, it can only exchange immutable state.<br />
<br />
* TuringTest: chessguy: You pass in normal Haskell values and then use ST to allocate mutable memory, then you initialize and play with it, then you put it away and return a normal Haskell value.<br />
<br />
* sjanssen: a monad that has mutable references and arrays, but has a "run" function that is referentially transparent<br />
<br />
* DapperDan2: it strikes me that ST is like a lexical scope, where all the variables/state disappear when the function returns.<br />
[[Category:Standard classes]] [[Category:Monad]]<br />
<br />
<br />
==An explanation in Haskell-Cafe==<br />
<br />
The ST monad lets you use update-in-place, but is escapable (unlike IO). <br />
ST actions have the form:<br />
<br />
<haskell><br />
ST s α<br />
</haskell><br />
<br />
Meaning that they return a value of type α, and execute in "thread" s.<br />
All reference types are tagged with the thread, so that actions can only<br />
affect references in their own "thread".<br />
<br />
Now, the type of the function used to escape ST is:<br />
<br />
<haskell><br />
runST :: forall α. (forall s. ST s α) -> α<br />
</haskell><br />
<br />
The action you pass must be universal in s, so inside your action you don't know what thread, thus you cannot access any other threads, thus <hask>runST</hask> is pure. This is very useful, since it allows you to implement externally pure things like in-place quicksort, and present them as pure functions ∀ e. Ord e ⇒ Array e → Array e; without using any unsafe functions.<br />
<br />
But that type of <hask>runST</hask> is illegal in Haskell-98, because it needs a universal quantifier *inside* the function-arrow! In the jargon, that type has rank 2; haskell 98 types may have rank at most 1.<br />
<br />
See http://www.haskell.org/pipermail/haskell-cafe/2007-July/028233.html<br />
<br />
== A few simple examples ==<br />
<br />
In this example, we define a version of the function sum, but do it in a way which more like how it would be done in imperative languages, where a variable is updated, rather than a new value is formed and passed to the next iteration of the function. While in place modifications of the STRef n are occurring, something that would usually be considered a side effect, it is all done in a safe way which is deterministic. The result is that we get the benefits of being able to modify memory in place, while still producing a pure function with the use of runST.<br />
<br />
<haskell><br />
import Control.Monad.ST<br />
import Data.STRef<br />
import Control.Monad<br />
<br />
<br />
sumST :: Num a => [a] -> a<br />
sumST xs = runST $ do -- runST takes out stateful code and makes it pure again.<br />
<br />
n <- newSTRef 0 -- Create an STRef (place in memory to store values)<br />
<br />
forM_ xs $ \x -> do -- For each element of xs ..<br />
modifySTRef n (+x) -- add it to what we have in n.<br />
<br />
readSTRef n -- read the value of n, and return it.<br />
<br />
<br />
</haskell><br />
<br />
An implementation of foldl using the ST monad (a lot like sum, and in fact sum can be defined in terms of foldlST):<br />
<br />
<haskell><br />
foldlST :: (a -> b -> a) -> a -> [b] -> a<br />
foldlST f acc xs = runST $ do<br />
acc' <- newSTRef acc -- Create a variable for the accumulator<br />
<br />
forM_ xs $ \x -> do -- For each x in xs...<br />
<br />
a <- readSTRef acc' -- read the accumulator<br />
writeSTRef acc' (f a x) -- apply f to the accumulator and x<br />
<br />
readSTRef acc' -- and finally read the result<br />
</haskell><br />
<br />
An example of the Fibonacci function running in constant¹ space:<br />
<br />
<haskell><br />
fibST :: Integer -> Integer<br />
fibST n = <br />
if n < 2<br />
then n<br />
else runST $ do<br />
x <- newSTRef 0<br />
y <- newSTRef 1<br />
fibST' n x y<br />
<br />
where fibST' 0 x _ = readSTRef x<br />
fibST' n x y = do<br />
x' <- readSTRef x<br />
y' <- readSTRef y<br />
writeSTRef x y'<br />
writeSTRef y $! x'+y'<br />
fibST' (n-1) x y<br />
</haskell><br />
<br />
[1] Since we're using Integers, technically it's not constant space, as they grow in size when they get bigger, but we can ignore this.<br />
<br />
== References ==<br />
* [http://research.microsoft.com/en-us/um/people/simonpj/papers/lazy-functional-state-threads.ps.Z Lazy Functional State Threads, John Launchbury and Simon Peyton Jones]<br />
* [https://hackage.haskell.org/package/base/docs/Control-Monad-ST.html Control.Monad.ST in the base libraries]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Applicative_functor&diff=63378Applicative functor2020-07-23T23:42:06Z<p>Ysangkok: fix links</p>
<hr />
<div>[[Category:Glossary]]<br />
[[Category:Applicative Functor|*]]<br />
An applicative functor has more structure than a [[functor]] but less than a [[monad]]. See the Haddock docs for [https://hackage.haskell.org/package/base-4.10.1.0/docs/Control-Applicative.html#t:Applicative Control.Applicative].<br />
<br />
== Example ==<br />
<br />
It has turned out that many applications do not require monad functionality but only those of applicative functors.<br />
Monads allow you to run actions depending on the outcomes of earlier actions.<br />
<haskell><br />
do text <- getLine<br />
if null text<br />
then putStrLn "You refuse to enter something?"<br />
else putStrLn ("You entered " ++ text)<br />
</haskell><br />
This is obviously necessary in some cases, but in other cases it is disadvantageous.<br />
<br />
Consider an extended IO monad which handles automated closing of allocated resources.<br />
This is possible with a monad.<br />
<haskell><br />
openDialog, openWindow :: String -> CleanIO ()<br />
<br />
liftToCleanup :: IO a -> CleanIO a<br />
<br />
runAndCleanup :: CleanIO a -> IO a<br />
<br />
runAndCleanup $<br />
do text <- liftToCleanup getLine<br />
if null text<br />
then openDialog "You refuse to enter something?"<br />
else openWindow ("You entered " ++ text)<br />
</haskell><br />
The (fictive) functions <hask>openDialog</hask> and <hask>openWindow</hask><br />
could not only open dialogs and windows but could also register some cleanup routine in the <hask>CleanIO</hask>.<br />
<hask> runAndCleanup </hask> would first run the opening actions and afterwards the required cleanup actions.<br />
I.e. if the dialog was opened, the dialog must be closed, but not the window.<br />
That is, the cleanup procedure depends on the outcomes of earlier actions.<br />
<br />
Now consider the slightly different task, where functions shall register ''initialization'' routines<br />
that shall be run before the actual action takes place.<br />
(See the original discussion started by Michael T. Richter in Haskell-Cafe:<br />
[http://www.haskell.org/pipermail/haskell-cafe/2007-June/027517.html Practical Haskell Question])<br />
This is impossible in the monadic framework.<br />
Consider the example above where the choice between <hask>openDialog</hask> and <hask>openWindow</hask><br />
depends on the outcome of <hask> getLine </hask>.<br />
You cannot run initialization code for either <hask>openDialog</hask> or <hask>openWindow</hask>,<br />
because you do not know which one will be called before executing <hask> getLine </hask>.<br />
If you eliminate this dependency, you end up in an applicative functor<br />
and there you can do the initialization trick.<br />
You could write<br />
<haskell><br />
initializeAndRun $<br />
liftA2<br />
(liftToInit getLine)<br />
(writeToWindow "You requested to open a window")<br />
</haskell><br />
where <hask> writeToWindow </hask> registers an initialization routine which opens the window.<br />
<br />
== Usage ==<br />
<br />
If you have the variables<br />
<haskell><br />
f :: a -> b -> c<br />
a :: f a<br />
b :: f b<br />
</haskell><br />
you can combine them in the following ways with the same result of type <hask>f c</hask>:<br />
* <hask>pure f <*> a <*> b</hask><br />
* <hask>liftA2 f a b</hask><br />
<br />
But how to cope with <hask>let</hask> and sharing in the presence of effects?<br />
Consider the non-functorial expression:<br />
<haskell><br />
x :: x<br />
g :: x -> y<br />
h :: y -> y -> z<br />
<br />
let y = g x<br />
in h y y<br />
</haskell><br />
Very simple.<br />
Now we like to generalize this to<br />
<haskell><br />
fx :: f x<br />
fg :: f (x -> y)<br />
fh :: f (y -> y -> z)<br />
</haskell><br />
However, we note that<br />
<haskell><br />
let fy = fg <*> fx<br />
in fh <*> fy <*> fy<br />
</haskell><br />
runs the effect of <hask>fy</hask> twice.<br />
E.g. if <hask>fy</hask> writes something to the terminal then <hask>fh <*> fy <*> fy</hask> writes twice. This could be intended, but how can we achieve, that the effect is run only once and the result is used twice?<br />
<br />
Actually, using the <hask>liftA</hask> commands we can pull results of applicative functors into a scope where we can talk exclusively about functor results and not about effects. Note that functor results can also be functions. This scope is simply a function, which contains the code that we used in the non-functorial setting.<br />
<haskell><br />
liftA3<br />
(\x g h -> let y = g x in h y y)<br />
fx fg fh<br />
</haskell><br />
The order of effects is entirely determined by the order of arguments to <hask>liftA3</hask>.<br />
<br />
== Some advantages of applicative functors ==<br />
<br />
* Code that uses only the <hask>Applicative</hask> interface is more general than code that uses the <hask>Monad</hask> interface, because there are more applicative functors than monads. The <hask>ZipList</hask> is an applicative functor on lists, where <hask>liftA2</hask> is implemented by <hask>zipWith</hask>. It is a typical example of an applicative functor that is not a monad.<br />
* Programming with <hask>Applicative</hask> has a more applicative/functional feel. Especially for newbies, it may encourage functional style even when programming with effects. Monad programming with [[Do notation considered harmful|do notation]] encourages a more sequential & imperative style.<br />
<br />
== Applicative transformers ==<br />
<br />
From the [[Monad Transformer Library]] we are used to have two flavours of every monad: a base monad like <hask>State</hask> and a transformer variant <hask>StateT</hask>. In the [http://hackage.haskell.org/package/transformers/ transformers] package we even have only monad transformers except the <hask>Identity</hask> monad.<br />
So where are applicative transformers? The answer is, that in most situations, we do not need special transformers for applicative functors since they can be combined in a generic way.<br />
<haskell><br />
h :: f (g (a -> b))<br />
a :: f (g a)<br />
<br />
liftA2 (<*>) h a :: f (g b)<br />
</haskell><br />
That is, <hask>liftA2 (<*>)</hask> is essentially the definition for <hask><*></hask><br />
for the composition of the functors <hask>f</hask> and <hask>g</hask>.<br />
This is implemented in the {{HackagePackage|id=TypeCompose}} library as type constructor <hask>O</hask> and in {{HackagePackage|id=transformers}} library in module <hask>Data.Functor.Compose</hask>. The first one needs a lot of type extensions, whereas the second one is entirely Haskell 98.<br />
<br />
It can be useful to use the applicative composition even when you have a monad transformer at hand. In the example above <hask>f</hask> might be <hask>Writer (Sum Int)</hask> that is used for counting the number of involved applicative actions. Since in an applicative functor the number of run actions is independent from interim results, the writer can count the actions at compile time.<br />
<br />
It is not true that transformers are unnecessary for applicatives, though. Consider <hask>State s (IO a) == s -> (s, IO a)</hask>, which behaves like an applicative with the above trick, but it is different from <hask>StateT s IO a == s -> IO (s, a)</hask>. The latter is more useful in some situations, and it is not a composition of any two applicatives.<br />
<br />
== How to switch from monads ==<br />
<br />
* Start using <hask>liftM</hask>, <hask>liftM2</hask>, etc or <hask>ap</hask> where you can, in place of <hask>do</hask>/<hask>(>>=)</hask>. You will often encounter code like<br />
<haskell><br />
do x <- fx<br />
y <- fy<br />
return (g x y)<br />
</haskell><br />
:It can be rewritten to <hask>liftM2 g fx fy</hask>. In general, whenever the choice or construction of monadic actions does not depend on the outcomes of previous monadic actions, then it should be possible to rewrite everything with <hask>liftM</hask>.<br />
* When you notice you're ''only'' using those monad methods, then import <hask>Control.Applicative</hask> and replace<hask>return</hask> with <hask>pure</hask>, <hask>liftM</hask> with <hask>(<$>)</hask> (or <hask>fmap</hask> or <hask>liftA</hask>), <hask>liftM2</hask> with <hask>liftA2</hask>, etc, and <hask>ap</hask> with <hask>(<*>)</hask>. If your function signature was <hask>Monad m => ...</hask>, change to <hask>Applicative m => ...</hask> (and maybe rename <hask>m</hask> to <hask>f</hask> or whatever).<br />
<br />
== Alternative terms ==<br />
<br />
Applicative functors were introduced by several people under different names:<br />
* Ross Paterson called them [http://www.haskell.org/arrows/arrows/Control.Sequence.html Sequence]<br />
* Conor McBride called them [http://www.haskell.org/pipermail/haskell/2004-July/014315.html Idiom]<br />
* The same kind of structure is used in the [http://www.cs.uu.nl/wiki/Center/UtrechtParserCombinators UU Parsing-Combinators].<br />
<br />
<br />
== See also ==<br />
<br />
* [http://www.soi.city.ac.uk/~ross/papers/Applicative.html Applicative Programming with Effects]<br />
* The blog article [http://www.serpentine.com/blog/2008/02/06/the-basics-of-applicative-functors-put-to-practical-work/ The basics of applicative functors, put to practical work]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=FAQ&diff=63377FAQ2020-07-23T06:23:52Z<p>Ysangkok: /* What's the difference between Integer and Int? */ genericLength and friends</p>
<hr />
<div>This FAQ is based on actual frequently-asked questions from [[IRC channel|<tt>#haskell</tt> IRC]]. The goal is simply to collect and edit some common answers. Beginner questions are still welcome on IRC, as always.<br />
<br />
This is a wiki, so please edit the text with any improvements you have. And feel free to add new questions, if they are frequently asked.<br />
<br />
== See also ==<br />
<br />
* [[:Category:FAQ|Other FAQs]]<br />
* The [[Introduction|introduction to Haskell]], and the FAQ at the end of that document.<br />
<br />
__TOC__<br />
<br />
= The real world =<br />
<br />
== Should I learn Haskell? ==<br />
<br />
That depends on your goals. In general, Haskellers will tell you that you should learn Haskell. :)<br />
<br />
Learning Haskell is fun. It will expand your mind and make you a better programmer in other languages. These are the immediate benefits.<br />
<br />
Haskell is also a great tool for solving real-world problems, but it can take many months of study to get to that point.<br />
<br />
== Is Haskell hard to learn? ==<br />
<br />
Any competent programmer can learn Haskell, but it will take more time and motivation than you may expect.<br />
<br />
Haskell requires learning a new way to think, not just new syntax for old concepts. This can be incredibly frustrating, as simple tasks seem impossibly difficult.<br />
<br />
Those with no prior programming experience may actually have an easier time learning Haskell, because they have less to un-learn.<br />
<br />
== How can I get started with Haskell ''right now''? ==<br />
<br />
Check out [http://tryhaskell.org/ Try Haskell].<br />
<br />
Also: [https://www.fpcomplete.com/business/fp-haskell-center/ FP Complete's free online IDE]<br />
<br />
<br />
== What should I read for learning Haskell? ==<br />
<br />
The most popular resources are [http://learnyouahaskell.com/ ''Learn You a Haskell''] and [http://book.realworldhaskell.org/ ''Real World Haskell'']. Each is available online for free, or can be purchased in hardcopy.<br />
<br />
Many other [[tutorials]], [[books]], and [[Learning Haskell|other resources]] are available.<br />
<br />
There's also the [https://www.schoolofhaskell.com/ School of Haskell] which has a set of free online tutorials with runnable examples.<br />
<br />
== How can I get help with learning Haskell? ==<br />
<br />
Your options include:<br />
<br />
* [[IRC channel|<tt>#haskell</tt> on Freenode IRC]]<br />
* [http://stackoverflow.com/questions/tagged/haskell Stack Overflow]<br />
* The [http://www.haskell.org/mailman/listinfo/haskell-cafe Haskell-Cafe] mailing list<br />
<br />
== Will Haskell get me a job? ==<br />
<br />
There are plenty of [[Haskell in industry|companies using Haskell]], but it's still a tiny number compared to the software industry as a whole.<br />
<br />
There are also many companies which do not use Haskell, but prefer to hire people who know Haskell. It indicates that you learned something hard and obscure just for fun, which employers take as a sign of intelligence.<br />
<br />
== Is Haskell similar to Language X? ==<br />
<br />
Probably not. It's best if you approach Haskell with a clean slate. Most analogies to another language will break down somewhere, often in a subtle and misleading way. If you first learn the Haskell concepts for what they are, you can then draw useful connections to other languages.<br />
<br />
== What's the relationship between Haskell and GHC? ==<br />
<br />
Haskell is not a piece of software; it is a specification for a standardized programming language. The [[Language and library specification|latest version of the spec]] is the Haskell 2010 Report.<br />
<br />
[http://www.haskell.org/ghc/ GHC] is the Glorious Glasgow Haskell Compiler. It is by far the most popular and &quot;production-ready&quot; implementation of the standard Haskell language. It also implements many [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/lang.html extension] features that go above and beyond standard Haskell. Many programs use these features and so aren't &quot;written in Haskell&quot; in the strictest sense.<br />
<br />
You can use the term &quot;Haskell&quot; to refer to the standard language, and &quot;GHC Haskell&quot; when including GHC extensions.<br />
<br />
Besides GHC, several other [[implementations]] of Haskell are available. Each one provides its own extensions, some of which don't exist in GHC.<br />
<br />
== What is the Haskell Platform? ==<br />
<br />
The [http://hackage.haskell.org/platform/ Haskell Platform] is a copy of GHC bundled with a &quot;blessed&quot; set of useful libraries. It is the easiest way to get started with Haskell. It's not essential to start with the Platform, because you can install the same libraries as needed.<br />
<br />
== What is Haskell Prime (Haskell')? ==<br />
<br />
[http://prime.haskell.org/ Haskell Prime] is a process which produces new versions of the Haskell language spec. It does not refer to a particular present or future version of Haskell.<br />
<br />
== My textbook uses Haskell 98. Is it very different from Haskell 2010? ==<br />
<br />
No. Haskell 2010 is a [http://www.haskell.org/pipermail/haskell/2009-November/021750.html very conservative change] to Haskell 98. It fixes small syntactic flaws, and standardizes several well-behaved extensions which GHC has supported for years.<br />
<br />
The standardization process is very slow because standardizing a flawed language can be a costly mistake. Extensions are accepted only once they are considered mature and well-understood.<br />
<br />
== How do I get libraries for Haskell? ==<br />
<br />
You can find libraries on [http://hackage.haskell.org/packages/archive/pkg-list.html Hackage], and install them with [[Cabal-Install|<tt>cabal-install</tt>]].<br />
<br />
== Is Haskell compiled? ==<br />
<br />
Usually. GHC, the most popular Haskell implementation, has an optimizing ahead-of-time native-code compiler, as well as a bytecode compiler and interpreter for interactive use.<br />
<br />
Haskell itself is not a &quot;compiled language&quot; because nothing in the Haskell spec requires implementations to be compilers.<br />
<br />
== Does Haskell have an interpreter? ==<br />
<br />
Yes, but maybe you instead mean &quot;Is there a program where I can type Haskell code and see it run immediately?&quot;. GHCi provides such a &quot;read-evaluate-print loop&quot;.<br />
<br />
<br />
== Which project can I join? ==<br />
<br />
See [[Haskell projects needing help]].<br />
<br />
= Paradigms =<br />
<br />
== Is learning Haskell the best way to learn functional programming? ==<br />
<br />
Not necessarily! Haskell is not a ''typical'' functional language. It can be overwhelming to learn the basic concepts of functional programming alongside static types, algebraic data, laziness, type classes, first-class IO, etc. For an introduction to FP by itself you might want to learn Scheme, or play with the FP features in your current favorite language.<br />
<br />
That said, many people choose Haskell as an introduction to FP and have success with that approach. Haskell has an extremely active community of people teaching, doing research, writing libraries, etc. Haskell is where interesting things happen in the FP space, so it's an exciting place to jump in.<br />
<br />
== I heard Haskell is pure functional. Does that mean I can't do imperative / OOP / aspect-oriented / logic programming in Haskell? ==<br />
<br />
No, &quot;pure functional&quot; has a specific technical meaning. It doesn't mean that functional is the only supported paradigm.<br />
<br />
Paradigms describe the techniques used in a particular program. For example, the Linux kernel is written in C, with pervasive use of functional, object-oriented, and aspect-oriented programming. The most we can say about a ''language'' is that it encourages or discourages a particular paradigm. Haskell is very flexible and can comfortably accommodate most paradigms, even when there is no built-in support.<br />
<br />
== I heard Haskell is pure functional. Does that mean it can't do IO? ==<br />
<br />
No; [[Introduction to IO|IO in Haskell]] is straightforward.<br />
<br />
== I heard Haskell is pure functional. Does that mean it doesn't have mutable state? ==<br />
<br />
No; see [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-IORef.html <tt>IORef</tt>] for a simple example. A more sophisticated example is [http://book.realworldhaskell.org/read/software-transactional-memory.html software transactional memory], which provides concurrent state more sophisticated than you'll find in most other imperative languages.<br />
<br />
== Wait, is Haskell imperative or is it functional? ==<br />
<br />
Both. In Haskell, functions are first class, and so are imperative actions.<br />
<br />
There is no reason to consider &quot;imperative language&quot; and &quot;functional language&quot; as mutually exclusive. It's only a historical accident that a few of the most popular imperative languages are unusually bad at functional programming. Functional imperative programming is extremely powerful and is supported by many languages.<br />
<br />
= Math =<br />
<br />
== Was Haskell designed by mathematicians? ==<br />
<br />
Haskell was designed by people studying programming language design. Perhaps programmers would consider them to be mathematicians, while mathematicians would consider them to be programmers.<br />
<br />
Designing a programming language is a hard thing to do. There are many non-obvious tradeoffs, and many lessons to be learned from past failures and successes. Yet many of today's most popular languages were designed by people who hadn't done their homework.<br />
<br />
Haskell was designed by people who knew what they were doing. It's not perfect, but the contrast to an amateur's design is striking.<br />
<br />
== Do I need to know advanced math in order to use Haskell? ==<br />
<br />
No. Certain concepts in Haskell are named after concepts in advanced math. But other languages also appropriate math terminology: consider &quot;[http://en.wikipedia.org/wiki/Singleton_pattern singleton]&quot;, not to mention &quot;function&quot; and &quot;variable&quot;. The way these programming concepts relate to actual mathematics is not necessarily important or relevant.<br />
<br />
In addition, some people write articles about advanced math, using Haskell syntax as their notation. These articles are interesting, but the connection to everyday programming work is usually remote.<br />
<br />
Knowing advanced math will enrich your experience using Haskell, but is by no means a prerequisite.<br />
<br />
= Types =<br />
<br />
== Doesn't a static type system just make it harder to write programs? ==<br />
<br />
Yes. In particular, it makes it ''much'' harder to write ''incorrect'' programs.<br />
<br />
The tradeoff is that correct programs also become somewhat harder to write. In Haskell, features like type inference mitigate this burden to a large extent.<br />
<br />
== How do I make a list with elements of different types? ==<br />
<br />
Are you sure that's what you want? Consider instead creating a single data type to encompass the alternatives:<br />
<br />
<haskell><br />
data Identifier<br />
= ByNumber Int<br />
| ByName String<br />
<br />
doStuff :: [Identifier] -> Whatever<br />
</haskell><br />
<br />
In many dynamically-typed languages you aren't allowed to create &quot;variant types&quot; like this. The type system itself is used as a single ad-hoc global variant type. Keep this in mind if you're translating designs from a dynamically-typed language to Haskell.<br />
<br />
== No really, how do I make a list of elements of different types? ==<br />
<br />
Well, you can't avoid putting all your values into one type. But sometimes the &quot;variant type&quot; approach above is too restrictive. Maybe you need to let other people add to the set of allowed types, the way [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Exception.html Control.Exception] allows users to define new exception types.<br />
<br />
You can use an [[existential type]], possibly with a type class. Or you can use [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Dynamic.html Data.Dynamic].<br />
<br />
== I'm making an RPG. Should I define a type for each kind of monster, and a type class for them? ==<br />
<br />
Probably not. Some languages require a new type for each new behavior. In Haskell, behaviors are functions or IO actions, which are first-class values. So you can store behaviors in an ordinary data type:<br />
<br />
<haskell><br />
data MonsterOps = MonsterOps<br />
{ new :: Monster<br />
, move :: Monster -> Monster<br />
, attack :: Monster -> Player -> Player }<br />
<br />
data Monster = Monster<br />
{ position :: (Int, Int)<br />
, hitpoints :: Double }<br />
<br />
beholder :: MonsterOps<br />
beholder = MonsterOps new move attack where<br />
new = Monster (0,0) 9000<br />
move self = ...<br />
attack self player = ...<br />
</haskell><br />
<br />
This approach is especially nice if you want to generate or transform behaviors on the fly. See the article [http://lukepalmer.wordpress.com/2010/01/24/haskell-antipattern-existential-typeclass/ &quot;Haskell Antipattern: Existential Typeclass&quot;] for a longer discussion.<br />
<br />
== What's the difference between <hask>Integer</hask> and <hask>Int</hask>? ==<br />
<br />
<p><hask>Integer</hask> can represent arbitrarily large integers, up to using all of the storage on your machine.</p><br />
<br />
<p><hask>Int</hask> can only represent integers in a finite range. The [http://www.haskell.org/onlinereport/haskell2010/haskellch6.html#dx13-135009 language standard] only guarantees a range of -2<sup>29</sup> to (2<sup>29</sup> - 1). Most implementations will provide a full machine-size signed integer, i.e. 32 or 64 bits.</p><br />
<br />
Operations on <hask>Int</hask> can be much faster than operations on <hask>Integer</hask>, but overflow and underflow can cause weird bugs. Using <hask>Int</hask> in an initial design could be considered premature optimization. Unfortunately, many standard library functions (e.g. <hask>length</hask>, <hask>take</hask>) use <hask>Int</hask>. There are also [https://hackage.haskell.org/package/base-4.14.0.0/docs/Data-List.html#g:26 generic variants of those].<br />
<br />
== How do I convert type <tt>A</tt> to type <tt>B</tt>? ==<br />
<br />
This is just another way of asking for a function of type <hask>A -> B</hask>. For example, you can convert <hask>Double</hask> to <hask>Int</hask> with <hask>round</hask>, <hask>ceiling</hask>, or <hask>floor</hask>. Haskell does not privilege one of these as ''the'' conversion.<br />
<br />
== Does Haskell have type casts? ==<br />
<br />
The word &quot;cast&quot; can mean a lot of different things.<br />
<br />
* You want to convert a value from one type to another, preserving some idea of what it means. For example, you might convert an <hask>Int</hask> to a <hask>Double</hask> which represents the same integer. In this case you'd just use a function of type <hask>Int -> Double</hask>, such as <hask>fromIntegral</hask>. Haskell doesn't provide special rules or syntax for these functions. See also the previous question.<br /><br /><br />
* You want to pass a value of more specific type to a function expecting a less specific type. There's no syntax for this in Haskell; you just do it. For example you can pass <hask>x :: Int</hask> to <hask>show :: (Show a) => a -> String</hask>, which automatically specializes the type of <hask>show</hask> to <hask>Int -> String</hask>. Note that Haskell does not have subtyping, so this only happens in the context of instantiating type variables.<br /><br /><br />
* You want to use a value of less specific type under the assumption of a more specific type, with a checkable runtime error if they do not match. This is rarely the right way to do things in Haskell, and probably indicates a conceptual / design problem instead. If you really do need such a cast, you can use [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Typeable.html#v:cast <tt>cast</tt>] from [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Typeable.html Data.Typeable]. In this case the &quot;checkable runtime error&quot; is <hask>cast</hask> returning <hask>Nothing</hask>. Note that Haskell does not have subtyping, so this only happens in the context of instantiating type variables.<br /><br /><br />
* You want to use a value of less specific type under the assumption of a more specific type, and if the assumption is incorrect, the program is allowed to segfault / silently corrupt data / give the attacker a root shell / send illicit photos to your boss. Also known as a "reinterpret cast". GHC Haskell has a way to do this, but I dare not speak its name. It's so dangerous and so unlikely to be what you want that it has no place in a general FAQ. You can ask on IRC or read the docs if you have the right kind of morbid curiosity.<br />
<br />
== How do I convert from one numeric type to another? ==<br />
<br />
Probably using one of these:<br />
<br />
<haskell><br />
fromIntegral :: (Integral a, Num b ) => a -> b<br />
realToFrac :: (Real a, Fractional b) => a -> b<br />
</haskell><br />
<br />
<p><hask>fromIntegral</hask> converts to a wider range of types, but <hask>realToFrac</hask> converts from types which aren't integers.</p><br />
<br />
== How do I convert <hask>Maybe Int</hask> to <hask>Int</hask>? ==<br />
<br />
Use pattern-matching. If <hask>mx :: Maybe Int</hask>:<br />
<br />
<haskell><br />
case mx of<br />
Just x -> ...<br />
Nothing -> ...<br />
</haskell><br />
<br />
This forces you to consider the <hask>Nothing</hask> case, and is the main advantage of <hask>Maybe</hask>, compared to adding a <tt>null</tt> value to every type.<br />
<br />
See also the functions [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html#v:maybe <tt>maybe</tt>] and [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html#v:fromMaybe <tt>fromMaybe</tt>] in the module [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html Data.Maybe].<br />
<br />
''Do not'' use <hask>fromJust</hask>, because passing <hask>Nothing</hask> will crash your program with a supremely unhelpful error message. Even when you want to assume the value is not <hask>Nothing</hask>, you can provide a better error message:<br />
<br />
<haskell><br />
let x = fromMaybe (error "custom error message") mx in ...<br />
</haskell><br />
<br />
If you pattern-match without a <hask>Nothing</hask> case:<br />
<br />
<haskell><br />
let Just x = mx in ...<br />
</haskell><br />
<br />
you'll at least get a line number in the error message:<br />
<br />
<pre><br />
*** Exception: foo.hs:2:9-24: Irrefutable pattern failed for pattern Data.Maybe.Just x<br />
</pre><br />
<br />
== How do I convert <hask>IO Int</hask> to <hask>Int</hask>? ==<br />
<br />
You can't; they represent totally different things. An <hask>Int</hask> is an integer. An <hask>IO Int</hask> is a description of how some IO could be performed, in the future, to produce an integer. The IO hasn't been performed yet, and might never happen or might happen more than once.<br />
<br />
See the [[Introduction to IO]].<br />
<br />
== How do I convert between <hask>String</hask> (or <hask>Text</hask>) and <hask>ByteString</hask>? ==<br />
<br />
<p><hask>String</hask> represents a sequence of Unicode characters. <hask>ByteString</hask> represents a sequence of bytes. There are many different, incompatible ways to represent Unicode characters as bytes. See [http://www.joelonsoftware.com/articles/Unicode.html this article] if you're fuzzy on the character / byte distinction.</p><br />
<br />
The module [http://hackage.haskell.org/packages/archive/text/0.11.1.5/doc/html/Data-Text-Encoding.html Data.Text.Encoding] from the <tt>text</tt> package provides functions for common Unicode encodings. For more obscure / legacy encodings, see the [http://hackage.haskell.org/package/text-icu <tt>text-icu</tt>] package.<br />
<br />
== How do I catch the error thrown by <hask>read</hask> on a parse failure? ==<br />
<br />
Don't. Instead use<br />
<br />
<haskell><br />
import Text.Read (readMaybe)<br />
readMaybe :: Read a => String -> Maybe a<br />
</haskell><br />
<br />
which returns a <tt>Nothing</tt> in the case of parse failure.<br />
<br />
== What's the difference between <hask>type</hask>, <hask>data</hask>, and <hask>newtype</hask>? ==<br />
<br />
<p><hask>type</hask> introduces a synonym, which is fully interchangeable with the original type:</p><br />
<br />
<haskell><br />
type Foo = Int<br />
<br />
main = print ((2 :: Int) + (3 :: Foo))<br />
</haskell><br />
<br />
So it provides convenience and documentation, but no additional type checking.<br />
<br />
<p><hask>data</hask> is used to define new data types, distinct from any existing type.</p><br />
<br />
<p><hask>newtype</hask> can mostly be understood as a restricted form of <hask>data</hask>. You can use <hask>newtype</hask> when you have exactly one constructor with exactly one field. In those cases, <hask>newtype</hask> can give better performance than <hask>data</hask>.</p><br />
<br />
There is, however, a [[Newtype|subtle difference]] between <hask>data</hask> and <hask>newtype</hask> semantics, which is why the <hask>newtype</hask> optimization is not applied automatically.<br />
<br />
= Making it work =<br />
<br />
== How can I find type errors? ==<br />
<br />
There's no silver bullet, but here are a few useful techniques:<br />
<br />
* Comment out type signatures and see what GHC infers, using <tt>:t</tt> in GHCi.<br />
* Add more type signatures, for example inside <hask>let</hask>. This makes your assumptions clearer, so GHC's error message may better explain how your assumptions are inconsistent.<br />
* Replace some subexpressions with <hask>undefined</hask>, which can assume any type. In more recent versions of GHC, you should insert a "type hole", written <hask>_</hask> (a single underscore) instead of <hask>undefined</hask> for this purpose. GHC's error message will then indicate the type it's expecting for the expression in the hole.<br />
<br />
== How can I find bugs that occur at runtime? ==<br />
<br />
With pure functions, correctness is a matter of getting the right output for a given input. If one function gives incorrect results, you test the functions it calls, and so on until the bad code is located. You can perform these tests directly in GHCi, or with the help of a tool like QuickCheck.<br />
<br />
You can trace evaluation using [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Debug-Trace.html Debug.Trace]. You'll get a printout when the expression is evaluated. Due to lazy evaluation, this might be at an unexpected time. But this property is useful when debugging problems related to excessive laziness.<br />
<br />
GHCi also implements a [http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci-debugger.html &quot;simple imperative-style debugger&quot;].<br />
<br />
Haskell is a natural fit for novel [http://ww2.cs.mu.oz.au/~bjpop/buddha/ &quot;declarative debugging&quot; tools] but to our knowledge, no such tool is production-ready.<br />
<br />
== Why do I get an &quot;undefined symbol&quot; linker error when compiling? ==<br />
<br />
If you're using GHC 6, you should pass <tt>--make</tt> so that GHC will automatically link the appropriate Haskell libraries.<br />
<br />
== How can I get a stack backtrace when my program throws an exception? ==<br />
<br />
The standard stack in GHC Haskell doesn't represent nested function calls. The more informative stack is the profiling cost-center stack, which only exists if your code is built for profiling.<br />
<br />
With GHC 7 you can do something like this:<br />
<br />
<pre>$ ghc -fforce-recomp -prof -auto-all -rtsopts foo.hs</pre><br />
For GHC 6 you should leave off <tt>-rtsopts</tt>, and you'll probably want <tt>--make</tt>.<br />
<br />
You can then run your program with the [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-debugging <tt>-xc</tt> RTS option`]:<br />
<br />
<pre>$ ./foo +RTS -xc</pre><br />
== How can I do automated unit testing? ==<br />
<br />
See the [http://book.realworldhaskell.org/read/testing-and-quality-assurance.html testing chapter] in ''Real World Haskell''.<br />
<br />
== How can I find and fix performance problems? ==<br />
<br />
See the [http://book.realworldhaskell.org/read/profiling-and-optimization.html profiling and optimization chapter] in ''Real World Haskell''.<br />
<br />
= Modules =<br />
<br />
== How do I deal with name clashes between modules? ==<br />
<br />
You can disambiguate by prefixing a module name:<br />
<br />
<haskell><br />
import Data.List<br />
import Data.Map<br />
<br />
f = Data.List.lookup 7<br />
g = Data.Map.lookup 7<br />
</haskell><br />
<br />
The import syntax gives you additional control:<br />
<br />
* With <hask>import qualified Foo</hask> the names from <hask>Foo</hask> can ''only'' be used qualified, and won't clash with unqualified names.<br />
<br />
* With <hask>import Foo as M</hask> you'd write <hask>M.x</hask> instead of <hask>Foo.x</hask>.<br />
<br />
You can combine these two features. A more common way to write the above example is:<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
f = lookup 7 -- unqualified, from Prelude<br />
g = M.lookup 7<br />
</haskell><br />
<br />
In general, most combinations of <hask>import</hask> features are allowed. You<br />
can combine <hask>as</hask> and <hask>qualified</hask> with import and<br />
<hask>hiding</hask> lists. You can import two modules <hask>as</hask> the same<br />
name, or one module <hask>as</hask> two names, with different import and<br />
<hask>hiding</hask> lists, <hask>qualified</hask> or unqualified, etc.<br />
<br />
== How do I control the <hask>Prelude</hask> import? ==<br />
<br />
Haskell modules implicitly import <hask>Prelude</hask>, unless an explicit import is given. So you can write<br />
<br />
<haskell><br />
import Prelude as P hiding (length, head)<br />
</haskell><br />
<br />
== How do I qualify the name of an infix operator? ==<br />
<br />
You prefix the module name, as usual:<br />
<br />
<haskell><br />
x = 2 + 3<br />
y = 2 Prelude.+ 3<br />
<br />
f = (+) 7<br />
g = (Prelude.+) 7<br />
</haskell><br />
<br />
This looks weird but works fine. The syntax does clash a bit:<br />
<br />
<haskell><br />
xs = [False..True] -- wrong, parses as qualified name<br />
xs = [False .. True] -- ok<br />
</haskell><br />
<br />
== How do I mention an infix operator in an export / import / <hask>hiding</hask> list? ==<br />
<br />
The same way as elsewhere: enclose it in parentheses.<br />
<br />
<haskell><br />
import Prelude ( succ, (+), length, (*) )<br />
</haskell><br />
<br />
== I listed a data type in my import list but its data constructors aren't in scope. How do I fix it? ==<br />
<br />
You have to import data constructors explicitly:<br />
<br />
<haskell><br />
import Prelude ( Maybe ) -- the type only<br />
import Prelude ( Maybe(Nothing) ) -- type and specific constructor(s)<br />
import Prelude ( Maybe(..) ) -- type and all its constructors<br />
</haskell><br />
<br />
== How can I import and re-export a whole module? ==<br />
<br />
<haskell><br />
module Bar ( module Foo ) where<br />
import Foo<br />
</haskell><br />
<br />
== How can I export another module ''and'' everything defined in this module? ==<br />
<br />
<haskell><br />
module Bar ( module Bar, module Foo ) where<br />
import Foo<br />
</haskell><br />
<br />
= The M-word =<br />
<br />
See also &quot;[[What a Monad is not]]&quot;.<br />
<br />
== I heard Haskell is about monads. I heard that the core feature of Haskell is monads. Is that true? ==<br />
<br />
Absolutely not.<br />
<br />
== Do I need to understand monads in order to do IO? ==<br />
<br />
Not really. &quot;<tt>Monad</tt>&quot; is the name of a generic API that applies to many different types, including the <hask>IO</hask> type. If you're only thinking about IO, you don't need to worry about how this API generalizes.<br />
<br />
See the [[Introduction to IO]].<br />
<br />
== What should I know before trying to understand monads? ==<br />
<br />
Let's look at part of the definition of <hask>Monad</hask>:<br /><br /><br />
<br />
<haskell><br />
class Monad m where<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
</haskell><br />
<br />
This uses a lot of features:<br />
<br />
* first-class functions: the second argument to <hask>(>>=)</hask> is a function<br />
<br />
* type constructors (here <hask>m</hask>)<br />
<br />
* type class polymorphism<br />
<br />
* type class polymorphism ''over'' type constructors (which few other languages have)<br />
<br />
* parametric (not type class) polymorphism, over <hask>a</hask> and <hask>b</hask><br />
<br />
Each of these features is more fundamental than the specific idea of monads. If you understand each feature, then <hask>Monad</hask> is a small example of how they fit together. <hask>Functor</hask> is a slightly simpler example, and you can start there instead (see [[Typeclassopedia]]).<br />
<br />
== Aren't monads just a hack for handling impure things in a pure language? ==<br />
<br />
No. This is wrong in several ways.<br />
<br />
First, '''<hask>Monad</hask> isn't special.''' <hask>Monad</hask> is an ordinary Haskell type class. You can define it yourself in a few lines of pure Haskell code, so it's definitely not adding magical new capabilities to the language. Besides that, <hask>Monad</hask> is an API, not an implementation.<br /><br /><br />
<br />
(The <hask>do</hask> syntax ''is'' special, but it's only [[syntactic sugar]]. There's a straightforward translation to ordinary function calls, lambdas, etc.)<br /><br /><br />
<br />
Second, '''most monads have nothing to do with effects or "impurity".''' The <hask>Monad</hask> API is implemented by many different type constructors, including <hask>Maybe</hask> and <hask>[]</hask>. Lists and <hask>Maybe</hask> values are straightforward, familiar data values. There's nothing "impure" about them.<br /><br /><br />
<br />
Third, '''<hask>IO</hask> is not an exception to purity.''' IO actions are pure, first-class values like any other. You can create, store, and evaluate them without causing side effects. IO actions are just ''descriptions'' of IO which ''could'' be performed.<br /><br />
<br />
In short, Haskell programs are pure-functional programs which compute imperative programs.<br />
<br />
It's true that <hask>IO</hask> implements the <hask>Monad</hask> API, but that's not fundamental. You could instead use non-overloaded functions like<br /><br /><br />
<br />
<haskell><br />
returnIO :: a -> IO a<br />
bindIO :: IO a -> (a -> IO b) -> IO b<br />
</haskell><br />
<br />
<br />to glue together IO actions, and it would all work out basically the same. We use the generic <hask>Monad</hask> API for <hask>IO</hask> not because we have to, but because it lets us reuse convenient syntax and [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html libraries]. Indeed, you can [[Introduction to IO|introduce <tt>IO</tt>]] without mentioning <hask>Monad</hask> at all.<br />
<br />
== I heard monads are like burritos or space suits full of nuclear waste. Is that true? ==<br />
<br />
These analogies are not helpful. See [http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/ &quot;Abstraction, intuition, and the 'monad tutorial fallacy&quot;'].<br />
<br />
== I can use monads but I feel like I still don't &quot;get&quot; them. What am I missing? ==<br />
<br />
You're not necessarily missing anything. &quot;<tt>Monad</tt>&quot; is just the name of a generic API that applies to many different types. The types implementing the <tt>Monad</tt> API don't have a lot in common.<br />
<br />
You might want to read &quot;[[Typeclassopedia]]&quot; to see how <tt>Monad</tt> fits in with other similar APIs.<br />
<br />
== What's the difference between <hask>State s</hask> and <hask>ST s</hask> monads? ==<br />
<br />
<tt>State s a</tt> is just a wrapper for the function type <hask>s -> (a, s)</hask>: a function that takes an &quot;old state&quot; and returns a &quot;new state&quot; along with its result. You can implement <hask>State</hask> in a few lines of standard Haskell, without any special help from the compiler.<br />
<br />
<hask>ST</hask> gives you true mutable variables with in-place update. You can't implement it yourself in standard Haskell. In GHC, <hask>STRef</hask> and <hask>IORef</hask> will behave the same way at runtime. The difference is the extra compile-time safety checking associated with <hask>runST</hask>.<br />
<br />
= Concurrency and parallelism =<br />
<br />
See also notes on [[parallel]] and [[Concurrency|concurrent]] programming.<br />
<br />
== How can I do X without resorting to threads? ==<br />
<br />
That's usually the wrong attitude. Threads are useful for solving problems. The attitude comes from other languages where some combination of the following holds:<br />
<br />
* Per-thread overhead consumes a lot of memory or CPU<br />
<br />
* Thread APIs are cumbersome, sometimes due to lacking first-class functions or IO actions<br />
<br />
* The thread implementation is fundamentally broken, e.g. a global interpreter lock<br />
<br />
* Threads break easily because programs constantly mutate implicitly-shared state<br />
<br />
None of these is true in GHC Haskell. Threads have disadvantages and are not always the right tool. But avoiding them at all costs is counterproductive.<br />
<br />
== What's the difference between concurrency and parallelism? ==<br />
<br />
Briefly: concurrency describes semantics; parallelism describes an implementation property.<br />
<br />
Concurrent programs are written with explicit threads of control. Concurrent semantics fit naturally with certain real-world problems, like a network server talking to many simultaneous clients. This is still a nice model for writing a network server, even if you only intend to run it on one CPU core — concurrency without parallelism.<br />
<br />
Parallel programs are those which run on multiple CPU cores simultaneously, regardless of how they were implemented.<br />
<br />
Concurrency is a popular way to obtain parallel performance, but converting a pure computation to use concurrent semantics is difficult and error-prone. GHC Haskell provides "[http://hackage.haskell.org/packages/archive/parallel/latest/doc/html/Control-Parallel-Strategies.html semi-implicit parallelism]" as an alternative. Adding these "annotations" to a program cannot change its behavior.<br />
<br />
There's a longer discussion on the [http://ghcmutterings.wordpress.com/2009/10/06/parallelism-concurrency/ GHC blog].<br />
<br />
== How do <hask>par</hask>, <hask>pseq</hask>, and <hask>seq</hask> relate? ==<br />
<br />
The expression <hask>par x y</hask> is semantically equivalent to <hask>y</hask>, but suggests to the runtime system that evaluating <hask>x</hask> in parallel might be a good idea. Usually <hask>x</hask> would be a variable referring to a thunk (unevaluated expression) that will later be needed.<br /><br /><br />
<br />
Now consider <hask>par x (x+y)</hask>. Evaluating this expression suggests evaluating <hask>x</hask> in parallel. But before the runtime system can act on that suggestion, we evaluate <hask>(x+y)</hask>, which will evaluate both <hask>x</hask> and <hask>y</hask> in sequence. It would be better to work on <hask>y</hask> for a while, and only demand <hask>x</hask> later, after perhaps some parallel work has occurred. We can use <hask>pseq</hask> to force this evaluation order, as in <hask>par x (pseq y (x+y))</hask>.<br /><br /><br />
<br />
The [http://hackage.haskell.org/packages/archive/parallel/latest/doc/html/Control-Parallel-Strategies.html Strategies] module provides a nicer interface to these <hask>par</hask> / <hask>pseq</hask> tricks.<br />
<br />
<p><hask>seq</hask> is similar to <hask>pseq</hask> but provides a weaker guarantee. [http://www.mail-archive.com/glasgow-haskell-users@haskell.org/msg10973.html The details] are subtle; suffice to say that if you're controlling evaluation order, you want <hask>pseq</hask>.</p><br />
<br />
== How do I do event-based IO in GHC Haskell? Should I call <tt>select</tt>, <tt>epoll</tt>, etc? ==<br />
<br />
No; just do blocking IO from multiple threads, and GHC's runtime system will make these calls for you. GHC Haskell gives you the performance benefits of event-based IO without making you turn your code inside-out.<br />
<br />
Threads in GHC are lightweight — both in performance and in the mental effort of using them. You can handle [http://blog.johantibell.com/2010/09/final-version-of-our-ghc-io-manager.html ten thousand concurrent requests] at high throughput with a naive "one thread per client" model.<br />
<br />
== What's the difference between <hask>forkIO</hask> and <hask>forkOS</hask>? ==<br />
<br />
It only matters if you're calling into a C library that cares about thread-local state. In that case, <hask>forkOS</hask> guarantees that the C library will see the same OS thread each time. Any difference beyond that is an implementation detail and subject to change.<br />
<br />
== How can I wait for a thread to finish and produce a result? ==<br />
<br />
There's a few libraries for this on Hackage, like [http://hackage.haskell.org/package/async <tt>async</tt>], [http://hackage.haskell.org/package/spawn <tt>spawn</tt>], and [http://hackage.haskell.org/package/threads <tt>threads</tt>].<br />
<br />
It's not hard to implement this yourself using [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent-MVar.html <tt>MVar</tt>], though it's harder to get the exception handling right.<br />
<br />
= IRC =<br />
<br />
== What does lambdabot's "info" command do? ==<br />
<br />
At first, it seems like it just echoes whatever you type:<br />
<br />
<user> ?info foo bar baz<br />
<lambdabot> foo bar baz<br />
<br />
What is actually happening is that it autocorrects to the "undo" command, which desugars do blocks according to the Report's rules. So, a more interesting example might look like this:<br />
<br />
<user> ?info do { foo; x <- bar; baz }<br />
<lambdabot> foo >> bar >>= \ x -> baz<br />
<br />
<br />
= Error messages and warnings =<br />
<br />
== Not in scope: `catch' ==<br />
<br />
The function "catch" is removed from Prelude, add the line:<br />
<haskell>import Control.Exception</haskell><br />
(Note, that this might lead to an error if you compile the same code with an older [[GHC]].)<br />
<br />
<br />
[[Category:FAQ]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Questions_and_answers&diff=63376Questions and answers2020-07-23T06:17:47Z<p>Ysangkok: fix link to keeping intermediates</p>
<hr />
<div>Feel free to ask your questions here. Please sign your question using four tildes (<nowiki>~~~~</nowiki>). Questions and answers will be organised as they are added, and linked from here.<br />
<br />
[[Category:Community]]<br />
[[Category:FAQ]]<br />
<br />
== Questions and answers ==<br />
<br />
;Q. What are the best places to ask beginner questions?<br />
:A. The [http://www.haskell.org/pipermail/beginners/ beginners] mailing list, the [http://haskell.org/pipermail/haskell-cafe/ haskell-cafe] mailing list, or the [http://haskell.org/haskellwiki/IRC_channel #haskell irc channel].<br />
<br />
;Q. Symbols are valid in Haskell function names. What are the rules for which characters can be used?<br />
:A. Refer to the [[Language and library specification]] under [http://haskell.org/onlinereport/lexemes.html#ids "Identifiers and Operators"]. Variable identifiers start with a lowercase letter, constructor identifiers with an uppercase letter and both can contain underscores, single quotes, letters and digits. Operators are formed from one or more of '<hask>!#$%&*+./<=>?@\^|-~</hask>'. Constructors can be operator names, so long as they start with a '<hask>:</hask>' (e.g., <hask>:+</hask> for <hask>Data.Complex</hask>).<br />
<br />
;Q. Are fixity declarations required for functions defined with symbol names?<br />
:A. No. The default fixity is infixl 9.<br />
<br />
;Q. GHC does a wide variety of optimisations. How can I view the optimisations that are performed?<br />
:A. Keep around the [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/separate_compilation.html#keeping-intermediate-files intermediate compiler outputs] using --keep-tmp-files or -ddump-simpl.<br />
<br />
;Q. Can I use multiple CPUs with a Haskell program?<br />
:A. Yes, GHC 6.6 supports symmetric multicore processing. see [[GHC/Concurrency#Multiprocessor GHC]]<br />
<br />
;Q. I just wrote this really cool program! Who can I show it to?<br />
<br />
;Q. I just wrote this interesting program that someone else might find useful. Where can I put it?<br />
:A. Provided you are ok with the [[HaskellWiki:Copyrights | simple permissive license]], you can put it here on the wiki. To do that, you must first [[Special:Userlogin |create a login]]. Once that is done, start a page for your project. (People often add a link to their projects from their wiki home page.) Before starting the page, check out the [[HaskellWiki:Guidelines | guidelines for pages]]. If you need it, there is also [[Help:Editing | help on editing wiki pages]]. Finally, don't forget to categorize your new page.<br />
<br />
;Q. I have a simple function; it behaves like <hask>map</hask>, but also threads state through the computation. Is there a standard library function that does the same thing?<br />
:A. Yes. <hask>mapAccumL</hask>. You could also use a state monad.<br />
<br />
== Uncategorised questions ==<br />
<br />
* Which is faster? <hask>putStr (xs ++ ys ++ xs)</hask> or <hask>putStr xs; putStr ys; putStr zs</hask>? How much of a difference does it make? [[User:MathematicalOrchid|MathematicalOrchid]] 11:47, 22 January 2007 (UTC)<br />
** hmm, <hask>(++)</hask> is a very slow operation which is O(n) in the length of the first string. for short strings the difference should be small, for very long string you'll see a big difference. concrete timing depends on putStr... --[[User:JohannesAhlmann|Johannes Ahlmann]] 12:29, 22 January 2007 (UTC)<br />
*** <hask>(++)</hask> is right-associative when there's several, resulting in the fastest possible performance. (I understand this is why the <hask>Show</hask> class is so damn weird...) Even so, I wonder if it's more efficient to join strings or use real I/O... [[User:MathematicalOrchid|MathematicalOrchid]] 13:23, 22 January 2007 (UTC)<br />
<br />
* I want to write a program that renders bitmap graphics. Is there ''any'' way to get this onto the video screen in Haskell? Is there any way to get the data saved to disk in some sane file format? [[User:MathematicalOrchid|MathematicalOrchid]] 11:47, 22 January 2007 (UTC)<br />
** have a look at [[Libraries and tools/GUI libraries]]. i'd have a look at [http://haskell.org/graphics/ HGL], [http://haskell.org/HOpenGL/ HOpenGL] and/or [http://haskell.org/gtk2hs/ gtk2hs]. of these, at least gtk2hs has some image handling routines. for pure image format libraries there's unfortunately a little less :(<br />
*** This is where it starts to get messy... I already tried using HGL from within Hugs. (Drawing 'pixels' that are really small squares.) However, once it's drawn enough pixels, I get a Dr Watson error and Hugs ungracefully terminates. (Actually, the latest version of Hugs seems to do this a lot.) So I went to compile it with GHC - and it seems GHC doesn't come with that library at all. And the page you linked says that HGL is 'currently broken on Win32'. Hmm... OK, I'm confused now. Then there's HOpenGL. (Is that the same thing as Graphics.Rendering.OpenGL, or is it seperate?) It's nice to know you can have hardware 3D acceleration if you want it, but maybe a tad overkill for just writing a bitmap to the display. Also, IIRC, doesn't OpenGL require you to open a window in a platform-specific way first? And then there's gtk2hs. I don't know if you can run Gtk on Win32... but that one looks like it might be worth investigating. [[User:MathematicalOrchid|MathematicalOrchid]] 15:52, 22 January 2007 (UTC)<br />
*** Ah-hah! It seems that burried away in gtk2hs is a fair of functions to load and save PNG images. That will do nicely... if I can figure out how to use it. :-) [[User:MathematicalOrchid|MathematicalOrchid]] 16:08, 22 January 2007 (UTC)<br />
**** I spoke too soon... I was looking at the cairo part. Apparently the main Gtk2hs part supports JPEG and others too. And it provides functions which look like you can plot pixels with them. Now, if I can figure out how to install this stuff... [[User:MathematicalOrchid|MathematicalOrchid]] 22:10, 22 January 2007 (UTC)</div>Ysangkokhttps://wiki.haskell.org/index.php?title=FAQ&diff=63375FAQ2020-07-23T06:16:24Z<p>Ysangkok: fix link to ghc language extensiosn</p>
<hr />
<div>This FAQ is based on actual frequently-asked questions from [[IRC channel|<tt>#haskell</tt> IRC]]. The goal is simply to collect and edit some common answers. Beginner questions are still welcome on IRC, as always.<br />
<br />
This is a wiki, so please edit the text with any improvements you have. And feel free to add new questions, if they are frequently asked.<br />
<br />
== See also ==<br />
<br />
* [[:Category:FAQ|Other FAQs]]<br />
* The [[Introduction|introduction to Haskell]], and the FAQ at the end of that document.<br />
<br />
__TOC__<br />
<br />
= The real world =<br />
<br />
== Should I learn Haskell? ==<br />
<br />
That depends on your goals. In general, Haskellers will tell you that you should learn Haskell. :)<br />
<br />
Learning Haskell is fun. It will expand your mind and make you a better programmer in other languages. These are the immediate benefits.<br />
<br />
Haskell is also a great tool for solving real-world problems, but it can take many months of study to get to that point.<br />
<br />
== Is Haskell hard to learn? ==<br />
<br />
Any competent programmer can learn Haskell, but it will take more time and motivation than you may expect.<br />
<br />
Haskell requires learning a new way to think, not just new syntax for old concepts. This can be incredibly frustrating, as simple tasks seem impossibly difficult.<br />
<br />
Those with no prior programming experience may actually have an easier time learning Haskell, because they have less to un-learn.<br />
<br />
== How can I get started with Haskell ''right now''? ==<br />
<br />
Check out [http://tryhaskell.org/ Try Haskell].<br />
<br />
Also: [https://www.fpcomplete.com/business/fp-haskell-center/ FP Complete's free online IDE]<br />
<br />
<br />
== What should I read for learning Haskell? ==<br />
<br />
The most popular resources are [http://learnyouahaskell.com/ ''Learn You a Haskell''] and [http://book.realworldhaskell.org/ ''Real World Haskell'']. Each is available online for free, or can be purchased in hardcopy.<br />
<br />
Many other [[tutorials]], [[books]], and [[Learning Haskell|other resources]] are available.<br />
<br />
There's also the [https://www.schoolofhaskell.com/ School of Haskell] which has a set of free online tutorials with runnable examples.<br />
<br />
== How can I get help with learning Haskell? ==<br />
<br />
Your options include:<br />
<br />
* [[IRC channel|<tt>#haskell</tt> on Freenode IRC]]<br />
* [http://stackoverflow.com/questions/tagged/haskell Stack Overflow]<br />
* The [http://www.haskell.org/mailman/listinfo/haskell-cafe Haskell-Cafe] mailing list<br />
<br />
== Will Haskell get me a job? ==<br />
<br />
There are plenty of [[Haskell in industry|companies using Haskell]], but it's still a tiny number compared to the software industry as a whole.<br />
<br />
There are also many companies which do not use Haskell, but prefer to hire people who know Haskell. It indicates that you learned something hard and obscure just for fun, which employers take as a sign of intelligence.<br />
<br />
== Is Haskell similar to Language X? ==<br />
<br />
Probably not. It's best if you approach Haskell with a clean slate. Most analogies to another language will break down somewhere, often in a subtle and misleading way. If you first learn the Haskell concepts for what they are, you can then draw useful connections to other languages.<br />
<br />
== What's the relationship between Haskell and GHC? ==<br />
<br />
Haskell is not a piece of software; it is a specification for a standardized programming language. The [[Language and library specification|latest version of the spec]] is the Haskell 2010 Report.<br />
<br />
[http://www.haskell.org/ghc/ GHC] is the Glorious Glasgow Haskell Compiler. It is by far the most popular and &quot;production-ready&quot; implementation of the standard Haskell language. It also implements many [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/lang.html extension] features that go above and beyond standard Haskell. Many programs use these features and so aren't &quot;written in Haskell&quot; in the strictest sense.<br />
<br />
You can use the term &quot;Haskell&quot; to refer to the standard language, and &quot;GHC Haskell&quot; when including GHC extensions.<br />
<br />
Besides GHC, several other [[implementations]] of Haskell are available. Each one provides its own extensions, some of which don't exist in GHC.<br />
<br />
== What is the Haskell Platform? ==<br />
<br />
The [http://hackage.haskell.org/platform/ Haskell Platform] is a copy of GHC bundled with a &quot;blessed&quot; set of useful libraries. It is the easiest way to get started with Haskell. It's not essential to start with the Platform, because you can install the same libraries as needed.<br />
<br />
== What is Haskell Prime (Haskell')? ==<br />
<br />
[http://prime.haskell.org/ Haskell Prime] is a process which produces new versions of the Haskell language spec. It does not refer to a particular present or future version of Haskell.<br />
<br />
== My textbook uses Haskell 98. Is it very different from Haskell 2010? ==<br />
<br />
No. Haskell 2010 is a [http://www.haskell.org/pipermail/haskell/2009-November/021750.html very conservative change] to Haskell 98. It fixes small syntactic flaws, and standardizes several well-behaved extensions which GHC has supported for years.<br />
<br />
The standardization process is very slow because standardizing a flawed language can be a costly mistake. Extensions are accepted only once they are considered mature and well-understood.<br />
<br />
== How do I get libraries for Haskell? ==<br />
<br />
You can find libraries on [http://hackage.haskell.org/packages/archive/pkg-list.html Hackage], and install them with [[Cabal-Install|<tt>cabal-install</tt>]].<br />
<br />
== Is Haskell compiled? ==<br />
<br />
Usually. GHC, the most popular Haskell implementation, has an optimizing ahead-of-time native-code compiler, as well as a bytecode compiler and interpreter for interactive use.<br />
<br />
Haskell itself is not a &quot;compiled language&quot; because nothing in the Haskell spec requires implementations to be compilers.<br />
<br />
== Does Haskell have an interpreter? ==<br />
<br />
Yes, but maybe you instead mean &quot;Is there a program where I can type Haskell code and see it run immediately?&quot;. GHCi provides such a &quot;read-evaluate-print loop&quot;.<br />
<br />
<br />
== Which project can I join? ==<br />
<br />
See [[Haskell projects needing help]].<br />
<br />
= Paradigms =<br />
<br />
== Is learning Haskell the best way to learn functional programming? ==<br />
<br />
Not necessarily! Haskell is not a ''typical'' functional language. It can be overwhelming to learn the basic concepts of functional programming alongside static types, algebraic data, laziness, type classes, first-class IO, etc. For an introduction to FP by itself you might want to learn Scheme, or play with the FP features in your current favorite language.<br />
<br />
That said, many people choose Haskell as an introduction to FP and have success with that approach. Haskell has an extremely active community of people teaching, doing research, writing libraries, etc. Haskell is where interesting things happen in the FP space, so it's an exciting place to jump in.<br />
<br />
== I heard Haskell is pure functional. Does that mean I can't do imperative / OOP / aspect-oriented / logic programming in Haskell? ==<br />
<br />
No, &quot;pure functional&quot; has a specific technical meaning. It doesn't mean that functional is the only supported paradigm.<br />
<br />
Paradigms describe the techniques used in a particular program. For example, the Linux kernel is written in C, with pervasive use of functional, object-oriented, and aspect-oriented programming. The most we can say about a ''language'' is that it encourages or discourages a particular paradigm. Haskell is very flexible and can comfortably accommodate most paradigms, even when there is no built-in support.<br />
<br />
== I heard Haskell is pure functional. Does that mean it can't do IO? ==<br />
<br />
No; [[Introduction to IO|IO in Haskell]] is straightforward.<br />
<br />
== I heard Haskell is pure functional. Does that mean it doesn't have mutable state? ==<br />
<br />
No; see [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-IORef.html <tt>IORef</tt>] for a simple example. A more sophisticated example is [http://book.realworldhaskell.org/read/software-transactional-memory.html software transactional memory], which provides concurrent state more sophisticated than you'll find in most other imperative languages.<br />
<br />
== Wait, is Haskell imperative or is it functional? ==<br />
<br />
Both. In Haskell, functions are first class, and so are imperative actions.<br />
<br />
There is no reason to consider &quot;imperative language&quot; and &quot;functional language&quot; as mutually exclusive. It's only a historical accident that a few of the most popular imperative languages are unusually bad at functional programming. Functional imperative programming is extremely powerful and is supported by many languages.<br />
<br />
= Math =<br />
<br />
== Was Haskell designed by mathematicians? ==<br />
<br />
Haskell was designed by people studying programming language design. Perhaps programmers would consider them to be mathematicians, while mathematicians would consider them to be programmers.<br />
<br />
Designing a programming language is a hard thing to do. There are many non-obvious tradeoffs, and many lessons to be learned from past failures and successes. Yet many of today's most popular languages were designed by people who hadn't done their homework.<br />
<br />
Haskell was designed by people who knew what they were doing. It's not perfect, but the contrast to an amateur's design is striking.<br />
<br />
== Do I need to know advanced math in order to use Haskell? ==<br />
<br />
No. Certain concepts in Haskell are named after concepts in advanced math. But other languages also appropriate math terminology: consider &quot;[http://en.wikipedia.org/wiki/Singleton_pattern singleton]&quot;, not to mention &quot;function&quot; and &quot;variable&quot;. The way these programming concepts relate to actual mathematics is not necessarily important or relevant.<br />
<br />
In addition, some people write articles about advanced math, using Haskell syntax as their notation. These articles are interesting, but the connection to everyday programming work is usually remote.<br />
<br />
Knowing advanced math will enrich your experience using Haskell, but is by no means a prerequisite.<br />
<br />
= Types =<br />
<br />
== Doesn't a static type system just make it harder to write programs? ==<br />
<br />
Yes. In particular, it makes it ''much'' harder to write ''incorrect'' programs.<br />
<br />
The tradeoff is that correct programs also become somewhat harder to write. In Haskell, features like type inference mitigate this burden to a large extent.<br />
<br />
== How do I make a list with elements of different types? ==<br />
<br />
Are you sure that's what you want? Consider instead creating a single data type to encompass the alternatives:<br />
<br />
<haskell><br />
data Identifier<br />
= ByNumber Int<br />
| ByName String<br />
<br />
doStuff :: [Identifier] -> Whatever<br />
</haskell><br />
<br />
In many dynamically-typed languages you aren't allowed to create &quot;variant types&quot; like this. The type system itself is used as a single ad-hoc global variant type. Keep this in mind if you're translating designs from a dynamically-typed language to Haskell.<br />
<br />
== No really, how do I make a list of elements of different types? ==<br />
<br />
Well, you can't avoid putting all your values into one type. But sometimes the &quot;variant type&quot; approach above is too restrictive. Maybe you need to let other people add to the set of allowed types, the way [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Exception.html Control.Exception] allows users to define new exception types.<br />
<br />
You can use an [[existential type]], possibly with a type class. Or you can use [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Dynamic.html Data.Dynamic].<br />
<br />
== I'm making an RPG. Should I define a type for each kind of monster, and a type class for them? ==<br />
<br />
Probably not. Some languages require a new type for each new behavior. In Haskell, behaviors are functions or IO actions, which are first-class values. So you can store behaviors in an ordinary data type:<br />
<br />
<haskell><br />
data MonsterOps = MonsterOps<br />
{ new :: Monster<br />
, move :: Monster -> Monster<br />
, attack :: Monster -> Player -> Player }<br />
<br />
data Monster = Monster<br />
{ position :: (Int, Int)<br />
, hitpoints :: Double }<br />
<br />
beholder :: MonsterOps<br />
beholder = MonsterOps new move attack where<br />
new = Monster (0,0) 9000<br />
move self = ...<br />
attack self player = ...<br />
</haskell><br />
<br />
This approach is especially nice if you want to generate or transform behaviors on the fly. See the article [http://lukepalmer.wordpress.com/2010/01/24/haskell-antipattern-existential-typeclass/ &quot;Haskell Antipattern: Existential Typeclass&quot;] for a longer discussion.<br />
<br />
== What's the difference between <hask>Integer</hask> and <hask>Int</hask>? ==<br />
<br />
<p><hask>Integer</hask> can represent arbitrarily large integers, up to using all of the storage on your machine.</p><br />
<br />
<p><hask>Int</hask> can only represent integers in a finite range. The [http://www.haskell.org/onlinereport/haskell2010/haskellch6.html#dx13-135009 language standard] only guarantees a range of -2<sup>29</sup> to (2<sup>29</sup> - 1). Most implementations will provide a full machine-size signed integer, i.e. 32 or 64 bits.</p><br />
<br />
Operations on <hask>Int</hask> can be much faster than operations on <hask>Integer</hask>, but overflow and underflow can cause weird bugs. Using <hask>Int</hask> in an initial design could be considered premature optimization. Unfortunately, many standard library functions (e.g. <hask>length</hask>, <hask>take</hask>) use <hask>Int</hask>.<br />
<br />
== How do I convert type <tt>A</tt> to type <tt>B</tt>? ==<br />
<br />
This is just another way of asking for a function of type <hask>A -> B</hask>. For example, you can convert <hask>Double</hask> to <hask>Int</hask> with <hask>round</hask>, <hask>ceiling</hask>, or <hask>floor</hask>. Haskell does not privilege one of these as ''the'' conversion.<br />
<br />
== Does Haskell have type casts? ==<br />
<br />
The word &quot;cast&quot; can mean a lot of different things.<br />
<br />
* You want to convert a value from one type to another, preserving some idea of what it means. For example, you might convert an <hask>Int</hask> to a <hask>Double</hask> which represents the same integer. In this case you'd just use a function of type <hask>Int -> Double</hask>, such as <hask>fromIntegral</hask>. Haskell doesn't provide special rules or syntax for these functions. See also the previous question.<br /><br /><br />
* You want to pass a value of more specific type to a function expecting a less specific type. There's no syntax for this in Haskell; you just do it. For example you can pass <hask>x :: Int</hask> to <hask>show :: (Show a) => a -> String</hask>, which automatically specializes the type of <hask>show</hask> to <hask>Int -> String</hask>. Note that Haskell does not have subtyping, so this only happens in the context of instantiating type variables.<br /><br /><br />
* You want to use a value of less specific type under the assumption of a more specific type, with a checkable runtime error if they do not match. This is rarely the right way to do things in Haskell, and probably indicates a conceptual / design problem instead. If you really do need such a cast, you can use [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Typeable.html#v:cast <tt>cast</tt>] from [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Typeable.html Data.Typeable]. In this case the &quot;checkable runtime error&quot; is <hask>cast</hask> returning <hask>Nothing</hask>. Note that Haskell does not have subtyping, so this only happens in the context of instantiating type variables.<br /><br /><br />
* You want to use a value of less specific type under the assumption of a more specific type, and if the assumption is incorrect, the program is allowed to segfault / silently corrupt data / give the attacker a root shell / send illicit photos to your boss. Also known as a "reinterpret cast". GHC Haskell has a way to do this, but I dare not speak its name. It's so dangerous and so unlikely to be what you want that it has no place in a general FAQ. You can ask on IRC or read the docs if you have the right kind of morbid curiosity.<br />
<br />
== How do I convert from one numeric type to another? ==<br />
<br />
Probably using one of these:<br />
<br />
<haskell><br />
fromIntegral :: (Integral a, Num b ) => a -> b<br />
realToFrac :: (Real a, Fractional b) => a -> b<br />
</haskell><br />
<br />
<p><hask>fromIntegral</hask> converts to a wider range of types, but <hask>realToFrac</hask> converts from types which aren't integers.</p><br />
<br />
== How do I convert <hask>Maybe Int</hask> to <hask>Int</hask>? ==<br />
<br />
Use pattern-matching. If <hask>mx :: Maybe Int</hask>:<br />
<br />
<haskell><br />
case mx of<br />
Just x -> ...<br />
Nothing -> ...<br />
</haskell><br />
<br />
This forces you to consider the <hask>Nothing</hask> case, and is the main advantage of <hask>Maybe</hask>, compared to adding a <tt>null</tt> value to every type.<br />
<br />
See also the functions [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html#v:maybe <tt>maybe</tt>] and [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html#v:fromMaybe <tt>fromMaybe</tt>] in the module [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html Data.Maybe].<br />
<br />
''Do not'' use <hask>fromJust</hask>, because passing <hask>Nothing</hask> will crash your program with a supremely unhelpful error message. Even when you want to assume the value is not <hask>Nothing</hask>, you can provide a better error message:<br />
<br />
<haskell><br />
let x = fromMaybe (error "custom error message") mx in ...<br />
</haskell><br />
<br />
If you pattern-match without a <hask>Nothing</hask> case:<br />
<br />
<haskell><br />
let Just x = mx in ...<br />
</haskell><br />
<br />
you'll at least get a line number in the error message:<br />
<br />
<pre><br />
*** Exception: foo.hs:2:9-24: Irrefutable pattern failed for pattern Data.Maybe.Just x<br />
</pre><br />
<br />
== How do I convert <hask>IO Int</hask> to <hask>Int</hask>? ==<br />
<br />
You can't; they represent totally different things. An <hask>Int</hask> is an integer. An <hask>IO Int</hask> is a description of how some IO could be performed, in the future, to produce an integer. The IO hasn't been performed yet, and might never happen or might happen more than once.<br />
<br />
See the [[Introduction to IO]].<br />
<br />
== How do I convert between <hask>String</hask> (or <hask>Text</hask>) and <hask>ByteString</hask>? ==<br />
<br />
<p><hask>String</hask> represents a sequence of Unicode characters. <hask>ByteString</hask> represents a sequence of bytes. There are many different, incompatible ways to represent Unicode characters as bytes. See [http://www.joelonsoftware.com/articles/Unicode.html this article] if you're fuzzy on the character / byte distinction.</p><br />
<br />
The module [http://hackage.haskell.org/packages/archive/text/0.11.1.5/doc/html/Data-Text-Encoding.html Data.Text.Encoding] from the <tt>text</tt> package provides functions for common Unicode encodings. For more obscure / legacy encodings, see the [http://hackage.haskell.org/package/text-icu <tt>text-icu</tt>] package.<br />
<br />
== How do I catch the error thrown by <hask>read</hask> on a parse failure? ==<br />
<br />
Don't. Instead use<br />
<br />
<haskell><br />
import Text.Read (readMaybe)<br />
readMaybe :: Read a => String -> Maybe a<br />
</haskell><br />
<br />
which returns a <tt>Nothing</tt> in the case of parse failure.<br />
<br />
== What's the difference between <hask>type</hask>, <hask>data</hask>, and <hask>newtype</hask>? ==<br />
<br />
<p><hask>type</hask> introduces a synonym, which is fully interchangeable with the original type:</p><br />
<br />
<haskell><br />
type Foo = Int<br />
<br />
main = print ((2 :: Int) + (3 :: Foo))<br />
</haskell><br />
<br />
So it provides convenience and documentation, but no additional type checking.<br />
<br />
<p><hask>data</hask> is used to define new data types, distinct from any existing type.</p><br />
<br />
<p><hask>newtype</hask> can mostly be understood as a restricted form of <hask>data</hask>. You can use <hask>newtype</hask> when you have exactly one constructor with exactly one field. In those cases, <hask>newtype</hask> can give better performance than <hask>data</hask>.</p><br />
<br />
There is, however, a [[Newtype|subtle difference]] between <hask>data</hask> and <hask>newtype</hask> semantics, which is why the <hask>newtype</hask> optimization is not applied automatically.<br />
<br />
= Making it work =<br />
<br />
== How can I find type errors? ==<br />
<br />
There's no silver bullet, but here are a few useful techniques:<br />
<br />
* Comment out type signatures and see what GHC infers, using <tt>:t</tt> in GHCi.<br />
* Add more type signatures, for example inside <hask>let</hask>. This makes your assumptions clearer, so GHC's error message may better explain how your assumptions are inconsistent.<br />
* Replace some subexpressions with <hask>undefined</hask>, which can assume any type. In more recent versions of GHC, you should insert a "type hole", written <hask>_</hask> (a single underscore) instead of <hask>undefined</hask> for this purpose. GHC's error message will then indicate the type it's expecting for the expression in the hole.<br />
<br />
== How can I find bugs that occur at runtime? ==<br />
<br />
With pure functions, correctness is a matter of getting the right output for a given input. If one function gives incorrect results, you test the functions it calls, and so on until the bad code is located. You can perform these tests directly in GHCi, or with the help of a tool like QuickCheck.<br />
<br />
You can trace evaluation using [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Debug-Trace.html Debug.Trace]. You'll get a printout when the expression is evaluated. Due to lazy evaluation, this might be at an unexpected time. But this property is useful when debugging problems related to excessive laziness.<br />
<br />
GHCi also implements a [http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci-debugger.html &quot;simple imperative-style debugger&quot;].<br />
<br />
Haskell is a natural fit for novel [http://ww2.cs.mu.oz.au/~bjpop/buddha/ &quot;declarative debugging&quot; tools] but to our knowledge, no such tool is production-ready.<br />
<br />
== Why do I get an &quot;undefined symbol&quot; linker error when compiling? ==<br />
<br />
If you're using GHC 6, you should pass <tt>--make</tt> so that GHC will automatically link the appropriate Haskell libraries.<br />
<br />
== How can I get a stack backtrace when my program throws an exception? ==<br />
<br />
The standard stack in GHC Haskell doesn't represent nested function calls. The more informative stack is the profiling cost-center stack, which only exists if your code is built for profiling.<br />
<br />
With GHC 7 you can do something like this:<br />
<br />
<pre>$ ghc -fforce-recomp -prof -auto-all -rtsopts foo.hs</pre><br />
For GHC 6 you should leave off <tt>-rtsopts</tt>, and you'll probably want <tt>--make</tt>.<br />
<br />
You can then run your program with the [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-debugging <tt>-xc</tt> RTS option`]:<br />
<br />
<pre>$ ./foo +RTS -xc</pre><br />
== How can I do automated unit testing? ==<br />
<br />
See the [http://book.realworldhaskell.org/read/testing-and-quality-assurance.html testing chapter] in ''Real World Haskell''.<br />
<br />
== How can I find and fix performance problems? ==<br />
<br />
See the [http://book.realworldhaskell.org/read/profiling-and-optimization.html profiling and optimization chapter] in ''Real World Haskell''.<br />
<br />
= Modules =<br />
<br />
== How do I deal with name clashes between modules? ==<br />
<br />
You can disambiguate by prefixing a module name:<br />
<br />
<haskell><br />
import Data.List<br />
import Data.Map<br />
<br />
f = Data.List.lookup 7<br />
g = Data.Map.lookup 7<br />
</haskell><br />
<br />
The import syntax gives you additional control:<br />
<br />
* With <hask>import qualified Foo</hask> the names from <hask>Foo</hask> can ''only'' be used qualified, and won't clash with unqualified names.<br />
<br />
* With <hask>import Foo as M</hask> you'd write <hask>M.x</hask> instead of <hask>Foo.x</hask>.<br />
<br />
You can combine these two features. A more common way to write the above example is:<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
f = lookup 7 -- unqualified, from Prelude<br />
g = M.lookup 7<br />
</haskell><br />
<br />
In general, most combinations of <hask>import</hask> features are allowed. You<br />
can combine <hask>as</hask> and <hask>qualified</hask> with import and<br />
<hask>hiding</hask> lists. You can import two modules <hask>as</hask> the same<br />
name, or one module <hask>as</hask> two names, with different import and<br />
<hask>hiding</hask> lists, <hask>qualified</hask> or unqualified, etc.<br />
<br />
== How do I control the <hask>Prelude</hask> import? ==<br />
<br />
Haskell modules implicitly import <hask>Prelude</hask>, unless an explicit import is given. So you can write<br />
<br />
<haskell><br />
import Prelude as P hiding (length, head)<br />
</haskell><br />
<br />
== How do I qualify the name of an infix operator? ==<br />
<br />
You prefix the module name, as usual:<br />
<br />
<haskell><br />
x = 2 + 3<br />
y = 2 Prelude.+ 3<br />
<br />
f = (+) 7<br />
g = (Prelude.+) 7<br />
</haskell><br />
<br />
This looks weird but works fine. The syntax does clash a bit:<br />
<br />
<haskell><br />
xs = [False..True] -- wrong, parses as qualified name<br />
xs = [False .. True] -- ok<br />
</haskell><br />
<br />
== How do I mention an infix operator in an export / import / <hask>hiding</hask> list? ==<br />
<br />
The same way as elsewhere: enclose it in parentheses.<br />
<br />
<haskell><br />
import Prelude ( succ, (+), length, (*) )<br />
</haskell><br />
<br />
== I listed a data type in my import list but its data constructors aren't in scope. How do I fix it? ==<br />
<br />
You have to import data constructors explicitly:<br />
<br />
<haskell><br />
import Prelude ( Maybe ) -- the type only<br />
import Prelude ( Maybe(Nothing) ) -- type and specific constructor(s)<br />
import Prelude ( Maybe(..) ) -- type and all its constructors<br />
</haskell><br />
<br />
== How can I import and re-export a whole module? ==<br />
<br />
<haskell><br />
module Bar ( module Foo ) where<br />
import Foo<br />
</haskell><br />
<br />
== How can I export another module ''and'' everything defined in this module? ==<br />
<br />
<haskell><br />
module Bar ( module Bar, module Foo ) where<br />
import Foo<br />
</haskell><br />
<br />
= The M-word =<br />
<br />
See also &quot;[[What a Monad is not]]&quot;.<br />
<br />
== I heard Haskell is about monads. I heard that the core feature of Haskell is monads. Is that true? ==<br />
<br />
Absolutely not.<br />
<br />
== Do I need to understand monads in order to do IO? ==<br />
<br />
Not really. &quot;<tt>Monad</tt>&quot; is the name of a generic API that applies to many different types, including the <hask>IO</hask> type. If you're only thinking about IO, you don't need to worry about how this API generalizes.<br />
<br />
See the [[Introduction to IO]].<br />
<br />
== What should I know before trying to understand monads? ==<br />
<br />
Let's look at part of the definition of <hask>Monad</hask>:<br /><br /><br />
<br />
<haskell><br />
class Monad m where<br />
(>>=) :: m a -> (a -> m b) -> m b<br />
</haskell><br />
<br />
This uses a lot of features:<br />
<br />
* first-class functions: the second argument to <hask>(>>=)</hask> is a function<br />
<br />
* type constructors (here <hask>m</hask>)<br />
<br />
* type class polymorphism<br />
<br />
* type class polymorphism ''over'' type constructors (which few other languages have)<br />
<br />
* parametric (not type class) polymorphism, over <hask>a</hask> and <hask>b</hask><br />
<br />
Each of these features is more fundamental than the specific idea of monads. If you understand each feature, then <hask>Monad</hask> is a small example of how they fit together. <hask>Functor</hask> is a slightly simpler example, and you can start there instead (see [[Typeclassopedia]]).<br />
<br />
== Aren't monads just a hack for handling impure things in a pure language? ==<br />
<br />
No. This is wrong in several ways.<br />
<br />
First, '''<hask>Monad</hask> isn't special.''' <hask>Monad</hask> is an ordinary Haskell type class. You can define it yourself in a few lines of pure Haskell code, so it's definitely not adding magical new capabilities to the language. Besides that, <hask>Monad</hask> is an API, not an implementation.<br /><br /><br />
<br />
(The <hask>do</hask> syntax ''is'' special, but it's only [[syntactic sugar]]. There's a straightforward translation to ordinary function calls, lambdas, etc.)<br /><br /><br />
<br />
Second, '''most monads have nothing to do with effects or "impurity".''' The <hask>Monad</hask> API is implemented by many different type constructors, including <hask>Maybe</hask> and <hask>[]</hask>. Lists and <hask>Maybe</hask> values are straightforward, familiar data values. There's nothing "impure" about them.<br /><br /><br />
<br />
Third, '''<hask>IO</hask> is not an exception to purity.''' IO actions are pure, first-class values like any other. You can create, store, and evaluate them without causing side effects. IO actions are just ''descriptions'' of IO which ''could'' be performed.<br /><br />
<br />
In short, Haskell programs are pure-functional programs which compute imperative programs.<br />
<br />
It's true that <hask>IO</hask> implements the <hask>Monad</hask> API, but that's not fundamental. You could instead use non-overloaded functions like<br /><br /><br />
<br />
<haskell><br />
returnIO :: a -> IO a<br />
bindIO :: IO a -> (a -> IO b) -> IO b<br />
</haskell><br />
<br />
<br />to glue together IO actions, and it would all work out basically the same. We use the generic <hask>Monad</hask> API for <hask>IO</hask> not because we have to, but because it lets us reuse convenient syntax and [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html libraries]. Indeed, you can [[Introduction to IO|introduce <tt>IO</tt>]] without mentioning <hask>Monad</hask> at all.<br />
<br />
== I heard monads are like burritos or space suits full of nuclear waste. Is that true? ==<br />
<br />
These analogies are not helpful. See [http://byorgey.wordpress.com/2009/01/12/abstraction-intuition-and-the-monad-tutorial-fallacy/ &quot;Abstraction, intuition, and the 'monad tutorial fallacy&quot;'].<br />
<br />
== I can use monads but I feel like I still don't &quot;get&quot; them. What am I missing? ==<br />
<br />
You're not necessarily missing anything. &quot;<tt>Monad</tt>&quot; is just the name of a generic API that applies to many different types. The types implementing the <tt>Monad</tt> API don't have a lot in common.<br />
<br />
You might want to read &quot;[[Typeclassopedia]]&quot; to see how <tt>Monad</tt> fits in with other similar APIs.<br />
<br />
== What's the difference between <hask>State s</hask> and <hask>ST s</hask> monads? ==<br />
<br />
<tt>State s a</tt> is just a wrapper for the function type <hask>s -> (a, s)</hask>: a function that takes an &quot;old state&quot; and returns a &quot;new state&quot; along with its result. You can implement <hask>State</hask> in a few lines of standard Haskell, without any special help from the compiler.<br />
<br />
<hask>ST</hask> gives you true mutable variables with in-place update. You can't implement it yourself in standard Haskell. In GHC, <hask>STRef</hask> and <hask>IORef</hask> will behave the same way at runtime. The difference is the extra compile-time safety checking associated with <hask>runST</hask>.<br />
<br />
= Concurrency and parallelism =<br />
<br />
See also notes on [[parallel]] and [[Concurrency|concurrent]] programming.<br />
<br />
== How can I do X without resorting to threads? ==<br />
<br />
That's usually the wrong attitude. Threads are useful for solving problems. The attitude comes from other languages where some combination of the following holds:<br />
<br />
* Per-thread overhead consumes a lot of memory or CPU<br />
<br />
* Thread APIs are cumbersome, sometimes due to lacking first-class functions or IO actions<br />
<br />
* The thread implementation is fundamentally broken, e.g. a global interpreter lock<br />
<br />
* Threads break easily because programs constantly mutate implicitly-shared state<br />
<br />
None of these is true in GHC Haskell. Threads have disadvantages and are not always the right tool. But avoiding them at all costs is counterproductive.<br />
<br />
== What's the difference between concurrency and parallelism? ==<br />
<br />
Briefly: concurrency describes semantics; parallelism describes an implementation property.<br />
<br />
Concurrent programs are written with explicit threads of control. Concurrent semantics fit naturally with certain real-world problems, like a network server talking to many simultaneous clients. This is still a nice model for writing a network server, even if you only intend to run it on one CPU core — concurrency without parallelism.<br />
<br />
Parallel programs are those which run on multiple CPU cores simultaneously, regardless of how they were implemented.<br />
<br />
Concurrency is a popular way to obtain parallel performance, but converting a pure computation to use concurrent semantics is difficult and error-prone. GHC Haskell provides "[http://hackage.haskell.org/packages/archive/parallel/latest/doc/html/Control-Parallel-Strategies.html semi-implicit parallelism]" as an alternative. Adding these "annotations" to a program cannot change its behavior.<br />
<br />
There's a longer discussion on the [http://ghcmutterings.wordpress.com/2009/10/06/parallelism-concurrency/ GHC blog].<br />
<br />
== How do <hask>par</hask>, <hask>pseq</hask>, and <hask>seq</hask> relate? ==<br />
<br />
The expression <hask>par x y</hask> is semantically equivalent to <hask>y</hask>, but suggests to the runtime system that evaluating <hask>x</hask> in parallel might be a good idea. Usually <hask>x</hask> would be a variable referring to a thunk (unevaluated expression) that will later be needed.<br /><br /><br />
<br />
Now consider <hask>par x (x+y)</hask>. Evaluating this expression suggests evaluating <hask>x</hask> in parallel. But before the runtime system can act on that suggestion, we evaluate <hask>(x+y)</hask>, which will evaluate both <hask>x</hask> and <hask>y</hask> in sequence. It would be better to work on <hask>y</hask> for a while, and only demand <hask>x</hask> later, after perhaps some parallel work has occurred. We can use <hask>pseq</hask> to force this evaluation order, as in <hask>par x (pseq y (x+y))</hask>.<br /><br /><br />
<br />
The [http://hackage.haskell.org/packages/archive/parallel/latest/doc/html/Control-Parallel-Strategies.html Strategies] module provides a nicer interface to these <hask>par</hask> / <hask>pseq</hask> tricks.<br />
<br />
<p><hask>seq</hask> is similar to <hask>pseq</hask> but provides a weaker guarantee. [http://www.mail-archive.com/glasgow-haskell-users@haskell.org/msg10973.html The details] are subtle; suffice to say that if you're controlling evaluation order, you want <hask>pseq</hask>.</p><br />
<br />
== How do I do event-based IO in GHC Haskell? Should I call <tt>select</tt>, <tt>epoll</tt>, etc? ==<br />
<br />
No; just do blocking IO from multiple threads, and GHC's runtime system will make these calls for you. GHC Haskell gives you the performance benefits of event-based IO without making you turn your code inside-out.<br />
<br />
Threads in GHC are lightweight — both in performance and in the mental effort of using them. You can handle [http://blog.johantibell.com/2010/09/final-version-of-our-ghc-io-manager.html ten thousand concurrent requests] at high throughput with a naive "one thread per client" model.<br />
<br />
== What's the difference between <hask>forkIO</hask> and <hask>forkOS</hask>? ==<br />
<br />
It only matters if you're calling into a C library that cares about thread-local state. In that case, <hask>forkOS</hask> guarantees that the C library will see the same OS thread each time. Any difference beyond that is an implementation detail and subject to change.<br />
<br />
== How can I wait for a thread to finish and produce a result? ==<br />
<br />
There's a few libraries for this on Hackage, like [http://hackage.haskell.org/package/async <tt>async</tt>], [http://hackage.haskell.org/package/spawn <tt>spawn</tt>], and [http://hackage.haskell.org/package/threads <tt>threads</tt>].<br />
<br />
It's not hard to implement this yourself using [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent-MVar.html <tt>MVar</tt>], though it's harder to get the exception handling right.<br />
<br />
= IRC =<br />
<br />
== What does lambdabot's "info" command do? ==<br />
<br />
At first, it seems like it just echoes whatever you type:<br />
<br />
<user> ?info foo bar baz<br />
<lambdabot> foo bar baz<br />
<br />
What is actually happening is that it autocorrects to the "undo" command, which desugars do blocks according to the Report's rules. So, a more interesting example might look like this:<br />
<br />
<user> ?info do { foo; x <- bar; baz }<br />
<lambdabot> foo >> bar >>= \ x -> baz<br />
<br />
<br />
= Error messages and warnings =<br />
<br />
== Not in scope: `catch' ==<br />
<br />
The function "catch" is removed from Prelude, add the line:<br />
<haskell>import Control.Exception</haskell><br />
(Note, that this might lead to an error if you compile the same code with an older [[GHC]].)<br />
<br />
<br />
[[Category:FAQ]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Debugging&diff=63374Debugging2020-07-23T06:15:10Z<p>Ysangkok: /* Other tricks */ fix link to -xc rts flag</p>
<hr />
<div>== Stack trace ==<br />
<br />
<br />
<br />
=== General usage ===<br />
<br />
Recent versions of GHC allow a dump of a stack trace (of all cost centres) when an exception is raised. In order to enable this, compile with <code>-prof</code>, and run with <code>+RTS -xc</code>. (Since only the cost centre stack will be printed, you may want to add <code>-fprof-auto -fprof-cafs</code><ref name=depflags></ref> to the compilation step to include all definitions in the trace.) Since GHC version 7.8, the function [http://hackage.haskell.org/package/base/docs/GHC-Stack.html#v:errorWithStackTrace errorWithStackTrace] can be used to programmatically dump the stack trace, see [http://www.reddit.com/r/haskell/comments/2fwwx3/how_to_get_approx_stack_traces_with_profiled/ How to get (approx) stack traces with profiled builds].<br />
<br />
A more detailed list of options can be found [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-debugging in the RTS section] of the GHC user's guide.<br />
<br />
<br />
<br />
=== Example ===<br />
<br />
<haskell><br />
-- test.hs<br />
crash = sum [1,2,3,undefined,5,6,7,8]<br />
main = print crash<br />
</haskell><br />
<br />
<br />
> ghc-7.6.3 test.hs -prof -fprof-auto -fprof-cafs && ./test +RTS -xc<br />
*** Exception (reporting due to +RTS -xc): (THUNK_2_0), stack trace: <br />
GHC.Err.CAF<br />
--> evaluated by: Main.crash,<br />
called from Main.CAF:crash_reH<br />
test: Prelude.undefined<br />
<br />
<br />
== Printf and friends ==<br />
<br />
The simplest approach is to use <tt>Debug.Trace.trace</tt>:<br />
<pre><br />
trace :: String -> a -> a<br />
</pre><br />
: "''When called, trace outputs the string in its first argument, before returning the second argument as its result.'"<br />
<br />
A common idiom to trace a function is:<br />
<pre><br />
myfun a b | trace ("myfun " ++ show a ++ " " ++ show b) False = undefined<br />
myfun a b = ...<br />
</pre><br />
The advantage is that disabling and enabling the trace takes only one line comment.<br />
<br />
You must keep in mind that due to lazy evaluation your traces will only print if the value they wrap is ever demanded.<br />
<br />
The trace function is located in the base package. The package [http://hackage.haskell.org/package/htrace htrace] defines a trace function similar to the one in the base package, but with indentation for better visual effect (see the [http://www.haskell.org/pipermail/haskell-cafe/2012-January/098847.html mailing list thread] for examples). Other tools can be found at [http://hackage.haskell.org/packages/#cat:Debug the debug category in Hackage].<br />
<br />
A more powerful alternative for this approach is [http://hackage.haskell.org/package/hood Hood]. Even if it hasn't been<br />
updated in some time, Hood works perfectly with the current ghc<br />
distribution. Even more, Hugs has it already integrated, see the [http://cvs.haskell.org/Hugs/pages/users_guide/observe.html manual page]. Add an <tt>import Observe</tt> and start inserting observations in your code.<br />
For instance:<br />
<pre><br />
import Hugs.Observe<br />
<br />
f' = observe "Informative name for f" f <br />
f x = if odd x then x*2 else 0<br />
</pre><br />
And then in hugs:<br />
<pre><br />
Main> map f' [1..5]<br />
[2,0,6,0,10]<br />
<br />
>>>>>>> Observations <<<<<<<br />
<br />
Informative name for f<br />
{ \ 5 -> 10<br />
, \ 4 -> 0<br />
, \ 3 -> 6<br />
, \ 2 -> 0<br />
, \ 1 -> 2<br />
}<br />
<br />
</pre><br />
<br />
outputs a report of all the invocations of f and their result.<br />
<br />
I have a handy bogus Hugs.Observe module with no-ops for the observations so that I don't need to remove them manually, expecting that the compiler will optimize them away.<br />
<br />
The [http://hackage.haskell.org/package/GHood GHood] package adds a graphical back-end to Hood. See also the [http://community.haskell.org/~claus/GHood/ GHood homepage].<br />
<br />
<br />
== The Safe Library ==<br />
<br />
There is a safe library of functions from the Prelude that can crash, see [http://community.haskell.org/~ndm/safe/ the safe library]. If you get an error message such as "pattern match failure, head []", you can then use <tt>headNote "extra information"</tt> to get a more detailed error message for that particular call to <tt>head</tt>. The safe library also has functions that return default values and wrap their computation in <tt>Maybe</tt> as required.<br />
<br />
<br />
== Offline analysis of traces ==<br />
The most advanced debugging tools are based in offline analysis of traces.<br />
<br />
=== Haskell Tracer HAT ===<br />
<br />
[http://projects.haskell.org/hat/ Hat] is probably the most advanced tool for this, offering a comprehensive set of tools. [[User:NeilMitchell|Neil Mitchell]] has made available a Windows port of Hat at [http://projects.haskell.org/~ndm/hat/ his site].<br />
<br />
The disadvantage of traditional Haskell tracers is that they either need to transform the whole program or require a specialized run-time system. Therefore they are not always compatible with the latest libraries, so you can put them to use only in some cases. <br />
<br />
=== Hoed - The Lightweight Haskell Tracer and Debugger ===<br />
<br />
[https://github.com/MaartenFaddegon/Hoed Hoed] is a tracer/debugger that offers most of HATs functionality, and works with untransformed libraries. Hoed can therefore be used to debug much more programs than traditional tracer/debuggers.<br />
<br />
To locate a defect with Hoed you annotate suspected functions and compile as usual. Then you run your program, information about the annotated functions is collected. Finally you connect to a debugging session using a webbrowser.<br />
<br />
== Dynamic breakpoints in GHCi ==<br />
<br />
Finally, the [[GHC/GHCi debugger| GHCi debugger]] enables dynamic<br />
breakpoints and intermediate values observation. <br />
<br />
This tool allows to set breakpoints in your code, directly from the GHCi command prompt. An example session:<br />
<pre><br />
*main:Main> :break Main 2<br />
Breakpoint set at (2,15)<br />
*main:Main> qsort [10,9..1]<br />
Local bindings in scope:<br />
x :: a, xs :: [a], left :: [a], right :: [a]<br />
<br />
qsort2.hs:2:15-46> :sprint x<br />
x = _<br />
qsort2.hs:2:15-46> x<br />
</pre><br />
This is an untyped, unevaluated computation. You can use <hask>seq</hask> to force its evaluation and then <code>:print</code> to recover its type<br />
<pre><br />
qsort2.hs:2:15-46> seq x ()<br />
() <br />
qsort2.hs:2:15-46> :p x<br />
x - 10<br />
</pre><br />
<br />
Once a breakpoint is hit, you can explore the bindings in scope, as well as to evaluate any Haskell expression, as you would do in a normal GHCi prompt. The <code>:print</code> command can be very useful to explore the laziness of your code.<br />
<br />
<br />
== Source-located errors ==<br />
<br />
[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/loch LocH] provides wrappers over<br />
<hask>assert</hask> for generating source-located exceptions and errors.<br />
<br />
Consider the use of a located <hask>fromJust</hask>:<br />
<br />
<haskell><br />
import Debug.Trace.Location<br />
import qualified Data.Map as M<br />
import Data.Maybe<br />
<br />
main = do print f<br />
<br />
f = let m = M.fromList<br />
[(1,"1")<br />
,(2,"2")<br />
,(3,"3")]<br />
s = M.lookup 4 m<br />
in fromJustSafe assert s<br />
<br />
fromJustSafe a s = check a (fromJust s)<br />
</haskell><br />
<br />
This will result in:<br />
<br />
<haskell><br />
$ ./a.out<br />
a.out: A.hs:12:20-25: Maybe.fromJust: Nothing<br />
</haskell><br />
<br />
This can be automated, using the 'loch' preprocessor, so a program<br />
failing with:<br />
<br />
<code><br />
$ ghc A.hs --make -no-recomp<br />
[1 of 1] Compiling Main ( A.hs, A.o )<br />
Linking A ...<br />
<br />
$ ./A<br />
A: Maybe.fromJust: Nothing<br />
</code><br />
<br />
Can be transformed to a src-located one by adding:<br />
<br />
<haskell><br />
import Debug.Trace.Location<br />
</haskell><br />
<br />
and then recompiling with the preprocessor on:<br />
<br />
<code><br />
$ ghc A.hs --make -pgmF loch -F -no-recomp<br />
[1 of 1] Compiling Main ( A.hs, A.o )<br />
Linking A ...<br />
<br />
$ ./A<br />
A: A.hs:14:14-19: Maybe.fromJust: Nothing<br />
</code><br />
<br />
<br />
== Other tricks ==<br />
<br />
* If you use GHC, you can get a stack trace in the console when your program fails with an error condition. See the [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/runtime_control.html#rts-flag--xc description of relevant runtime options].<br />
* Some tips how to use GHCi debugger are also in [http://www.haskell.org/pipermail/glasgow-haskell-users/2009-February/016571.html this message].<br />
<br />
<br />
=== Locating a failure in a library function ===<br />
<br />
The simplest way to provide locating in the source code a mismatch<br />
run-time error in the library functions:<br />
<haskell><br />
head, tail, fromJust<br />
</haskell><br />
<br />
and others is to avoid these functions and to use explicit matching instead.<br />
<br />
For example, consider:<br />
<br />
<haskell><br />
g x = h $ fromJust $ f x,<br />
</haskell><br />
<br />
ghc-6.6 often loses the reference to <hask>g</hask>, <hask>f</hask>,<br />
and <hask>h</hask> in its run-time error report, when <hask>f</hask><br />
returns <hask>Nothing</hask>.<br />
<br />
But for the program:<br />
<br />
<haskell><br />
g x = let Just y = f x in h y,<br />
</haskell><br />
<br />
GHC reports:<br />
<br />
<haskell><br />
Main: M1.hs:9:11-22:<br />
Irrefutable pattern failed for pattern Data.Maybe.Just y<br />
</haskell><br />
<br />
Indicating the source of the failure.<br />
<br />
<br />
=== Mysterious parse errors ===<br />
<br />
GHC provides `-ferror-spans`, which will give you the exactly position<br />
of the start and end of an offending statement.<br />
<br />
<br />
=== Infinite loops ===<br />
<br />
On glasgow-haskell-users on 21 Nov 2007, pepe made the following suggestion for detecting the cause infinite loops in GHCi. Assuming the offending function is named `loop`, and takes one argument:<br />
<br />
# enable the flag -fbreak-on-error (`:set -fbreak-on-error` in GHCi)<br />
# run your expression with :trace (`:trace loop 'a'`)<br />
# hit Ctrl-C while your program is stuck in the loop to have the debugger break in the loop<br />
# use :history and :back to find out where the loop is located and why.<br />
<br />
''(For which versions? ghci >= 6.8?)''<br />
<br />
<references><br />
<ref name=depflags>was <code>-auto-all -caf-all</code> in previous ghc versions (now deprecated)</ref><br />
</references><br />
<br />
<br />
[[Category:Tools]]<br />
[[Category:Development tools]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Performance/GHC&diff=63373Performance/GHC2020-07-23T06:12:35Z<p>Ysangkok: /* Measuring performance */ fix link to gc options in users guide</p>
<hr />
<div>{{Performance infobox}}<br />
[[Category:Performance|GHC]] [[Category:GHC]]<br />
Please report any overly-slow GHC-compiled programs. Since [[GHC]] doesn't have any credible competition in the performance department these days it's hard to say what overly-slow means, so just use your judgement! Of course, if a GHC compiled program runs slower than the same program compiled with another Haskell compiler, then it's definitely a bug. Furthermore, if an equivalent OCaml, SML or Clean program is faster, this ''might'' be a bug.<br />
<br />
== Use optimisation ==<br />
<br />
Optimise, using <tt>-O</tt> or <tt>-O2</tt>: this is the most basic way to make your program go faster. Compilation time will be slower, especially with <tt>-O2</tt>.<br />
<br />
At present, <tt>-O2</tt> is nearly indistinguishable from <tt>-O</tt>.<br />
<br />
GHCi cannot optimise interpreted code, so when using GHCi, compile critical modules using <tt>-O</tt> or <tt>-O2</tt>, then load them into GHCi.<br />
<br />
Here is a short summary of useful compile time flags:<br />
* <tt>-O</tt>:<br />
* <tt>-O2</tt>:<br />
* <tt>-funfolding-use-threshold=16</tt>: demand more inlining.<br />
* <tt>-fexcess-precision</tt>: see [[Performance/Floating_point]]<br />
* <tt>-optc-O3</tt>: Enables a suite of optimizations in the GCC compiler. See the [http://www.openbsd.org/cgi-bin/man.cgi?query=gcc&sektion=1 gcc(1) man-page] for details. (a C-compiler option).<br />
* <tt>-optc-ffast-math</tt>: A C-compiler option which allows it to be less strict with respect to the standard when compiling IEEE 754 floating point arithmetic. Math operations will not trap if something goes wrong and math operations will assume that NaN and +- Infinity are not in arguments or results. For most practical floating point processing, this is a non-issue and enabling the flag can speed up FP arithmetic by a considerable amount. Also see the gcc(1) man-page. (a C-compiler option).<br />
<br />
Other useful flags:<br />
* <tt>-ddump-simpl > core.txt</tt>: generate core.txt file (see below).<br />
<br />
<br />
== Measuring performance ==<br />
<br />
The first thing to do is measure the performance of your program, and find out whether all the time is being spent in the garbage collector or not. Run your program with the <tt>+RTS -sstderr</tt> option:<br />
<br />
$ ./clausify 20 +RTS -sstderr<br />
42,764,972 bytes allocated in the heap<br />
6,915,348 bytes copied during GC (scavenged)<br />
360,448 bytes copied during GC (not scavenged)<br />
36,616 bytes maximum residency (7 sample(s))<br />
<br />
81 collections in generation 0 ( 0.07s)<br />
7 collections in generation 1 ( 0.00s)<br />
<br />
2 Mb total memory in use<br />
<br />
INIT time 0.00s ( 0.00s elapsed)<br />
MUT time 0.65s ( 0.94s elapsed)<br />
GC time 0.07s ( 0.06s elapsed)<br />
EXIT time 0.00s ( 0.00s elapsed)<br />
Total time 0.72s ( 1.00s elapsed)<br />
<br />
%GC time 9.7% (6.0% elapsed)<br />
<br />
Alloc rate 65,792,264 bytes per MUT second<br />
<br />
Productivity 90.3% of total user, 65.1% of total elapsed<br />
<br />
{{Note|Hint: You can use [[ThreadScope]] to visualize GHC's output.}}<br />
<br />
This tells you how much time is being spent running the program itself (MUT time), and how much time spent in the garbage collector (GC time). <br />
<br />
If your program is doing a lot of GC, then your first priority should be to check for [[Memory leak|Space Leaks]] using [https://downloads.haskell.org/~ghc/7.0.3/docs/html/users_guide/prof-heap.html heap profiling], and then to try to reduce allocations by [https://downloads.haskell.org/~ghc/7.0.3/docs/html/users_guide/prof-time-options.html time and allocation profiling]. <br />
<br />
If you can't reduce the GC cost any further, then using more memory by tweaking the [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/runtime_control.html#rts-options-to-control-the-garbage-collector GC options] will probably help. For example, increasing the default heap size with <tt>+RTS -H128m</tt> will reduce the number of GCs.<br />
<br />
If your program isn't doing too much GC, then you should proceed to [http://www.haskell.org/ghc/docs/latest/html/users_guide/prof-time-options.html time and allocation profiling] to see where the big hitters are.<br />
<br />
== Modules and separate compilation ==<br />
<br />
In general, splitting code across modules should not make programs less efficient. GHC does quite aggressive cross-module inlining: when you import a function f from another module M, GHC consults the "interface file" M.hi to get f's definition.<br />
<br />
For best results, ''use an explicit export list''. If you do, GHC can inline any non-exported functions that are only called once, even if they are very big. Without an explicit export list, GHC must assume that every function is exported, and hence (to avoid code bloat) is more conservative about inlining.<br />
<br />
There is one exception to the general rule that splitting code across modules does not harm performance. As mentioned above, if a non-exported non-recursive function is called exactly once, then it is inlined ''regardless of size'', because doing so does not cause code duplication. But if it's exported and is large, then its inlining is not exposed -- and even if it were it might not be inlined, because doing so duplicates its code an unknown number of times. You can change the threshold for (a) exposing and (b) using an inlining, with flags <tt>-funfolding-creation-threshold</tt> and <tt>-funfolding-use-threshold</tt> respectively.<br />
<br />
== Unboxed types ==<br />
<br />
When you are ''really'' desperate for speed, and you want to get right down to the &ldquo;raw bits.&rdquo; Please see [http://www.haskell.org/ghc/docs/latest/html/users_guide/primitives.html GHC Primitives] for some information about using unboxed types.<br />
<br />
This should be a last resort, however, since unboxed types and primitives are non-portable. Fortunately, it is usually not necessary to resort to using explicit unboxed types and primitives, because GHC's optimiser can do the work for you by inlining operations it knows about, and unboxing strict function arguments (see [[Performance/Strictness]]). Strict and unpacked constructor fields can also help a lot (see [[Performance/Data Types]]). Sometimes GHC needs a little help to generate the right code, so you might have to look at the Core output to see whether your tweaks are actually having the desired effect.<br />
<br />
One thing that can be said for using unboxed types and primitives is that you ''know'' you're writing efficient code, rather than relying on GHC's optimiser to do the right thing, and being at the mercy of changes in GHC's optimiser down the line. This may well be important to you, in which case go for it.<br />
<br />
=== An example ===<br />
<br />
Usually unboxing is not explicitly required (see the Core tutorial below), however there<br />
are circumstances where you require precise control over how your code is<br />
unboxed. The following program was at one point an entry in the<br />
[http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=ghc&lang2=ghc Great Language Shootout]. <br />
GHC did a good job unboxing the loop, but wouldn't generate the best loop. The<br />
solution was to unbox the loop function by hand, resulting in better code.<br />
<br />
The original code:<br />
<br />
loop :: Int -> Double -> Double<br />
loop d s = if d == 0 then s<br />
else loop (d-1) (s + 1/fromIntegral d)<br />
The hand-unboxed code (note that it is uglier, and harder to read):<br />
<br />
import GHC.Base<br />
import GHC.Float<br />
<br />
loop :: Int# -> Double# -> Double#<br />
loop d s = if d ==# 0# then s <br />
else loop (d -# 1#) (s +## (1.0## /## int2Double# d))<br />
<br />
GHC 6.4.1 compiles the first loop to:<br />
<br />
$wloop :: Int# -> Double# -> Double#<br />
$wloop = \ (ww_s2Ga :: Int#) (ww1_s2Ge :: Double#) -><br />
case Double# ww_s2Ga of wild_XC {<br />
__DEFAULT -><br />
case /## 1.0 (int2Double# wild_XC) of y_a2Cd { <br />
__DEFAULT -> $wloop (-# wild_XC 1) (+## ww1_s2Ge y_a2Cd)<br />
};<br />
0 -> ww1_s2Ge<br />
}<br />
<br />
And the second, unboxed loop is translated to<br />
<br />
loop1 :: Int# -> Double# -> Double#<br />
loop1 = \ (d_a1as :: Int#) (s_a1at :: Double#) -><br />
case Double# d_a1as of wild_B1 {<br />
__DEFAULT -> loop1 (-# wild_B1 1) (+## s_a1at (/## 1.0 (int2Double# wild_B1)));<br />
0 -> s_a1at<br />
}<br />
<br />
which contains 1 less case statement. The second version runs as fast as C, the<br />
first a bit slower. A similar problem was also solved with explicit unboxing in the [http://shootout.alioth.debian.org/gp4/benchmark.php?test=recursive&lang=all recursive benchmark entry].<br />
<br />
== Primops ==<br />
<br />
If you really, really need the speed, and other techniques don't seem to<br />
be helping, programming your code in raw GHC primops can sometimes do<br />
the job. As for unboxed types, you get some guarantees that your code's<br />
performance isn't subject to changes to the GHC optimisations, at the<br />
cost of more unreadable code.<br />
<br />
For example, in an imperative benchmark program a bottleneck was<br />
swapping two values. Raw primops solved the problem:<br />
<br />
swap i j a s =<br />
if i <# j then case readIntOffAddr# a i s of { (# s, x #) -><br />
case readIntOffAddr# a j s of { (# s, y #) -><br />
case writeIntOffAddr# a j x s of { s -><br />
case writeIntOffAddr# a i y s of { s -><br />
swap (i +# 1#) (j -# 1#) a s<br />
}}}}<br />
else (# s, () #)<br />
{-# INLINE swap #-}<br />
<br />
== Inlining ==<br />
<br />
GHC does a lot of inlining, which has a dramatic effect on performance.<br />
<br />
Without -O, GHC does inlining ''within'' a module, but no ''cross-module'' inlining. <br />
<br />
With -O, it does a lot of cross-module inlining. Indeed, generally<br />
speaking GHC will inline ''across'' modules just as much as it does<br />
''within'' modules, with a single large exception. If GHC sees that a<br />
function 'f' is called just once, it inlines it regardless of how big<br />
'f' is. But once 'f' is exported, GHC can never see that it's called<br />
exactly once, even if that later turns out to be the case. This<br />
inline-once optimisation is pretty important in practice. <br />
<br />
So: if you care about performance, do not export functions that are not used outside the module (i.e. use an explicit export list, and keep it as small as possible).<br />
<br />
Sometimes ''explicitly'' inlining critical chunks of code can help.<br />
The INLINE pragma can be used for this purpose; but not for recursive functions, since inlining them forever would obviously be a bad idea.<br />
<br />
If a function you want inlined contains a slow path, it can help a<br />
good deal to separate the slow path into its own function and NOINLINE<br />
it. <br />
<br />
== Looking at the Core ==<br />
<br />
GHC's compiler intermediate language can be very useful for improving<br />
the performance of your code. Core is a functional language much like a very<br />
stripped down Haskell (by design), so it's still readable, and still purely<br />
functional. The general technique is to iteratively inspect how the critical<br />
functions of your program are compiled to Core, checking that they're compiled<br />
in the most optimal manner. Sometimes GHC doesn't quite manage to unbox your<br />
function arguments, float out common subexpressions, or unfold loops ideally --<br />
but you'll only know if you read the Core.<br />
<br />
References:<br />
* [http://haskell.org/ghc/docs/papers/core.ps.gz An External Representation for the GHC Core Language], Andrew Tolmach<br />
* [http://research.microsoft.com/Users/simonpj/Papers/comp-by-trans-scp.ps.gz A transformation-based optimiser for Haskell], Simon L. Peyton Jones and Andre Santos<br />
* [http://research.microsoft.com/Users/simonpj/Papers/inlining/index.htm Secrets of the Glasgow Haskell Compiler Inliner], Simon L. Peyton Jones and Simon Marlow<br />
* [http://research.microsoft.com/users/simonpj/papers/spineless-tagless-gmachine.ps.gz Implementing lazy functional languages on stock hardware: the Spineless Tagless G-machine], Simon L. Peyton Jones<br />
<br />
== Core by example ==<br />
<br />
Here's a step-by-step guide to optimising a particular program, <br />
the [http://shootout.alioth.debian.org/gp4/benchmark.php?test=partialsums&lang=ghc&id=2 partial-sums problem] from the [http://shootout.alioth.debian.org Great Language Shootout]. We developed a number<br />
of examples on [http://haskell.org/haskellwiki/Shootout/Partial_sums Haskell shootout entry] page.<br />
<br />
Begin with the naive translation of the Clean entry (which was fairly quick):<br />
Lots of math in a tight loop.<br />
<br />
import System<br />
import Numeric<br />
<br />
main = do n <- getArgs >>= readIO . head<br />
let sums = loop 1 n 1 0 0 0 0 0 0 0 0 0<br />
fn (s,t) = putStrLn $ (showFFloat (Just 9) s []) ++ "\t" ++ t<br />
mapM_ (fn :: (Double, String) - IO ()) (zip sums names)<br />
<br />
names = ["(2/3)^k", "k^-0.5", "1/k(k+1)", "Flint Hills", "Cookson Hills"<br />
, "Harmonic", "Riemann Zeta", "Alternating Harmonic", "Gregory"]<br />
<br />
loop k n alt a1 a2 a3 a4 a5 a6 a7 a8 a9<br />
| k > n = [ a1, a2, a3, a4, a5, a6, a7, a8, a9 ]<br />
| otherwise = loop (k+1) n (-alt)<br />
(a1 + (2/3) ** (k-1))<br />
(a2 + k ** (-0.5))<br />
(a3 + 1 / (k * (k + 1)))<br />
(a4 + 1 / (k*k*k * sin k * sin k))<br />
(a5 + 1 / (k*k*k * cos k * cos k))<br />
(a6 + 1 / k)<br />
(a7 + 1 / (k*k))<br />
(a8 + alt / k)<br />
(a9 + alt / (2 * k - 1))<br />
<br />
Compiled with '''-O2''' it runs. However, the performance is ''really'' bad.<br />
Somewhere greater than 128M heap -- in fact eventually running out of<br />
memory. A classic space leak. So look at the generated Core. <br />
<br />
=== Inspect the Core ===<br />
<br />
The best way to check the Core that GHC generates is with the<br />
'''-ddump-simpl''' flag (dump the results after code simplification, and<br />
after all optimisations are run). The result can be verbose, so pipe it into a pager.<br />
<br />
Looking for the 'loop', we find that it has been compiled to a function with<br />
the following type:<br />
<br />
$sloop_r2U6 :: GHC.Prim.Double#<br />
-> GHC.Float.Double<br />
-> GHC.Float.Double<br />
-> GHC.Float.Double<br />
-> GHC.Float.Double<br />
-> GHC.Float.Double<br />
-> GHC.Float.Double<br />
-> GHC.Float.Double<br />
-> GHC.Float.Double<br />
-> GHC.Float.Double<br />
-> GHC.Float.Double<br />
-> GHC.Prim.Double#<br />
-> [GHC.Float.Double]<br />
<br />
Hmm, I certainly don't want boxed doubles in such a tight loop (boxed values<br />
are represented as pointers to closures on the heap, unboxed values are raw<br />
machine values).<br />
<br />
=== Strictify ===<br />
<br />
The next step then is to encourage GHC to unbox this loop, by providing some<br />
strictness annotations. So rewrite the loop like this:<br />
<br />
loop k n alt a1 a2 a3 a4 a5 a6 a7 a8 a9<br />
| () !k !n !alt !a1 !a2 !a3 !a4 !a5 !a6 !a7 !a8 !a9 !False = undefined<br />
| k > n = [ a1, a2, a3, a4, a5, a6, a7, a8, a9 ]<br />
| otherwise = loop (k+1) n (-alt)<br />
(a1 + (2/3) ** (k-1))<br />
(a2 + k ** (-0.5))<br />
(a3 + 1 / (k * (k + 1)))<br />
(a4 + 1 / (k*k*k * sin k * sin k))<br />
(a5 + 1 / (k*k*k * cos k * cos k))<br />
(a6 + 1 / k)<br />
(a7 + 1 / (k*k))<br />
(a8 + alt / k)<br />
(a9 + alt / (2 * k - 1)) where x ! y = x `seq` y<br />
<br />
Here the first guard is purely a syntactic trick to inform ghc that the<br />
arguments should be strictly evaluated. I've played a little game here, using<br />
'''!''' for '''`seq`''' is reminiscent of the new bang-pattern proposal for<br />
strictness. Let's see how this compiles. Strictifying all args GHC produces an<br />
inner loop of:<br />
<br />
$sloop_r2WS :: GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> GHC.Prim.Double#<br />
-> [GHC.Float.Double]<br />
<br />
Ah! perfect. Let's see how that runs:<br />
<br />
$ ghc Naive.hs -O2 -no-recomp<br />
$ time ./a.out 2500000<br />
3.000000000 (2/3)^k<br />
3160.817621887 k^-0.5<br />
0.999999600 1/k(k+1)<br />
30.314541510 Flint Hills<br />
42.995233998 Cookson Hills<br />
15.309017155 Harmonic<br />
1.644933667 Riemann Zeta<br />
0.693146981 Alternating Harmonic<br />
0.785398063 Gregory<br />
./a.out 2500000 4.45s user 0.02s system 99% cpu 4.482 total<br />
<br />
=== Crank up the gcc flags ===<br />
<br />
Not too bad. No space leak and quite zippy. But let's see what more can be<br />
done. First, double arithmetic usually (always?) benefits from<br />
-fexcess-precision, and cranking up the flags to gcc:<br />
<br />
paprika$ ghc Naive.hs -O2 -fexcess-precision -optc-O3 -optc-ffast-math -no-recomp<br />
paprika$ time ./a.out 2500000<br />
3.000000000 (2/3)^k<br />
3160.817621887 k^-0.5<br />
0.999999600 1/k(k+1)<br />
30.314541510 Flint Hills<br />
42.995233998 Cookson Hills<br />
15.309017155 Harmonic<br />
1.644933667 Riemann Zeta<br />
0.693146981 Alternating Harmonic<br />
0.785398063 Gregory<br />
./a.out 2500000 3.71s user 0.01s system 99% cpu 3.726 total<br />
<br />
Even better! Now, let's dive into the Core to see if there are any optimisation<br />
opportunites that GHC missed. So add '''-ddump-simpl''' and peruse the output.<br />
<br />
=== Common subexpressions ===<br />
<br />
Looking at the Core, I see firstly that some of the common subexpressions<br />
haven't been factored out:<br />
<br />
case [GHC.Float.Double] GHC.Prim./## 1.0<br />
(GHC.Prim.*## (GHC.Prim.*##<br />
(GHC.Prim.*## (GHC.Prim.*## sc10_s2VS sc10_s2VS) sc10_s2VS)<br />
(GHC.Prim.sinDouble# sc10_s2VS))<br />
(GHC.Prim.sinDouble# sc10_s2VS))<br />
<br />
Multiple calls to '''sin'''. Hmm... And similar for '''cos''' and '''k*k'''. <br />
Simon Peyton-Jones says:<br />
<br />
GHC doesn't do full CSE. It'd be a relatively easy pass for someone to<br />
add, but it can cause space leaks. And it can replace two<br />
strictly-evaluated calls with one lazy thunk:<br />
let { x = case e of ....; y = case e of .... } in ...<br />
==><br />
let { v = e; x = case v of ...; y = case v of ... } in ...<br />
<br />
Instead GHC does "opportunistic CSE". If you have<br />
let x = e in .... let y = e in ....<br />
then it'll discard the duplicate binding. But that's very weak.<br />
<br />
So it looks like we might have to float out the commmon subexpressions by hand.<br />
The inner loop now looks like:<br />
<br />
loop k n alt a1 a2 a3 a4 a5 a6 a7 a8 a9<br />
| () !k !n !alt !a1 !a2 !a3 !a4 !a5 !a6 !a7 !a8 !a9 !False = undefined<br />
| k > n = [ a1, a2, a3, a4, a5, a6, a7, a8, a9 ]<br />
| otherwise = loop (k+1) n (-alt)<br />
(a1 + (2/3) ** (k-1))<br />
(a2 + k ** (-0.5))<br />
(a3 + 1 / (k * (k + 1)))<br />
(a4 + 1 / (k3 * sk * sk))<br />
(a5 + 1 / (k3 * ck * ck))<br />
(a6 + 1 / k)<br />
(a7 + 1 / k2)<br />
(a8 + alt / k)<br />
(a9 + alt / (2 * k - 1))<br />
where sk = sin k<br />
ck = cos k<br />
k2 = k * k<br />
k3 = k2 * k<br />
x ! y = x `seq` y<br />
<br />
looking at the Core shows the sins are now allocated and shared:<br />
<br />
let a9_s2MI :: GHC.Prim.Double#<br />
a9_s2MI = GHC.Prim.sinDouble# sc10_s2Xa<br />
<br />
So the common expressions are floated out, and it now runs:<br />
<br />
paprika$ time ./a.out 2500000 <br />
3160.817621887 k^-0.5<br />
0.999999600 1/k(k+1)<br />
30.314541510 Flint Hills<br />
42.995233998 Cookson Hills<br />
15.309017155 Harmonic<br />
1.644933667 Riemann Zeta<br />
0.693146981 Alternating Harmonic<br />
0.785398063 Gregory<br />
./a.out 2500000 3.29s user 0.00s system 99% cpu 3.290 total<br />
<br />
Faster. So we gained 12% by floating out those common expressions.<br />
<br />
See also the [[GCD inlining strictness and CSE]] for another example of<br />
where CSE should be performed to improve performance.<br />
<br />
=== Strength reduction ===<br />
<br />
Finally, another trick -- manual <br />
[http://en.wikipedia.org/wiki/Strength_reduction strength reduction]. When I checked the C<br />
entry, it used an integer for the k parameter to the loop, and cast it<br />
to a double for the math each time around, so perhaps we can make it an<br />
Int parameter. Secondly, the alt parameter only has it's sign flipped<br />
each time, so perhaps we can factor out the alt / k arg (it's either 1 /<br />
k or -1 on k), saving a division. Thirdly, '''(k ** (-0.5))''' is just a<br />
slow way of doing a '''sqrt'''.<br />
<br />
The final loop looks like:<br />
<br />
loop i n alt a1 a2 a3 a4 a5 a6 a7 a8 a9<br />
| i !n !alt !a1 !a2 !a3 !a4 !a5 !a6 !a7 !a8 !a9 !False = undefined -- strict<br />
| k > n = [ a1, a2, a3, a4, a5, a6, a7, a8, a9 ]<br />
| otherwise = loop (i+1) n (-alt)<br />
(a1 + (2/3) ** (k-1))<br />
(a2 + 1 / sqrt k)<br />
(a3 + 1 / (k * (k + 1)))<br />
(a4 + 1 / (k3 * sk * sk))<br />
(a5 + 1 / (k3 * ck * ck))<br />
(a6 + dk)<br />
(a7 + 1 / k2)<br />
(a8 + alt * dk)<br />
(a9 + alt / (2 * k - 1))<br />
where k3 = k2*k; k2 = k*k; dk = 1/k; k = fromIntegral i :: Double<br />
sk = sin k; ck = cos k; x!y = x`seq`y<br />
<br />
Checking the generated C code (for another tutorial, perhaps) shows that the<br />
same C operations are generated as the C entry uses.<br />
<br />
And it runs:<br />
$ time ./i 2500000<br />
3.000000200 (2/3)^k<br />
3186.765000000 k^-0.5<br />
0.999852700 1/k(k+1)<br />
30.314493000 Flint Hills<br />
42.995068000 Cookson Hills<br />
15.403683000 Harmonic<br />
1.644725300 Riemann Zeta<br />
0.693137470 Alternating Harmonic<br />
0.785399100 Gregory<br />
./i 2500000 2.37s user 0.01s system 99% cpu 2.389 total<br />
<br />
A big speedup!<br />
<br />
This entry in fact <br />
[http://shootout.alioth.debian.org/gp4/benchmark.php?test=partialsums&lang=all runs] <br />
faster than hand optimised (and vectorised) GCC! And is only slower than<br />
optimised Fortran. Lesson: Haskell can be very, very fast.<br />
<br />
So, by carefully tweaking things, we first squished a space leak, and then<br />
gained another 45%.<br />
<br />
=== Summary ===<br />
<br />
* Manually inspect the Core that is generated<br />
* Use strictness annotations to ensure loops are unboxed<br />
* Watch out for optimisations such as CSE and strength reduction that are missed<br />
* Read the generated C for really tight loops.<br />
* Use -fexcess-precision and -optc-ffast-math for doubles<br />
<br />
== Parameters ==<br />
<br />
On x86 (possibly others), adding parameters to a loop is rather<br />
expensive, and it can be a large win to "hide" your parameters in a<br />
mutable array. (Note that this is the kind of thing quite likely to<br />
change between GHC versions, so measure before using this trick!)<br />
<br />
== Pattern matching ==<br />
<br />
On rare occasions pattern matching can give improvements in code that<br />
needs to repeatedly take apart data structures. This code:<br />
<br />
flop :: Int -> [Int] -> [Int]<br />
flop n xs = rs<br />
where (rs, ys) = fl n xs ys<br />
fl 0 xs ys = (ys, xs)<br />
fl n (x:xs) ys = fl (n-1) xs (x:ys)<br />
<br />
Can be rewritten to be faster (and more ugly) as:<br />
<br />
flop :: Int -> [Int] -> [Int]<br />
flop 2 (x1:x2:xs) = x2:x1:xs<br />
flop 3 (x1:x2:x3:xs) = x3:x2:x1:xs<br />
flop 4 (x1:x2:x3:x4:xs) = x4:x3:x2:x1:xs<br />
flop 5 (x1:x2:x3:x4:x5:xs) = x5:x4:x3:x2:x1:xs<br />
flop 6 (x1:x2:x3:x4:x5:x6:xs) = x6:x5:x4:x3:x2:x1:xs<br />
flop 7 (x1:x2:x3:x4:x5:x6:x7:xs) = x7:x6:x5:x4:x3:x2:x1:xs<br />
flop 8 (x1:x2:x3:x4:x5:x6:x7:x8:xs) = x8:x7:x6:x5:x4:x3:x2:x1:xs<br />
flop 9 (x1:x2:x3:x4:x5:x6:x7:x8:x9:xs) = x9:x8:x7:x6:x5:x4:x3:x2:x1:xs<br />
flop 10 (x1:x2:x3:x4:x5:x6:x7:x8:x9:x10:xs) = x10:x9:x8:x7:x6:x5:x4:x3:x2:x1:xs<br />
flop n xs = rs<br />
where (rs, ys) = fl n xs ys<br />
fl 0 xs ys = (ys, xs)<br />
fl n (x:xs) ys = fl (n-1) xs (x:ys)<br />
<br />
== Arrays ==<br />
<br />
If you are using array access and GHC primops, do not be too eager to<br />
use raw Addr#esses; MutableByteArray# is just as fast and frees you<br />
from memory management.<br />
<br />
== Memory allocation and arrays ==<br />
<br />
When you are allocating arrays, it may help to know a little about GHC's memory allocator. There are lots of deatils in [http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage The GHC Commentary]), but here are some useful facts:<br />
<br />
* For larger objects ghc has an allocation granularity of 4k. That is it always uses a multiple of 4k bytes, which can lead to wasteage of up to 4k per array. Furthermore, a byte array has some overhead: it needs one word for the heap cell header and another for the length. So if you allocate a 4k byte array then it uses 8k. So the trick is to allocate 4k - overhead. This is what the Data.ByteString library does<br />
<br />
* GHC allocates memory from the OS in units of a "megablock", currently 1Mbyte. So if you allocate a 1Mb array, the storage manager has to allocate 1Mb + overhead, which will cause it to allocate a 2Mb megablock. The surplus will be returned to the system in the form of free blocks, but if all you do is allocate lots of 1Mb arrays, you'll waste about half the space because there's never enough contiguous free space to contain another 1Mb array. Similar problem for 512k arrays: the storage manager allocates a 1Mb block, and returns slightly less than half of it as free blocks, so each 512k allocation takes a whole new 1Mb block.<br />
<br />
== Rewrite rules ==<br />
<br />
Algebraic properties in your code might be missed by the GHC optimiser.<br />
You can use [[Playing by the rules|user-supplied rewrite rules]] to<br />
teach the compiler to optimise your code using domain-specific<br />
optimisations.<br />
<br />
<br />
== See also == <br />
<br />
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/faster.html Faster: producing a program that runs quicker] (part of the GHC User's Guide)<br />
<br />
* [http://stackoverflow.com/questions/12653787/what-optimizations-can-ghc-be-expected-to-perform-reliably What optimizations can GHC be expected to perform reliably?] (stackoverflow.com)</div>Ysangkokhttps://wiki.haskell.org/index.php?title=GHC/Type_system&diff=63372GHC/Type system2020-07-23T06:11:20Z<p>Ysangkok: fix link to users guide</p>
<hr />
<div>[[Category:GHC|Type system]]<br />
<span style='font-size: x-large; font-weight: bold'>Type system extensions in GHC</span><br />
<br />
GHC comes with a rather large collection of type-system extensions (beyond Haskell 98). They are all documented in the [http://www.haskell.org/ghc/docs/latest/html/users_guide/ghc-language-features.html user manual], but this page is a place to record user-oriented observations, notes, and suggestions on how to use them.<br />
<br />
* '''[[GHC/Indexed_types|Indexed data types]]'''<br />
* '''[[GHC/TypeHoles|Agda-like "holes" in GHC]]'''<br />
* '''[[GHC/Stand-alone deriving declarations|"Stand-alone deriving" declarations]]'''<br />
* '''[[GHC/TypeSigsAndAmbiguity|Type signatures and ambiguity]]'''<br />
* '''Overlapping instances'''. GHC supports overlapping instances, with carefully specified rules. Make sure you read the [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#instance-declarations relevant sections of the user manual]. Here is an application note about [[GHC/AdvancedOverlap|advanced use of overlapping instances]], combined with functional dependencies.<br />
* '''[[GHC/SuperClass|Super-Class Constraints: Type Families, Type Equalities, FunDep, Overlaps]]'''<br />
* '''[[GHC/Coercible|Safe coercions using Coercible]]'''</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Arrays&diff=63371Arrays2020-07-23T06:09:35Z<p>Ysangkok: fix link to runtime options in users guide</p>
<hr />
<div>Haskell'98 supports just one array constructor type, namely [http://haskell.org/onlinereport/array.html Array], which gives you immutable<br />
boxed arrays. "Immutable" means that these arrays, like any other pure<br />
functional data structure, have contents fixed at construction time.<br />
You can't modify them, only query. There are "modification" operations,<br />
but they just return new arrays and don't modify the original one. This<br />
makes it possible to use Arrays in pure functional code along with lists.<br />
"Boxed" means that array elements are just ordinary Haskell (lazy)<br />
values, which are evaluated on demand, and can even contain bottom<br />
(undefined) values. You can learn how to use these arrays at<br />
http://haskell.org/tutorial/arrays.html and I'd recommend that you read<br />
this before proceeding to the rest of this page<br />
<br />
Nowadays the main Haskell compilers, GHC and Hugs, ship with<br />
the same set of [http://www.haskell.org/ghc/docs/latest/html/libraries/index.html Hierarchical Libraries],<br />
and these libraries contain a new implementation of arrays which is<br />
backward compatible with the Haskell'98 one, but which has far more features.<br />
Suffice it to say that these libraries support 9 types of array<br />
constructors: Array, UArray, IOArray, IOUArray, STArray, STUArray,<br />
DiffArray, DiffUArray and StorableArray. Each provides just one of two interfaces, and one of these you already know.<br />
<br />
== Quick reference ==<br />
<br />
{| class="wikitable" style="text-align:center;"<br />
!<br />
! Immutable<br><hask>instance IArray a e</hask><br />
! IO monad<br><hask>instance MArray a e IO</hask><br />
! ST monad<br><hask>instance MArray a e ST</hask><br />
|-<br />
! Standard<br />
| <hask>Array</hask><br><hask>DiffArray</hask><br />
| <hask>IOArray</hask><br />
| <hask>STArray</hask><br />
|-<br />
! Unboxed<br />
| <hask>UArray</hask><br><hask>DiffUArray</hask><br />
| <hask>IOUArray</hask><br><hask>StorableArray</hask><br />
| <hask>STUArray</hask><br />
|}<br />
<br />
== Immutable arrays (module [http://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-IArray.html Data.Array.IArray]) ==<br />
<br />
The first interface provided by the new array library, is defined<br />
by the typeclass IArray (which stands for "immutable array" and defined<br />
in the module [http://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-IArray.html Data.Array.IArray])<br />
and defines the same operations that were defined for Array in<br />
Haskell'98. The big difference is that it is now a typeclass and there are 4<br />
array type constructors, each of which implements this interface: Array,<br />
UArray, DiffArray, and DiffUArray. We will later describe the differences<br />
between them and the cases when these other types are preferable to use instead<br />
of the good old Array. Also note that to use Array type constructor<br />
together with other new array types, you need to import<br />
Data.Array.IArray module instead of Data.Array<br />
<br />
<br />
<br />
== Mutable IO arrays (module [http://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-IO.html Data.Array.IO]) ==<br />
<br />
The second interface is defined by the type class MArray (which stands for<br />
"mutable array" and is defined in the module [http://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-MArray.html Data.Array.MArray])<br />
and contains operations to update array elements in-place. Mutable<br />
arrays are very similar to IORefs, only they contain multiple values. Type<br />
constructors for mutable arrays are IOArray and IOUArray and<br />
operations which create, update and query these arrays all belong to the<br />
IO monad:<br />
<br />
<haskell><br />
import Data.Array.IO<br />
main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)<br />
a <- readArray arr 1<br />
writeArray arr 1 64<br />
b <- readArray arr 1 <br />
print (a,b)<br />
</haskell><br />
<br />
This program creates an array of 10 elements with all values initially set to 37. Then it reads <br />
the first element of the array. After that, the<br />
program modifies the first element of the array and then reads it<br />
again. The type declaration in the second line is necessary because our little<br />
program doesn't provide enough context to allow the compiler to determine the concrete type of `arr`. Unlike examples, real programs rarely need such declarations.<br />
<br />
<br />
<br />
== Mutable arrays in ST monad (module [http://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-ST.html Data.Array.ST]) ==<br />
<br />
In the same way that IORef has its more general cousin STRef, IOArray has a more<br />
general version STArray (and similarly, IOUArray corresponds to STUArray). These<br />
array types allow one to work with mutable arrays in the ST monad:<br />
<br />
<haskell><br />
import Control.Monad.ST<br />
import Data.Array.ST<br />
<br />
buildPair = do arr <- newArray (1,10) 37 :: ST s (STArray s Int Int)<br />
a <- readArray arr 1<br />
writeArray arr 1 64<br />
b <- readArray arr 1<br />
return (a,b)<br />
<br />
main = print $ runST buildPair<br />
</haskell><br />
<br />
Believe it or not, now you know all that is needed to '''use''' any<br />
array type. Unless you are interested in speed issues, just use Array,<br />
IOArray and STArray where appropriate. The following topics are almost<br />
exclusively about selecting the proper array type to make programs run<br />
faster.<br />
<br />
<br />
<br />
== DiffArray (module [http://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-Diff.html Data.Array.Diff]) ==<br />
<br />
Note, as of Jan 2012, DiffArray is not yet ready for production use; it's practical (wall clock) performance does not live up to its theoretical advantages.<br />
<br />
As we already stated, the update operation on immutable arrays (IArray)<br />
just creates a new copy of the array, which is very inefficient, but it is a<br />
pure operation which can be used in pure functions. On the other hand,<br />
updates on mutable arrays (MArray) are efficient but can be done only<br />
in monadic code. In theory, DiffArray combines the best of both worlds - it<br />
supports the IArray interface and therefore can be used in a purely<br />
functional way, but internally it uses the efficient update of MArrays.<br />
<br />
(In practice, however, DiffArrays are 10-100x slower than MArrays, due to the overhead of maintaining an immmutable interface. See bug report here: [http://trac.haskell.org/diffarray/ticket/2])<br />
<br />
How does this trick work? DiffArray has a pure external interface, but<br />
internally it is represented as a reference to an IOArray.<br />
<br />
When the '//' operator is applied to a diff array, its contents<br />
are physically updated in place. The old array silently changes<br />
its representation without changing the visible behavior: <br />
it stores a link to the new current array along with the <br />
difference to be applied to get the old contents. <br />
<br />
So if a diff array is used in a single-threaded style, <br />
that is, after '//' application the old version is no longer used, <br />
a!i takes O(1) time and a//d takes O(length d). <br />
Accessing elements of older versions gradually becomes slower. <br />
<br />
Updating an array which is not current makes a physical copy. <br />
The resulting array is unlinked from the old family. So you <br />
can obtain a version which is guaranteed to be current and <br />
thus has fast element access by a//[]. <br />
<br />
The library provides two "differential" array constructors - DiffArray,<br />
made internally from IOArray, and DiffUArray, based on IOUArray. If you really need to, you can construct new "differential" array types from any<br />
'MArray' types living in the 'IO' monad. Since GHC-6.12, DiffArray has been splitted off into separated package due to its "unusably slow". See [http://hackage.haskell.org/package/diffarray Hackage documentation] for further details.<br />
<br />
Usage of DiffArray doesn't differ from that of Array, the only difference is memory consumption and speed:<br />
<br />
<haskell><br />
import Data.Array.Diff<br />
<br />
main = do<br />
let arr = listArray (1,1000) [1..1000] :: DiffArray Int Int<br />
a = arr ! 1<br />
arr2 = arr // [(1,37)]<br />
b = arr2 ! 1<br />
print (a,b)<br />
</haskell><br />
<br />
You can use 'seq' to force evaluation of array elements prior to updating an array:<br />
<br />
<haskell><br />
import Data.Array.Diff<br />
<br />
main = do<br />
let arr = listArray (1,1000) [1..1000] :: DiffArray Int Int<br />
a = arr ! 1<br />
b = arr ! 2<br />
arr2 = a `seq` b `seq` (arr // [(1,37),(2,64)])<br />
c = arr2 ! 1<br />
print (a,b,c)<br />
</haskell><br />
<br />
== Unboxed arrays ==<br />
<br />
In most implementations of lazy evaluation, values are represented at runtime as pointers to either their value, or code for computing their value. This extra level of indirection, together with any extra tags needed by the runtime, is known as a box. The default "boxed" arrays consist of many of these boxes, each of which may compute its value separately. This allows for many neat tricks, like recursively defining an array's elements in terms of one another, or only computing the specific elements of the array which are ever needed. However, for large arrays, it costs a lot in terms of overhead, and if the entire array is always needed, it can be a waste.<br />
<br />
Unboxed arrays are more like arrays in C - they contain just the plain<br />
values without this extra level of indirection, so that, for example,<br />
an array of 1024 values of type Int32 will use only 4 kb of memory. <br />
Moreover, indexing of such arrays can be significantly faster.<br />
<br />
Of course, unboxed arrays have their own disadvantages. First, unboxed<br />
arrays can be made only of plain values having a fixed size - Int, Word,<br />
Char, Bool, Ptr, Double, etc. (see the full list in the [http://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-Unboxed.html Data.Array.Unboxed] module).<br />
You can even implement unboxed arrays yourself for other<br />
simple types, including enumerations. But Integer, String and any<br />
other types defined with variable size cannot be elements of unboxed arrays.<br />
Second, without that extra level of indirection, all of the elements in an unboxed array must be evaluated when the array is evaluated, so you lose the benefits of lazy evaluation. Indexing the array to read just one element will construct the entire array. This is not much of a loss if you will eventually need the whole array, but it does prevent recursively defining the array elements in terms of each other, and may be too expensive if you only ever need specific values. Nevertheless, unboxed arrays are a very useful optimization<br />
instrument, and I recommend using them as much as possible.<br />
<br />
All main array types in the library have unboxed counterparts:<br />
<br />
Array - UArray (module Data.Array.Unboxed)<br />
IOArray - IOUArray (module Data.Array.IO)<br />
STArray - STUArray (module Data.Array.ST)<br />
DiffArray - DiffUArray (module Data.Array.Diff)<br />
<br />
So, basically replacing boxed arrays in your program with unboxed ones<br />
is very simple - just add 'U' to the type signatures, and you are done! Of course, if you change Array to UArray, you also need to add "Data.Array.Unboxed"<br />
to your imports list.<br />
<br />
<br />
<br />
== StorableArray (module [http://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-Storable.html Data.Array.Storable]) ==<br />
<br />
A storable array is an IO-mutable array which stores its<br />
contents in a contiguous memory block living in the C<br />
heap. Elements are stored according to the class 'Storable'.<br />
You can obtain the pointer to the array contents to manipulate<br />
elements from languages like C.<br />
<br />
It is similar to 'IOUArray' (in particular, it implements the same<br />
MArray interface) but slower. The advantage is that it's compatible<br />
with C through the foreign function interface. The memory addresses of<br />
storable arrays are fixed, so you can pass them to C routines.<br />
<br />
The pointer to the array contents is obtained by 'withStorableArray'.<br />
The idea is similar to 'ForeignPtr' (used internally here).<br />
The pointer should be used only during execution of the 'IO' action<br />
returned by the function passed as argument to 'withStorableArray'.<br />
<br />
<haskell><br />
{-# OPTIONS_GHC -fglasgow-exts #-}<br />
import Data.Array.Storable<br />
import Foreign.Ptr<br />
import Foreign.C.Types<br />
<br />
main = do arr <- newArray (1,10) 37 :: IO (StorableArray Int Int)<br />
a <- readArray arr 1<br />
withStorableArray arr <br />
(\ptr -> memset ptr 0 40)<br />
b <- readArray arr 1<br />
print (a,b)<br />
<br />
foreign import ccall unsafe "string.h" <br />
memset :: Ptr a -> CInt -> CSize -> IO ()<br />
</haskell><br />
<br />
If you want to use this pointer afterwards, ensure that you call<br />
'touchStorableArray' AFTER the last use of the pointer,<br />
so that the array will be not freed too early.<br />
<br />
<br />
Additional comments: GHC 6.6 made access to <br />
'StorableArray' as fast as to any other unboxed arrays. The only difference between 'StorableArray' and 'UArray' is that UArray lies in relocatable part of GHC heap while 'StorableArray' lies in non-relocatable part and therefore keep the fixed address, what allow to pass this address to the C routines and save it in the C data structures.<br />
<br />
GHC 6.6 also adds an 'unsafeForeignPtrToStorableArray' operation that allows<br />
the use of any Ptr as the address of a 'StorableArray' and in particular works with<br />
arrays returned by C routines. Here is an example of using this operation:<br />
<br />
<haskell><br />
import Data.Array.Storable<br />
import Data.Array.Unsafe<br />
import Foreign.Marshal.Alloc<br />
import Foreign.Marshal.Array<br />
import Foreign.ForeignPtr<br />
<br />
main = do ptr <- mallocArray 10<br />
fptr <- newForeignPtr_ ptr<br />
arr <- unsafeForeignPtrToStorableArray (1,10) fptr :: IO (StorableArray Int Int)<br />
writeArray arr 1 64<br />
a <- readArray arr 1<br />
print a<br />
free ptr<br />
</haskell><br />
<br />
This example allocates memory for 10 Ints (which emulates an array returned by some C function),<br />
then converts the returned 'Ptr Int' to 'ForeignPtr Int' and 'ForeignPtr Int' to<br />
'StorableArray Int Int'. It then writes and reads the first element of the array. At the end, the<br />
memory used by the array is deallocated by 'free', which again emulates deallocation<br />
by C routines. We can also enable the automatic freeing of the allocated block by replacing<br />
"newForeignPtr_ ptr" with "newForeignPtr finalizerFree ptr". In this case memory will be <br />
automatically freed after the last array usage, as for any other Haskell objects.<br />
<br />
<br />
== The Haskell Array Preprocessor (STPP) ==<br />
<br />
Using mutable (IO and ST) arrays in Haskell is not very handy.<br />
But there is one tool which adds syntactic sugar to make the use of such<br />
arrays very close to that of imperative languages. It is written by<br />
Hal Daume III and you can get it at<br />
http://hal3.name/STPP/stpp.tar.gz <br />
<br />
Using this tool, you can index array elements in arbitrarily complex<br />
expressions with the notation "arr[|i|]" and the preprocessor will<br />
automatically convert these forms to the appropriate calls to<br />
'readArray' and 'writeArray'. Multi-dimensional arrays are also<br />
supported, with indexing in the form "arr[|i|][|j|]". See further<br />
descriptions at http://hal3.name/STPP/.<br />
<br />
== Repa package ==<br />
Another option for arrays in Haskell which is worth consideration are REgular PArallel arrays (Repa). Repa is a Haskell library for high performance, regular, multi-dimensional parallel arrays. It allows to easily get an advantage from multi-core CPU's. Repa also provides list-like operations on arrays such as map, fold and zipWith, moreover repa arrays are instances of Num, which comes in hand for many applications.<br />
<br />
Repa employs a different syntax for arrays, which is also used in an experimental accelerate package. [http://hackage.haskell.org/package/accelerate Data.Array.Accelerate] is aimed to gain the performance from using GPGPU (via CUDA).<br />
<br />
Repa possesses a number of other interesting features, such as exporting/importing arrays from ascii or bmp files. For further information consult [[Numeric_Haskell:_A_Repa_Tutorial | repa tutorial]].<br />
<br />
== ArrayRef library ==<br />
<br />
The [http://haskell.org/haskellwiki/Library/ArrayRef#Reimplemented_Arrays_library ArrayRef library] reimplements array libraries with the following extensions:<br />
<br />
* dynamic (resizable) arrays<br />
* polymorphic unboxed arrays<br />
<br />
It also adds [http://haskell.org/haskellwiki/Library/ArrayRef#Syntax_sugar_for_mutable_types syntactic sugar]<br />
which simplifies arrays usage. Although not<br />
as elegant as STPP, it is implemented entirely<br />
inside the Haskell language without requiring any preprocessors.<br />
<br />
<br />
== Unsafe indexing, freezing/thawing, running over array elements ==<br />
<br />
There are operations that convert between mutable and immutable<br />
arrays of the same type, namely 'freeze' (mutable->immutable) and<br />
'thaw' (immutable->mutable). They make a new copy of the array. If you are<br />
sure that a mutable array will not be modified or that an immutable array will<br />
not be used after the conversion, you can use unsafeFreeze/unsafeThaw.<br />
These operations convert array the in-place if the input and resulting<br />
arrays have the the same memory representation (i.e. the same type and<br />
boxing). Please note that the "unsafe*" operations modify memory - they<br />
set/clear a flag in the array header which specifies array mutability.<br />
So these operations can't be used together with multi-threaded access<br />
to arrays (using threads or some form of coroutines).<br />
<br />
There are also operations that convert unboxed arrays to another<br />
element type, namely castIOUArray and castSTUArray. These operations<br />
rely on the actual type representation in memory and therefore there are no<br />
guarantees on their results. In particular, these operations can<br />
be used to convert any unboxable value to a sequence of bytes and<br />
vice versa. For example, they are used in the AltBinary library to serialize<br />
floating-point values. Please note that these operations don't<br />
recompute array bounds to reflect any changes in element size. You<br />
need to do that yourself using the 'sizeOf' operation.<br />
<br />
<br />
While arrays can have any type of index, the internal representation only accepts Ints for indexing. The array libraries first use the Ix class to translate the polymorphic index into an Int. An internal indexing function is then called on this Int index. The internal functions are: unsafeAt, unsafeRead and unsafeWrite, found in the Data.Array.Base module.<br />
You can use these operations yourself in order to speed up your program by avoiding bounds checking. These functions are marked "unsafe" for good a reason -- they allow the programmer to access and overwrite arbitrary addresses in memory. These operations are especially useful<br />
if you need to walk through entire array:<br />
<br />
<haskell><br />
import Data.Array.Base (unsafeAt)<br />
-- | Returns a list of all the elements of an array, in the same order<br />
-- as their indices.<br />
elems arr = [ unsafeAt arr i<br />
| i <- [0 .. rangeSize(bounds arr)-1] ]<br />
</haskell><br />
<br />
"unsafe*" operations in such loops are really safe because 'i' loops<br />
only through positions of existing array elements.<br />
<br />
<br />
== [[GHC]]-specific topics ==<br />
=== Parallel arrays (module GHC.PArr) ===<br />
<br />
As we already mentioned, array library supports two array varieties -<br />
lazy boxed arrays and strict unboxed ones. A parallel array implements<br />
something intermediate: it's a strict boxed immutable array. This<br />
keeps the flexibility of using any data type as an array element while making<br />
both creation of and access to such arrays much faster. Array creation is<br />
implemented as one imperative loop that fills all the array elements,<br />
while accesses to array elements don't need to check the "box". It should be<br />
obvious that parallel arrays are not efficient in cases where the<br />
calculation of array elements is relatively complex and most elements<br />
will not be used. One more drawback of practical usage is that<br />
parallel arrays don't support the IArray interface, which means that you<br />
can't write generic algorithms which work both with Array and the parallel<br />
array constructor.<br />
<br />
Like many GHC extensions, this is described in a paper: [http://www.cse.unsw.edu.au/~chak/papers/CK03.html An Approach to Fast Arrays in Haskell], by Manuel M. T. Chakravarty and Gabriele Keller.<br />
<br />
You can also look at the sources of [http://darcs.haskell.org/packages/base/GHC/PArr.hs GHC.PArr] module, which contains a lot of comments.<br />
<br />
The special syntax for parallel arrays is enabled by "ghc -fparr" or "ghci -fparr" which is undocumented in the GHC 6.4.1 user manual.<br />
<br />
<br />
=== Welcome to the machine: Array#, MutableArray#, ByteArray#, MutableByteArray#, pinned and moveable byte arrays ===<br />
<br />
The GHC heap contains two kinds of objects. Some are just byte sequences,<br />
while the others are pointers to other objects (so-called "boxes"). This<br />
segregation allows the system to find chains of references when performing<br />
garbage collection and to update these pointers when memory used by the heap<br />
is compacted and objects are moved to new places. The internal (raw) GHC<br />
type Array# represents a sequence of object pointers (boxes). There is a<br />
low-level operation in the ST monad which allocates an array of specified size in the heap.<br />
Its type is something like (Int -> ST s Array#). The Array# type is used<br />
inside the Array type which represents boxed immutable arrays.<br />
<br />
There is a different type for '''mutable''' boxed arrays<br />
(IOArray/STArray), namely MutableArray#. A separate type for mutable<br />
arrays is required because of the 2-stage garbage collection mechanism.<br />
The internal representations of Array# and MutableArray# are the same<br />
apart from some flags in header, and this make possible to perform in-place<br />
convsion between MutableArray# and Array# (this is that<br />
unsafeFreeze and unsafeThaw operations do).<br />
<br />
Unboxed arrays are represented by the ByteArray# type. This is just a plain<br />
memory area in the Haskell heap, like a C array. There are two primitive operations<br />
that create a ByteArray# of specified size. One allocates memory in the<br />
normal heap and so this byte array can be moved when<br />
garbage collection occurs. This prevents the conversion of a ByteArray#<br />
to a plain memory pointer that can be used in C procedures (although<br />
it's still possible to pass a current ByteArray# pointer to an "'''unsafe'''<br />
foreign" procedure if the latter doesn't try to store this pointer somewhere).<br />
The second primitive allocates a ByteArray# of a specified size in the<br />
"pinned" heap area, which contains objects with a fixed location. Such a byte<br />
array will never be moved by garbage collection, so its address can be used as a plain<br />
Ptr and shared with the C world. The first way to create ByteArray# is used<br />
inside the implementation of all UArray types, while the second way is used in<br />
StorableArray (although StorableArray can also point to data<br />
allocated by C malloc). Pinned ByteArray# also used in ByteString.<br />
<br />
There is also a MutableByteArray# type which is very similar to ByteArray#, but GHC's primitives support only monadic read/write<br />
operations for MutableByteArray#, and only pure reads for ByteArray#,<br />
as well as the unsafeFreeze/unsafeThaw operations which change appropriate<br />
fields in headers of this arrays. This differentiation doesn't make much<br />
sense except for additional safety checks.<br />
<br />
So, pinned MutableByteArray# or C malloced memory is used inside<br />
StorableArray, pinned ByteArray# or C malloced memory - inside<br />
ByteString, unpinned MutableByteArray# - inside IOUArray and<br />
STUArray, and unpinned ByteArray# is used inside UArray.<br />
<br />
The API's of boxed and unboxed arrays API are almost identical:<br />
<br />
marr <- alloc n - allocates a mutable array of the given size<br />
arr <- unsafeFreeze marr - converts a mutable array to an immutable one<br />
marr <- unsafeThaw arr - converts an immutable array to a mutable one<br />
x <- unsafeRead marr i - monadic reading of the value with the given index from a mutable array<br />
unsafeWrite marr i x - monadic writing of the value with the given index from a mutable array<br />
let x = unsafeAt arr i - pure reading of the value with the given index from an immutable array<br />
(all indices are counted from 0)<br />
<br />
Based on these primitive operations, the array library implements<br />
indexing with any type and with any lower bound, bounds checking and<br />
all other high-level operations. Operations that create<br />
immutable arrays just create them as mutable arrays in the ST monad, make<br />
all required updates on this array, and then use unsafeFreeze before<br />
returning the array from runST. Operations on IO arrays are implemented<br />
via operations on ST arrays using the stToIO operation.<br />
<br />
=== Mutable arrays and GC ===<br />
<br />
GHC implements 2-stage GC which is very fast. Minor GC occurs after<br />
each 256 kb allocated and scans only this area (plus recent stack<br />
frames) when searching for "live" data. This solution uses the fact<br />
that normal Haskell data are immutable and therefore any data<br />
structures created before the previous minor GC can't point to<br />
data structures created after it, since due to immutability, data<br />
can contain only "backward" references.<br />
<br />
But this simplicity breaks down when we add to the language mutable<br />
boxed references (IORef/STRef) and arrays (IOArray/STArray).<br />
On each GC, including minor ones, each element in a<br />
mutable data structure has to be be scanned because it may have been updated<br />
since the last GC and to make it point to data allocated since then.<br />
<br />
For programs that contain a lot of data in mutable boxed<br />
arrays/references, GC times may easily outweigh the useful computation time.<br />
Ironically, one such program is GHC itself.<br />
The solution for such programs is to add to a command line option like "+RTS -A10m", <br />
which increases the size of minor GC chunks from 256 kb to 10 mb, <br />
making minor GC 40 times less frequent. You can see effect of this<br />
change by using "+RTS -sstderr" option: "%GC time" should significantly decrease.<br />
<br />
There is a way to include this option in your executable so that it will<br />
be used automatically on each execution - you should just add to your<br />
the following line to your project C source file:<br />
<br />
char *ghc_rts_opts = "-A10m";<br />
<br />
Of course, you can increase or decrease this value according to your needs.<br />
<br />
Increasing "-A" value doesn't comes for free. Aside from the obvious<br />
increase in memory usage, execution times (of useful code) will also<br />
grow. The default "-A" value is tuned to be close to modern CPU cache sizes, so that most memory references fall inside the cache.<br />
When 10 mb of memory are allocated before doing GC, this data locality<br />
no longer holds. So increasing "-A" can either increase or decrease<br />
program speed. You should try various settings between<br />
64 kb and 16 mb while the running program with "typical" parameters and<br />
try to select the best setting for your specific program and CPU combination.<br />
<br />
There is also another way to avoid increasing GC times: use either<br />
unboxed or immutable arrays. Also note that immutable arrays are built<br />
as mutable ones and then "frozen", so during the construction time GC<br />
will also scan their contents.<br />
<br />
Hopefully, GHC 6.6 has fixed the problem - it remembers which<br />
references/arrays were updated since last GC and scans only them. You<br />
can suffer from the old problems only if you use very<br />
large arrays.<br />
<br />
Further information:<br />
* [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/runtime_control.html#rts-options-to-control-the-garbage-collector RTS options to control the garbage collector]<br />
* [http://hackage.haskell.org/trac/ghc/ticket/650 Problem description by Simon Marlow and report about GHC 6.6 improvements in this area]<br />
* [http://hackage.haskell.org/trac/ghc/wiki/GarbageCollectorNotes Notes about GHC garbage collector]<br />
* [http://research.microsoft.com/~simonpj/Papers/papers.html#gc Papers about GHC garbage collector]<br />
<br />
<br />
== Notes for contributors to this page ==<br />
if you have any questions, please<br />
ask at the IRC/mailing list. If you have any answers, please submit them<br />
directly to this page. please don't sign your contributions, so that<br />
anyone will feel free to further improve this page. but if you are<br />
compiler/Array libraries author - please sign your text to let us know<br />
that it is the Last Word of Truth :-)<br />
<br />
[[Category:Tutorials]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Ruleaza_pe_sisteme_multicore_%3F&diff=63370Ruleaza pe sisteme multicore ?2020-07-23T06:06:51Z<p>Ysangkok: fix link to smp in user guide</p>
<hr />
<div>[[Category:Ro]]<br />
[[Category:Parallel]]<br />
<br />
==. Haskell ruleaza pe sistemele multicore ! ==<br />
<br />
<br />
[http://haskell.org/ghc GHC Haskell] vine impreuna cu biblioteci si optiuni de compilare care permit compilarea pt sisteme Multicore: [http://en.wikipedia.org/wiki/Multi-core_(computing) multicore architectures].<br />
<br />
__TOC__<br />
<br />
== Introducere ==<br />
<br />
Ca sa aveti o idee cum s-ar putea reduce timpul de calcul olosind mai multe nuclee hack-uiti programul de mai jos: un program carre calculeaza termenii sirului lui Fibonacci, pina la un loc secvential apoi paralel. <br />
<br />
<haskell><br />
import Control.Parallel<br />
import Control.Monad<br />
import Text.Printf<br />
<br />
cutoff = 35 -- nivelul de la care comutam pe SMP<br />
<br />
fib' :: Int -> Integer<br />
fib' 0 = 0<br />
fib' 1 = 1<br />
fib' n = fib' (n-1) + fib' (n-2)<br />
<br />
fib :: Int -> Integer -- paralelism explicit<br />
fib n | n < cutoff = fib' n<br />
| otherwise = r `par` (l `pseq` l + r)<br />
where<br />
l = fib (n-1)<br />
r = fib (n-2)<br />
<br />
main = forM_ [0..45] $ \i -><br />
printf "n=%d => %d\n" i (fib i)<br />
</haskell><br />
<br />
Trebuie neaparat compilat cu optiunea `-threaded`:<br />
<br />
$ ghc -O2 -threaded --make fib.hs<br />
[1 of 1] Compiling Main ( fib.hs, fib.o )<br />
Linking fib ...<br />
<br />
Si rulat cu optiunile:<br />
<br />
+RTS -Nx<br />
<br />
unde 'x' unde x de dupa N este numarul de nuclee disponibile.<br />
De exemplu, pe un sistem Linux cu procesor quad core :<br />
<br />
./fib +RTS -N4 <br />
<br />
<br />
=== Exemples ===<br />
<br />
* [http://haskell.org/haskellwiki/Concurrency_demos/Zeta Functia zeta, a lui Riemann ]<br />
<br />
== De citit ==<br />
<br />
* [http://haskell.org/haskellwiki/GHC/Concurrency Ghidul GHC-ului folosit pe multiprocesor ]<br />
* [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/using-concurrent.html#using-smp-parallelism Options pentru utilizarea paralelismului pe masinile SMP]<br />
* [http://www.haskell.org/ghc/docs/latest/html/libraries/parallel/Control-Parallel-Strategies.html Documentation API-ului pt implementat strategii de calcul paralel ]<br />
* [http://book.realworldhaskell.org/read/concurrent-and-multicore-programming.html Real World Haskell:Capitolul Concurrent and Parallel Programming] <br />
* [http://haskell.org/haskellwiki/Blog_articles/Parallel Postari despre parallelism]<br />
<br />
== Primitivele pt lucrul cu thread-uri ==<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent.html Control.Concurrent Control.Concurrent]<br />
<br />
== Continuarea ==<br />
Pe pagina originala, in limba engleza: [[Haskell_for_multicores]]<br />
de unde este luat si tradus textul de mai sus.</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Haskell_for_multicores&diff=63369Haskell for multicores2020-07-23T06:06:28Z<p>Ysangkok: fix link to smp in user guide</p>
<hr />
<div>[[Category:Parallel]]<br />
<br />
[http://haskell.org/ghc GHC Haskell] comes with a large set of libraries and tools for building programs that exploit [http://en.wikipedia.org/wiki/Multi-core_(computing) multicore architectures].<br />
<br />
This site attempts to document all our available information on<br />
exploiting such hardware with Haskell.<br />
<br />
Throughout, we focus on exploiting shared-memory [http://en.wikipedia.org/wiki/Symmetric_multiprocessing SMP systems], with aim of lowering absolute wall clock times. The machines we target are typical 2x to 32x desktop multicore machine, on which vanilla GHC will run.<br />
<br />
__TOC__<br />
<br />
== Introduction ==<br />
<br />
To get an idea of what we aim to do -- reduce running times by exploiting more cores -- here's a naive "hello, world" of parallel programs: parallel, naive fib. It simply tells us whether or not the SMP runtime is working:<br />
<br />
<haskell><br />
import Control.Parallel<br />
import Control.Monad<br />
import Text.Printf<br />
<br />
cutoff = 35<br />
<br />
fib' :: Int -> Integer<br />
fib' 0 = 0<br />
fib' 1 = 1<br />
fib' n = fib' (n-1) + fib' (n-2)<br />
<br />
fib :: Int -> Integer<br />
fib n | n < cutoff = fib' n<br />
| otherwise = r `par` (l `pseq` l + r)<br />
where<br />
l = fib (n-1)<br />
r = fib (n-2)<br />
<br />
main = forM_ [0..45] $ \i -><br />
printf "n=%d => %d\n" i (fib i)<br />
</haskell><br />
<br />
We compile it with the `-threaded` flag:<br />
<br />
$ ghc -O2 -threaded --make fib.hs<br />
[1 of 1] Compiling Main ( fib.hs, fib.o )<br />
Linking fib ...<br />
<br />
And run it with:<br />
<br />
+RTS -Nx<br />
<br />
where 'x' is the number of cores you have (or a slightly higher value).<br />
Here, on a quad core linux system:<br />
<br />
./fib +RTS -N4 76.81s user 0.75s system 351% cpu 22.059 total<br />
<br />
So we were able to use 3.5/4 of the available cpu time. And this is typical, most problems aren't easily scalable, and we must trade off work on more cores, for more overhead with communication.<br />
<br />
=== Examples ===<br />
<br />
* [http://haskell.org/haskellwiki/Concurrency_demos/Zeta Riemann's zeta function]<br />
<br />
=== Further reading ===<br />
<br />
* [http://haskell.org/haskellwiki/GHC/Concurrency GHC's multiprocessor guide]<br />
* [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/using-concurrent.html#using-smp-parallelism runtime options to enable SMP parallelism]<br />
* [http://www.haskell.org/ghc/docs/latest/html/libraries/parallel/Control-Parallel-Strategies.html API documentation for paralell strategies]<br />
* [http://book.realworldhaskell.org/read/concurrent-and-multicore-programming.html Real World Haskell: Concurrent and Parallel Programming] <br />
* [http://haskell.org/haskellwiki/Blog_articles/Parallel Blog posts about parallelism]<br />
<br />
== Thread primitives ==<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent.html Control.Concurrent Control.Concurrent]<br />
<br />
For explicit concurrency and/or parallelism, Haskell implementations have a light-weight thread system that schedules logical threads on the available operating system threads. These light and cheap threads can be created with forkIO. (We won't discuss full OS threads which are created via <code>forkOS</code>, as they have significantly higher overhead and are only useful in a few situations like in FFIs.)<br />
<br />
<haskell><br />
forkIO :: IO () -> IO ThreadId<br />
</haskell><br />
<br />
Lets take a simple Haskell application that hashes two files and prints the result:<br />
<br />
<haskell><br />
import Data.Digest.Pure.MD5 (md5)<br />
import qualified Data.ByteString.Lazy as L<br />
import System.Environment (getArgs)<br />
<br />
main = do<br />
[fileA, fileB] <- getArgs<br />
hashAndPrint fileA<br />
hashAndPrint fileB<br />
<br />
hashAndPrint f = L.readFile f >>= return . md5 >>= \h -> putStrLn (f ++ ": " ++ show h)<br />
</haskell><br />
<br />
This is a straight forward solution that hashs the files one at a time printing the resulting hash to the screen. What if we wanted to use more than one processor to hash the files in parallel?<br />
<br />
One solution is to start a new thread, hash in parallel, and print the answers as they are computed:<br />
<br />
<haskell><br />
import Control.Concurrent (forkIO)<br />
import Data.Digest.Pure.MD5 (md5)<br />
import qualified Data.ByteString.Lazy as L<br />
import System.Environment (getArgs)<br />
<br />
main = do<br />
[fileA,fileB] <- getArgs<br />
forkIO $ hashAndPrint fileA<br />
hashAndPrint fileB<br />
<br />
hashAndPrint f = L.readFile f >>= return . md5 >>= \h -> putStrLn (f ++ ": " ++ show h)<br />
</haskell><br />
<br />
Now we have a rough program with great performance boost - which is expected given the trivially parallel computation.<br />
<br />
But wait! You say there is a bug? Two, actually. One is that if the main thread is finished hashing fileB first, the program will exit before the child thread is done with fileA. The second is a potential for garbled output due to two threads writing to stdout. Both these problems can be solved using some inter-thread communication - we'll pick this example up in the MVar section.<br />
<br />
=== Further reading ===<br />
<br />
* [http://blog.moertel.com/articles/2004/03/13/concurrent-port-scanner-in-haskell A concurrent port scanner]<br />
* [http://haskell.org/haskellwiki/Research_papers/Parallelism_and_concurrency#Concurrent_Haskell Research papers on concurrency in Haskell]<br />
* [http://haskell.org/haskellwiki/Research_papers/Parallelism_and_concurrency#Parallel_Haskell Research papers on parallel Haskell]<br />
<br />
== Synchronisation with locks ==<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent-MVar.html Control.Concurrent.MVar]<br />
<br />
Locking mutable variables (MVars) can be used to great effect not only for communicating values (such as the resulting string for a single function to print) but it is also common for programmers to use their locking features as a signaling mechanism.<br />
<br />
MVars are a polymorphic mutable variables that might or might not contain a value at any given time. Common functions include:<br />
<br />
<haskell><br />
newMVar :: a -> IO (MVar a)<br />
newEmptyMVar :: IO (MVar a)<br />
takeMVar :: MVar a -> IO a<br />
putMVar :: MVar a -> a -> IO ()<br />
isEmptyMVar :: MVar a -> IO Bool<br />
</haskell><br />
<br />
While they are fairly self-explanitory it should be noted that <hask>takeMVar</hask> will block until the MVar is non-empty and <hask>putMVar</hask> will block until the current MVar is empty. Taking an MVar will leave the MVar empty when returning the value.<br />
<br />
In the <hask>forkIO</hask> example we developed a program to hash two files in parallel and ended with a couple small bugs because the program terminated prematurely (the main thread would exit when done). A second issue was that threads can conflict with each others use of stdout.<br />
<br />
Lets now generalize the example to operate on any number of files, block until the hashing is complete, and print all the results from just one thread so no stdout garbling occurs.<br />
<br />
<haskell><br />
{-# LANGUAGE BangPatterns #-}<br />
import Data.Digest.Pure.MD5<br />
import qualified Data.ByteString.Lazy as L<br />
import System.Environment<br />
import Control.Concurrent<br />
import Control.Monad (replicateM_)<br />
<br />
main = do<br />
files <- getArgs<br />
str <- newEmptyMVar<br />
mapM_ (forkIO . hashAndPrint str) files<br />
printNrResults (length files) str<br />
<br />
printNrResults i var = replicateM_ i (takeMVar var >>= putStrLn)<br />
<br />
hashAndPrint str f = do<br />
bs <- L.readFile f<br />
let !h = show $ md5 bs<br />
putMVar str (f ++ ": " ++ h)<br />
</haskell><br />
<br />
We define a new variable, <hask>str</hask>, as an empty MVar. After the hashing, the result is reported with <hask>putMVar</hask> - remember this function blocks when the MVar is already full so no hashes are dropped on account of the mutable memory. Similarly, <hask>printNrResults</hask> uses the <hask>takeMVar</hask> function which will block until the MVar is full - or once the next file is done being hashed in this case.<br />
<br />
Note how the value is evaluated before the putMVar call. If the argument is an unevaluated thunk then <hask>printNrResults</hask> will have to evaluate the thunks before it prints the result and our efforts would have been worthless. <br />
<br />
Knowing the <hask>str</hask> MVar will be filled '<hask>length files</hask>' times we can let the main thread exit after printing the given number of results, thus terminating the program.<br />
<br />
<pre><br />
$ ghc exMVar.hs -o exMVar-threaded --make -O2 -threaded<br />
$ time ./exMVar-threaded +RTS -N2 -RTS 2GB 2GB 2GB 2GB <br />
2GB: b8f1f1faa6dda5426abffb3a7811c1fb<br />
2GB: b8f1f1faa6dda5426abffb3a7811c1fb<br />
2GB: b8f1f1faa6dda5426abffb3a7811c1fb<br />
2GB: b8f1f1faa6dda5426abffb3a7811c1fb<br />
<br />
real 0m40.524s<br />
<br />
<br />
$ time ./exMVar-threaded +RTS -N1 -RTS 2GB 2GB 2GB 2GB<br />
2GB: b8f1f1faa6dda5426abffb3a7811c1fb<br />
2GB: b8f1f1faa6dda5426abffb3a7811c1fb<br />
2GB: b8f1f1faa6dda5426abffb3a7811c1fb<br />
2GB: b8f1f1faa6dda5426abffb3a7811c1fb<br />
<br />
real 1m8.170s<br />
</pre><br />
<br />
=== Further reading ===<br />
<br />
== Message passing channels ==<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Concurrent-Chan.html Control.Concurrent.Chan]<br />
<br />
For streaming data it is hard to beat the performance of channels. After declaring a channel (<hask>newChan</hask>), you can pipe data between threads (<hask>writeChan</hask>, <hask>readChan</hask>) and tee data to separate readers (<hask>dupChan</hask>). The flexibility of channels makes them useful for a wide range of communications.<br />
<br />
Continuing with our hashing example, lets say the names of the files needing hashed are coming available, or need streaming for other reasons. We can fork a set of worker threads and feed them the filenames through a channel. For consistancy, the program has also been modified to communicate the result from worker to printer via a channel.<br />
<br />
<haskell><br />
{-# LANGUAGE BangPatterns #-}<br />
import Data.Digest.Pure.MD5<br />
import qualified Data.ByteString.Lazy as L<br />
import System.Environment<br />
import Control.Concurrent<br />
import Control.Concurrent.Chan<br />
import Control.Monad (forever, forM_, replicateM_)<br />
<br />
nrWorkers = 2<br />
<br />
main = do<br />
files <- getArgs<br />
str <- newChan<br />
fileChan <- newChan<br />
forM_ [1..nrWorkers] (\_ -> forkIO $ worker str fileChan)<br />
forM_ files (writeChan fileChan)<br />
printNrResults (length files) str<br />
<br />
printNrResults i var = replicateM_ i (readChan var >>= putStrLn)<br />
<br />
worker :: Chan String -> Chan String -> IO ()<br />
worker str fileChan = forever (readChan fileChan >>= hashAndPrint str)<br />
<br />
hashAndPrint str f = do<br />
bs <- L.readFile f<br />
let !h = show $ md5 bs<br />
writeChan str (f ++ ": " ++ h)<br />
</haskell><br />
<br />
Notice that this has advantages: results are available incrementally, and the performance has improved with the number of parallel hash operations matching the number of cores.<br />
<br />
=== Examples ===<br />
<br />
* [http://haskell.org/haskellwiki/Implement_a_chat_server Implementing a chat server]<br />
* [http://haskell.org/haskellwiki/Concurrency_demos/Two_reader_threads Two reader threads]<br />
<br />
=== Further reading ===<br />
<br />
== Lock-free synchronisation ==<br />
<br />
[http://www.haskell.org/haskellwiki/Software_transactional_memory Software Transactional Memory]<br />
<br />
* STM<br />
<br />
''Todo''<br />
<br />
=== Further reading ===<br />
<br />
* [http://haskell.org/haskellwiki/Research_papers/Parallelism_and_concurrency#Lock_free_data_structures_and_transactional_memory Research papers on transactional memory]<br />
<br />
== Asynchronous messages ==<br />
<br />
[http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Exception.html#11 Control.Exception:asynchronous]<br />
<br />
* Async exceptions<br />
<br />
<br />
''Todo''<br />
<br />
=== Examples ===<br />
<br />
* [http://haskell.org/haskellwiki/Concurrency_demos/Graceful_exit Graceful exit]<br />
<br />
=== Further reading ===<br />
<br />
== Parallelism strategies ==<br />
<br />
[http://hackage.haskell.org/package/parallel Control.Parallel]<br />
<br />
* Parallel, pure strategies<br />
<br />
''Todo''<br />
<br />
=== Further reading ===<br />
<br />
* [http://haskell.org/haskellwiki/Shootout/Parallel/BinaryTrees Parallel binary trees benchmark]<br />
<br />
== Data parallel arrays ==<br />
<br />
[http://haskell.org/haskellwiki/GHC/Data_Parallel_Haskell Data Parallel Arrays]<br />
<br />
''Todo''<br />
<br />
=== Further reading ===<br />
<br />
== Foreign languages calls and concurrency ==<br />
<br />
Non-blocking foreign calls in concurrent threads.<br />
<br />
== Profiling and measurement ==<br />
<br />
+RTS -sstderr<br />
<br />
=== Further reading ===<br />
<br />
''Todo''</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Windows&diff=63368Windows2020-07-23T06:04:32Z<p>Ysangkok: fix links to user guide</p>
<hr />
<div>== Quickstart on Windows 7 ==<br />
<br />
This page describes what you need to know to ''use'' Haskell on a Windows machine.<br />
See [https://ghc.haskell.org/trac/ghc/wiki/Building/Preparation/Windows the GHC Trac Wiki] for what you need to know to ''build'' GHC on Windows.<br />
<br />
For a minimal setup [https://www.haskell.org/downloads/windows download the MinGHC package from haskell.org/downloads].<br />
<br />
This should install ghc, ghci, cabal, mingw and msys2 to "C:\Program Files\MinGHC-#.##.##" for the latest MinGHC version #, and add the correct programs to your path. <br />
<br />
=== Msys2 Shells and Building Hoogle ===<br />
<br />
If you launch <hask>msys2_shell.bat</hask> (as opposed to <hask>mingw32_shell.bat</hask> or <hask>mingw64_shell.bat</hask>) then make sure that the following environment variable is defined : <br />
<br />
* <hask>MSYSTEM=MINGW32</hask> or <hask>MSYSTEM=MINGW64</hask><br />
<br />
Then test by firing up either <hask>msys2_shell.bat</hask>, <hask>mingw32_shell.bat</hask>, or <hask>mingw64_shell.bat</hask> and then executing the following sequence of commands : <br />
<br />
* <hask><br />
mkdir test<br />
cd test<br />
cabal sandbox init<br />
cabal install hoogle<br />
</hask><br />
<br />
Note that the absence of the environment variables above will result in linker errors when building hoogle.<br />
<br />
== Editors ==<br />
<br />
* [http://www.e-texteditor.com/ E-Text Editor (TextMate for Windows)]<br />
* [http://www.textpad.com/ TextPad]<br />
* [http://ftp.gnu.org/gnu/emacs/windows/ Emacs], [http://www.vim.org/ Vi(m)], etc<br />
* [http://www.leksah.org/index.html Leksah]: Haskell IDE written in Haskell<br />
* [http://eclipsefp.sourceforge.net/ Eclipse]<br />
* [http://notepad-plus-plus.org/ Notepad++]<br />
* [http://www.sublimetext.com/ Sublime Text]<br />
* [http://www.pnotepad.org/ Programmer's Notepad]<br />
See also the [[Editors]] page<br />
<br />
== Compilers/interpreters ==<br />
<br />
* [[Stack]] &mdash; this is not a compiler, but will install [[GHC]] automatically.<br />
* [http://www.haskell.org/platform/ The Haskell Platform] is a combination of GHC and a set of blessed libraries<br />
* [[WinHugs]]<br />
* [[GHC]]: Special notes for Cygwin users - [http://www.haskell.org/ghc/docs/6.6/html/building/platforms.html] [http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci-cygwin.html]<br />
* [http://code.google.com/p/winghci/ WinGhci], a GUI for GHCi (included in the Haskell Platform)<br />
<br />
== Tools for compilation ==<br />
<br />
If you use [https://www.haskell.org/downloads/windows MinGHC], the necessary compilers and Unix tools for compilation (such as MSYS2, mingw, gcc / g++, etc.) are installed automatically.<br />
<br />
* As some of the packages contain Unix/Linux specific scripts/commands, you need [http://www.mingw.org/ MinGW] or [http://mingw-w64.org/doku.php Mingw-w64] (the 64 bit version of MinGW) and [http://www.mingw.org/wiki/msys MSYS] to simulate a Unix environment. In some cases you need [http://www.cygwin.com/ Cygwin] instead. If you use [http://code.google.com/p/msysgit/ msysgit] on Windows already, all you need to do is add MinGW to your path.<br />
<br />
* If you need to link to C-software, [http://en.wikipedia.org/wiki/Environment_variable#DOS.2C_OS.2F2_and_Windows_.28Command_Prompt.29 define environment variable] C_INCLUDE_PATH that lists the directories where the header files can be found, for example:<br />
Set C_INCLUDE_PATH=C:\usr\local\include;C:\usr\local\include\SDL<br />
:(It is advisable to use paths without spaces, because some scripts in the MinGW/MSYS environment have problems with spaces in paths.)<br><br />
:For linking the libraries, you need to define environment variable LIBRARY_PATH as well, listing the directories where .a and .lib files can be found. In case C++ software must be compiled, define CPLUS_INCLUDE_PATH to list the directories with C++ header files.<br />
<br />
* Packages are often delivered as a .tar or .tar.gz file, see [[How to unpack a tar file in Windows]]<br />
<br />
* In some cases, [http://sourceforge.net/projects/pkgconfiglite/files/latest/download pkg-config.exe] is needed for compiling C/C++ packages<br />
<br />
== Generating Dynamically Linked Libraries (DLL's) ==<br />
<br />
If you have GHC >= 7.0.1, see [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/shared_libs.html Using shared libraries] and [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/win32-dlls.html#win32-dlls Building and using Win32 DLLs].<br />
<br />
=== Linking DLL's against C++ ===<br />
<br />
Recent improvements to GHC's handling of shared libraries make this fairly painless for simple projects. However, as of GHC 7.10.1, linking against C++ object files can break FFI symbol exports. To circumvent the issue, use dlltool.exe (in a similar process to building with < GHC 7.0.1). <br />
<br />
This process can be automated by combining GHC's ability to generate a makefile, dlltool.exe's ability to create a .def symbol export file from compiled object files, and [http://hackage.haskell.org/package/shake-0.15.4/docs/Development-Shake-Util.html#v:parseMakefile Shake's makefile parser]. <br />
<br />
First the makefile is created:<br />
ghc -M -dep-suffix . dep-makefile ./<make> MyMain.hs<br />
<br />
Then dlltool.exe extracts all exported symbols from the compiled object files (.o). <br />
<br />
dlltool.exe -z dll.def -D MyDll.dll --export-all-symbols hs/<file1>.o hs/<file2>.o ...<br />
<br />
Finally, a .dll can be output by including the .def file in the ghc command.<br />
<br />
ghc -static -shared -package base -package ... -o MyDll.dll cpp/<file.o> ... hs/<file1>.o hs/<file2>.o ... dll.def -lstdc++<br />
<br />
dlltool.exe is included in the MinGHC distribution of GHC. In 7.10.1, it is installed at "C:\Program Files\MinGHC-7.10.1\ghc-7.10.1\mingw\bin"<br />
<br />
A clumsy, but working [http://shakebuild.com/ Shake]file implementing this approach is available [https://gist.github.com/oconnore/7d874f23dc4a825f5bc4 here] for reference. <br />
<br />
=== Building DLL's with an older GHC ===<br />
<br />
To work with/produce DLL files with GHC < 7.0.1, you need dlltool.exe, from the [http://sourceforge.net/projects/mingw/files/ mingw-binutils] package and pexports.exe from the [http://sourceforge.net/projects/mingw/files/ mingw-utils] package. For more information see [http://www.cse.yorku.ca/tdb/_doc.php/userg/man/name/dlltool/section/1 the dlltool manual] and [http://www.willus.com/mingw/yongweiwu_stdcall.html Stdcall and DLL tools of MSVC and MinGW]<br />
<br />
== Libraries ==<br />
<br />
* GUI : [[wxHaskell]] - A binding of wxWidgets (formerly known as wxWindows) in Haskell. Note: see also [[wxHaskell/Windows]]<br />
<br />
* GUI : [[Gtk2Hs]] - A binding of GTK+ in Haskell. Note: this requires installing [http://www.gtk.org GTK+] on windows.<br />
<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Win32 Win32] - low levelish bindings to Windows API. Comes with GHC and non-minimal Hugs distribution. [https://github.com/haskell/win32 Win32 git repo]<br />
<br />
* [[HDBC-ODBC under Windows]] for database access.<br />
<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/winerror winerror]: Error handling for foreign calls to the Windows API<br />
<br />
== Special tips and tricks for Windows ==<br />
<br />
* If there are DLLs missing from your environment, you can find out which, using [http://cygwin.com/cygwin-ug-net/using-utils.html cygcheck] from the [http://www.cygwin.com/ Cygwin project]. Note, that you will get problems if you have both MinGW and Cygwin in your search path; it is best to specify the full path to cygcheck.exe, or copy cygcheck.exe to some location in the search path.<br />
: Another option is [http://www.dependencywalker.com/ Dependency Walker]; this tool can also be used to find out, in which DLL a crash occurs.<br />
<br />
* [http://www.haskell.org/pipermail/haskell-cafe/2013-February/106436.html Terminal Win32/Building Haskeline/8.3 file issue] (Haskell-cafe)<br />
<br />
* darcs : http://wiki.darcs.net/WindowsConfiguration<br />
<br />
* Make sure your Haskell compiler (e.g. GHC) and tools are on your system path: http://www.computerhope.com/issues/ch000549.htm<br />
<br />
* Instead of using WinGHCi, one can also run GHCi in shell mode in Emacs &mdash; do 'M-x shell' in Emacs, then type 'ghci'.<br />
<br />
* GHCi on Cygwin: When running GHC under a Cygwin shell on Windows, Ctrl-C sometimes doesn't work. A workaround is to use the rlwrap program to invoke GHCi : In addition to proper Ctrl-C, you also get Emacs (or vi) key bindings and command history across sessions, which saves you a load of typing.<br />
<br />
* If a package depends (either directly or indirectly) on the <code>unix</code> package, you cannot compile it on Windows (except when using Cygwin).<br />
:A simple way to see, if a package X depends on <code>unix</code>, is giving the command:<br />
cabal install X --dry-run<br />
:This will list all packages that would be installed<br />
<br />
* If you are missing or need to distribute libraries with an application, the correct place to put them is *NOT* in \WINDOWS\System32 as once was the practice in the early days of Windows. All sane applications/installers keep their own private dependencies in the application directory. E.g., if the user has chosen to install your application to C:\Program Files\Foo then it is best to install any DLLs in the same location.<br />
<br />
* When compiling a program with GUI, use the compiler option -optl-mwindows to prevent a DOS-shell being displayed behind your GUI. (This passes the option -mwindows to the linker.)<br />
<br />
* Source files from Unix(-like) systems have lines terminated with Line Feed only; if your favorite editor cannot handle this, you can convert the files to MS-DOS format with the <code>unix2dos</code> command (from the [http://sourceforge.net/projects/mingw/files/ mingw-utils] package). For more information, give command: <code>unix2dos --help</code><br />
:Note, that GHC can handle source files in Unix format.<br />
<br />
* To convert a set of files to MS-DOS format (note: this might damage binary files):<br />
::<code>C:\MSYS\1.0\bin\find . -type f -exec unix2dos {} ;</code><br />
:Note: the <code>find</code> command included in MSYS is different from the MS-DOS <code>find</code> command, therefore, you need to specify the entire path to this command.<br />
<br />
== Binary downloads ==<br />
<br />
=== Haskell ===<br />
<br />
Below a list of binary packages for Windows. To be sure you get the most recent version of each, it is best to download the source from [http://hackage.haskell.org/packages/archive/pkg-list.html Hackage] and compile (except for the Haskell Platform).<br />
<br />
* [http://www.haskell.org/platform/windows.html The Haskell Platform] [[Haskell Platform | (HaskellWiki page)]], contains GHC and a set of libraries and tools <br />
* [https://www.haskell.org/ghc/dist/7.8.3/ghc-7.8.3-i386-unknown-mingw32.tar.xz GHC 7.8.3 for Windows x86], [https://www.haskell.org/ghc/dist/7.8.3/ghc-7.8.3-x86_64-unknown-mingw32.tar.xz GHC 7.8.3 for Windows 64 bit] [[GHC | (HaskellWiki page)]]<br />
* [http://leksah.org/download.html Leksah] [[Leksah | (HaskellWiki page)]]<br />
* [http://darcs.net/Binaries Darcs] [[Darcs | (HaskellWiki page)]]<br />
* [http://repetae.net/computer/haskell/DrIFT/drop/ Drift] [http://repetae.net/computer/haskell/DrIFT/ (website)] <br />
* [http://www.haskell.org/haddock/haddock-0.7-Win32.zip Haddock 0.7] (obsolete) [http://www.haskell.org/haddock/ (website)] <br />
* [http://www.haskell.org/happy/dist/1.13/happy-1-13.msi Happy 1.13] (obsolete) [http://www.haskell.org/happy/ (website)] <br />
* [ftp://ftp.cs.york.ac.uk/pub/haskell/contrib/hscolour-1.9.zip HsColour 1.9] [http://www.cs.york.ac.uk/fp/darcs/hscolour/ (website)] <br />
* [http://cvs.haskell.org/Hugs/pages/downloading.htm WinHugs September 2006] [http://www.haskell.org/hugs/ (website)] <br />
* [http://haskell.forkio.com/Home/curl-win32/curl-7.19.4-mingw32.zip?attredirects=0 cURL 7.19.4] [http://haskell.forkio.com/Home/curl-win32/ (website)]<br />
<br />
=== Development ===<br />
<br />
[https://ghc.haskell.org/trac/ghc/wiki/Building/Preparation/Windows Setting up a Windows system for building GHC]<br />
<br />
== Shipping Installable Applications ==<br />
<br />
* [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/bamse bamse] lets you build windows installers for your Haskell app (MSI). N.B. <code>bamse</code> is not updated since 2009 and can not be compiled with recent compiler/packages; it depends on <code>com</code>, which also suffered bitrot.<br />
* [http://www.jrsoftware.org/isinfo.php Inno Setup] is another tool to create windows installers.<br />
* [http://wixtoolset.org/ WiX Toolset], builds Windows installation packages from XML source code<br />
* [http://zero-install.sourceforge.net/ Zero Install] creates packages for several platforms ("a decentralised cross-distribution software installation system")<br />
<br />
[[Category:OS]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Typeclassopedia&diff=63367Typeclassopedia2020-07-23T06:02:56Z<p>Ysangkok: fix link to recursive do in ghc user guide</p>
<hr />
<div>''By [[User:Byorgey|Brent Yorgey]], byorgey@gmail.com''<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 [{{HackageDocs|base|Prelude}} <code>Prelude</code>], the type system, data types, and type classes.<br />
<br />
The type classes we will be discussing and their interrelationships ([[:File:Dependencies.txt|source code for this graph can be found here]]):<br />
<br />
[[Image:Typeclassopedia-diagram.png]]<br />
<br />
{{note|<code>Apply</code> can be found 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 lines</span> indicate some other sort of relationship.<br />
* <code>Monad</code> and <code>ArrowApply</code> are equivalent.<br />
* <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://www.haskell.org/onlinereport/haskell2010/ Haskell 2010 Language 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 />
[[Instances of List and Maybe]] illustrates these type classes with simple examples using List and Maybe. We now begin with the simplest type class of all: <code>Functor</code>.<br />
<br />
=Functor=<br />
<br />
The <code>Functor</code> class ([{{HackageDocs|base|Prelude}}#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 />
<br />
(<$) :: a -> f b -> f a<br />
(<$) = fmap . const<br />
</haskell><br />
<br />
<code>Functor</code> is exported by the <code>Prelude</code>, so no special imports are needed to use it. Note that the <code>(<$)</code> operator is provided for convenience, with a default implementation in terms of <code>fmap</code>; it is included in the class just to give <code>Functor</code> instances the opportunity to provide a more efficient implementation than the default. To understand <code>Functor</code>, then, we really need to understand <code>fmap</code>.<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 a concrete type like <code>Int</code>; it is a sort of ''type function'' which takes another type as a parameter. More precisely, the ''kind'' of <code>f</code> must be <code>* -> *</code>. For example, <code>Maybe</code> is such a type with kind <code>* -> *</code>: <code>Maybe</code> is not a concrete type by itself (that is, there are no values of type <code>Maybe</code>), 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 />
Finally, we can understand <code>(<$)</code>: instead of applying a function to the values a container/context, it simply replaces them with a given value. This is the same as applying a constant function, so <code>(<$)</code> can be implemented in terms of <code>fmap</code>.<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 :: (a -> b) -> [a] -> [b]<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 :: (a -> b) -> Maybe a -> Maybe b<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 library as well:<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://archive.fo/9sQhq 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 :: (a -> b) -> [a] -> [b]<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://archive.fo/U8xIY 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 />
{{note|Actually, if <code>seq</code>/<code>undefined</code> are considered, it [http://stackoverflow.com/a/8323243/305559 is possible] to have an implementation which satisfies the first law but not the second. The rest of the comments in this section should be considered in a context where <code>seq</code> and <code>undefined</code> are excluded.}}<br />
<br />
A [https://github.com/quchen/articles/blob/master/second_functor_law.md 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.{{noteref}}<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 (excluding <code>undefined</code>), 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 />
==Utility functions==<br />
<br />
There are a few more <code>Functor</code>-related functions which can be imported from the <code>Data.Functor</code> module.<br />
<br />
* <code>(<$>)</code> is defined as a synonym for <code>fmap</code>. This enables a nice infix style that mirrors the <code>($)</code> operator for function application. For example, <code>f $ 3</code> applies the function <code>f</code> to 3, whereas <code>f <$> [1,2,3]</code> applies <code>f</code> to each member of the list.<br />
* <code>($>) :: Functor f => f a -> b -> f b</code> is just <code>flip (<$)</code>, and can occasionally be useful. To keep them straight, you can remember that <code>(<$)</code> and <code>($>)</code> point towards the value that will be kept.<br />
* <code>void :: Functor f => f a -> f ()</code> is a specialization of <code>(<$)</code>, that is, <code>void x = () <$ x</code>. This can be used in cases where a computation computes some value but the value should be ignored.<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 [{{HackageDocs|base|Control-Applicative}} <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> (variously pronounced as "apply", "app", or "splat"). 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 />
infixl 4 <*>, *>, <*<br />
(<*>) :: f (a -> b) -> f a -> f b<br />
<br />
(*>) :: f a -> f b -> f b<br />
a1 *> a2 = (id <$ a1) <*> a2<br />
<br />
(<*) :: f a -> f b -> f a<br />
(<*) = liftA2 const<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 />
<code>(*>)</code> and <code>(<*)</code> are provided for convenience, in case a particular instance of <code>Applicative</code> can provide more efficient implementations, but they are provided with default implementations. For more on these operators, see the section on [[#Utility functions|Utility functions]] below.<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 />
[{{HackageDocs|base|Control-Applicative}} haddock for Applicative] and [http://www.soi.city.ac.uk/~ross/papers/Applicative.html Applicative programming with effects]}}<br />
<br />
Traditionally, there are four laws that <code>Applicative</code> instances should satisfy {{noteref}}. In some sense, they are all concerned with making sure that <code>pure</code> deserves its name:<br />
<br />
* The identity law:<br /><haskell>pure id <*> v = v</haskell><br />
* Homomorphism:<br /><haskell>pure f <*> pure x = pure (f x)</haskell>Intuitively, applying a non-effectful function to a non-effectful argument in an effectful context is the same as just applying the function to the argument and then injecting the result into the context with <code>pure</code>.<br />
* Interchange:<br /><haskell>u <*> pure y = pure ($ y) <*> u</haskell>Intuitively, this says that when evaluating the application of an effectful function to a pure argument, the order in which we evaluate the function and its argument doesn't matter.<br />
* Composition:<br /><haskell>u <*> (v <*> w) = pure (.) <*> u <*> v <*> w </haskell>This one is the trickiest law to gain intuition for. In some sense it is expressing a sort of associativity property of <code>(<*>)</code>. The reader may wish to simply convince themselves that this law is type-correct.<br />
<br />
Considered as left-to-right rewrite rules, the homomorphism, interchange, and composition laws actually constitute an algorithm for transforming any expression using <code>pure</code> and <code>(<*>)</code> into a canonical form with only a single use of <code>pure</code> at the very beginning and only left-nested occurrences of <code>(<*>)</code>. Composition allows reassociating <code>(<*>)</code>; interchange allows moving occurrences of <code>pure</code> leftwards; and homomorphism allows collapsing multiple adjacent occurrences of <code>pure</code> into one.<br />
<br />
There is also a law specifying how <code>Applicative</code> should relate to <code>Functor</code>:<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. Since <code>(<$>)</code> is a synonym for <code>fmap</code>, the above law can also be expressed as:<br />
<br />
<code>g <$> x = pure g <*> x</code>.<br />
<br />
{{Exercises|<br />
# (Tricky) One might imagine a variant of the interchange law that says something about applying a pure function to an effectful argument. Using the above laws, prove that<haskell>pure f <*> x = pure (flip ($)) <*> x <*> pure f</haskell><br />
}}<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 :: a -> ZipList a<br />
pure = undefined -- exercise<br />
<br />
(<*>) :: ZipList (a -> b) -> ZipList a -> ZipList b<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 :: a -> [a]<br />
pure x = [x]<br />
<br />
(<*>) :: [a -> b] -> [a] -> [b]<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 />
x3 :: 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 />
In addition, as of GHC 8, the <code>ApplicativeDo</code> extension enables <code>g <$> x1 <*> x2 <*> ... <*> xn</code> to be written in a different style:<br />
<haskell><br />
do v1 <- x1<br />
v2 <- x2<br />
...<br />
vn <- xn<br />
pure (g v1 v2 ... vn)<br />
</haskell><br />
See the Further Reading section below as well as the discussion of do-notation in the Monad section for more information.<br />
<br />
==Utility functions==<br />
<br />
<code>Control.Applicative</code> provides several utility functions that work generically with any <code>Applicative</code> instance.<br />
<br />
* <code>liftA :: Applicative f => (a -> b) -> f a -> f b</code>. This should be familiar; of course, it is the same as <code>fmap</code> (and hence also the same as <code>(<$>)</code>), but with a more restrictive type. This probably exists to provide a parallel to <code>liftA2</code> and <code>liftA3</code>, but there is no reason you should ever need to use it.<br />
<br />
* <code>liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c</code> lifts a 2-argument function to operate in the context of some <code>Applicative</code>. When <code>liftA2</code> is fully applied, as in <code>liftA2 f arg1 arg2</code>,it is typically better style to instead use <code>f <$> arg1 <*> arg2</code>. However, <code>liftA2</code> can be useful in situations where it is partially applied. For example, one could define a <code>Num</code> instance for <code>Maybe Integer</code> by defining <code>(+) = liftA2 (+)</code> and so on.<br />
<br />
* There is a <code>liftA3</code> but no <code>liftAn</code> for larger <code>n</code>.<br />
<br />
* <code>(*>) :: Applicative f => f a -> f b -> f b</code> sequences the effects of two <code>Applicative</code> computations, but discards the result of the first. For example, if <code>m1, m2 :: Maybe Int</code>, then <code>m1 *> m2</code> is <code>Nothing</code> whenever either <code>m1</code> or <code>m2</code> is <code>Nothing</code>; but if not, it will have the same value as <code>m2</code>.<br />
<br />
* Likewise, <code>(<*) :: Applicative f => f a -> f b -> f a</code> sequences the effects of two computations, but keeps only the result of the first, discarding the result of the second. Just as with <code>(<$)</code> and <code>($>)</code>, to keep <code>(<*)</code> and <code>(*>)</code> straight, remember that they point towards the values that will be kept.<br />
<br />
* <code>(<**>) :: Applicative f => f a -> f (a -> b) -> f b</code> is similar to <code>(<*>)</code>, but where the first computation produces value(s) which are provided as input to the function(s) produced by the second computation. Note this is not the same as <code>flip (<*>)</code>, because the effects are performed in the opposite order. This is possible to observe with any <code>Applicative</code> instance with non-commutative effects, such as the instance for lists: <code>(<**>) [1,2] [(+5),(*10)]</code> produces a different result than <code>(flip (<*>))</code> on the same arguments. <br />
<br />
* <code>when :: Applicative f => Bool -> f () -> f ()</code> conditionally executes a computation, evaluating to its second argument if the test is <code>True</code>, and to <code>pure ()</code> if the test is <code>False</code>.<br />
<br />
* <code>unless :: Applicative f => Bool -> f () -> f ()</code> is like <code>when</code>, but with the test negated.<br />
<br />
* The <code>guard</code> function is for use with instances of <code>Alternative</code> (an extension of <code>Applicative</code> to incorporate the ideas of failure and choice), which is discussed in the [[#Failure_and_choice:_Alternative.2C_MonadPlus.2C_ArrowPlus|section on <code>Alternative</code> and friends]].<br />
<br />
{{Exercises|<br />
# Implement a function <haskell>sequenceAL :: Applicative f => [f a] -> f [a]</haskell>. There is a generalized version of this, <code>sequenceA</code>, which works for any <code>Traversable</code> (see the later section on Traversable), but implementing this version specialized to lists is a good exercise.<br />
}}<br />
<br />
==Alternative formulation==<br />
<br />
An alternative, equivalent formulation of <code>Applicative</code> is given by<br />
<br />
<haskell><br />
class Functor f => Monoidal f where<br />
unit :: f ()<br />
(**) :: f a -> f b -> f (a,b)<br />
</haskell><br />
<br />
{{note|In category-theory speak, we say <code>f</code> is a ''lax'' monoidal functor because there aren't necessarily functions in the other direction, like <code>f (a, b) -> (f a, f b)</code>.}}<br />
Intuitively, this states that a <i>monoidal</i> functor{{noteref}} is one which has some sort of "default shape" and which supports some sort of "combining" operation. <code>pure</code> and <code>(<*>)</code> are equivalent in power to <code>unit</code> and <code>(**)</code> (see the Exercises below). More technically, the idea is that <code>f</code> preserves the "monoidal structure" given by the pairing constructor <code>(,)</code> and unit type <code>()</code>. This can be seen even more clearly if we rewrite the types of <code>unit</code> and <code>(**)</code> as<br />
<haskell><br />
unit' :: () -> f ()<br />
(**') :: (f a, f b) -> f (a, b)<br />
</haskell><br />
<br />
Furthermore, to deserve the name "monoidal" (see the [[#Monoid|section on Monoids]]), instances of <code>Monoidal</code> ought to satisfy the following laws, which seem much more straightforward than the traditional <code>Applicative</code> laws:<br />
<br />
{{note|In this and the following laws, <code>≅</code> refers to <i>isomorphism</i> rather than equality. In particular we consider <code>(x,()) ≅ x ≅ ((),x)</code> and <code>((x,y),z) ≅ (x,(y,z))</code>.}}<br />
* Left identity{{noteref}}: <haskell>unit ** v ≅ v</haskell><br />
* Right identity: <haskell>u ** unit ≅ u</haskell><br />
* Associativity: <haskell>u ** (v ** w) ≅ (u ** v) ** w</haskell><br />
<br />
These turn out to be equivalent to the usual <code>Applicative</code> laws. In a category theory setting, one would also require a naturality law:<br />
<br />
{{note|Here <code>g *** h {{=}} \(x,y) -> (g x, h y)</code>. See [[#Arrow|Arrows]].}}<br />
* Naturality: <haskell>fmap (g *** h) (u ** v) = fmap g u ** fmap h v</haskell><br />
<br />
but in the context of Haskell, this is a free theorem.<br />
<br />
Much of this section was taken from [http://blog.ezyang.com/2012/08/applicative-functors/ a blog post by Edward Z. Yang]; see his actual post for a bit more information.<br />
<br />
{{Exercises|<br />
# Implement <code>pure</code> and <code>(<*>)</code> in terms of <code>unit</code> and <code>(**)</code>, and vice versa.<br />
# Are there any <code>Applicative</code> instances for which there are also functions <code>f () -> ()</code> and <code>f (a,b) -> (f a, f b)</code>, satisfying some "reasonable" laws?<br />
# (Tricky) Prove that given your implementations from the first exercise, the usual <code>Applicative</code> laws and the <code>Monoidal</code> laws stated above are equivalent.<br />
}}<br />
<br />
==Further reading==<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://web.archive.org/web/20090416111947/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 />
Gershom Bazerman's [http://comonad.com/reader/2012/abstracting-with-applicatives/ post] contains many insights into applicatives.<br />
<br />
The <code>ApplicativeDo</code> extension is described in [https://ghc.haskell.org/trac/ghc/wiki/ApplicativeDo this wiki page], and in more detail in [http://doi.org/10.1145/2976002.2976007 this Haskell Symposium paper].<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. (As of GHC 8, <code>do</code>-notation can be used with <code>Applicative</code> as well, but the notation is still fundamentally related to monads.)<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 />
As of GHC 7.10, [{{HackageDocs|base|Prelude}}#t:Monad <code>Monad</code>] is defined as:<br />
<br />
<haskell><br />
class Applicative m => 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 />
(Prior to GHC 7.10, <code>Applicative</code> was not a superclass of <code>Monad</code>, for historical reasons.)<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 [{{HackageDocs|base|Control-Monad}} <code>Control.Monad</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.) For historical reasons, we still have both names, but they should always denote the same value (although this cannot be enforced). Likewise, <code>(>>)</code> should be the same as <code>(*>)</code> from <code>Applicative</code>. It is possible that <code>return</code> and <code>(>>)</code> may eventually be removed from the <code>Monad</code> class: see the [https://ghc.haskell.org/trac/ghc/wiki/Proposal/MonadOfNoReturn Monad of No Return proposal].<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''.<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 :: a -> Maybe a<br />
return = Just<br />
<br />
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b<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, one can recursively construct ''infinite'' grammars, and hence <code>Applicative</code> (together with <code>Alternative</code>) is enough to parse any context-sensitive language with a finite alphabet. See [http://byorgey.wordpress.com/2012/01/05/parsing-context-sensitive-languages-with-applicative/ Parsing context-sensitive languages with Applicative].}}<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 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 canonical definition of monads in category theory is 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 [{{HackageDocs|base|Control-Monad}} <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 />
* <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 a consequence of the fact that the <code>Monad</code> type class did not require a <code>Functor</code> instance until recently, even though mathematically speaking, every monad is a functor. If you are using GHC 7.10 or newer, you should avoid using <code>liftM</code> and just use <code>fmap</code> instead.<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> (see the exercise at the end of the Utility Functions section for Applicative). Note that the actual type of <code>sequence</code> is more general, and works over any <code>Traversable</code> rather than just lists; see the [[#Traversable|section on <code>Traversable</code>]].<br />
<br />
* <code>replicateM :: Monad m => Int -> m a -> m [a]</code> is simply a combination of [{{HackageDocs|base|Prelude}}#v:replicate <code>replicate</code>] and <code>sequence</code>.<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. Again, these functions actually work over any <code>Traversable</code>, not just lists, and they can also be defined in terms of <code>Applicative</code>, not <code>Monad</code>: the analogue of <code>mapM</code> for <code>Applicative</code> is called <code>traverse</code>.<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 />
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 />
</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.<br />
<br />
{{note|I like to pronounce this operator “fish”.}}<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}}.<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 />
{{Exercises|<br />
# Given the definition <code>g >{{=}}> h {{=}} \x -> g x >>{{=}} h</code>, prove the equivalence of the above laws and the usual monad laws.<br />
}}<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> is 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://www.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 />
Sometimes, the full power of <code>Monad</code> is not needed to desugar <code>do</code>-notation. For example,<br />
<br />
<haskell><br />
do x <- foo1<br />
y <- foo2<br />
z <- foo3<br />
return (g x y z)<br />
</haskell><br />
<br />
would normally be desugared to <code>foo1 >>= \x -> foo2 >>= \y -> foo3 >>= \z -> return (g x y z)</code>, but this is equivalent to <code>g <$> foo1 <*> foo2 <*> foo3</code>. With the <code>ApplicativeDo</code> extension enabled (as of GHC 8.0), GHC tries hard to desugar <code>do</code>-blocks using <code>Applicative</code> operations wherever possible. This can sometimes lead to efficiency gains, even for types which also have <code>Monad</code> instances, since in general <code>Applicative</code> computations may be run in parallel, whereas monadic ones may not. For example, consider<br />
<br />
<haskell><br />
g :: Int -> Int -> M Int<br />
<br />
-- These could be expensive<br />
bar, baz :: M Int<br />
<br />
foo :: M Int<br />
foo = do<br />
x <- bar<br />
y <- baz<br />
g x y<br />
</haskell><br />
<br />
<code>foo</code> definitely depends on the <code>Monad</code> instance of <code>M</code>, since the effects generated by the whole computation may depend (via <code>g</code>) on the <code>Int</code> outputs of <code>bar</code> and <code>baz</code>. Nonetheless, with <code>ApplicativeDo</code> enabled, <code>foo</code> can be desugared as<br />
<haskell><br />
join (g <$> bar <*> baz)<br />
</haskell><br />
which may allow <code>bar</code> and <code>baz</code> to be computed in parallel, since they at least do not depend on each other.<br />
<br />
The <code>ApplicativeDo</code> extension is described in [https://ghc.haskell.org/trac/ghc/wiki/ApplicativeDo this wiki page], and in more detail in [http://doi.org/10.1145/2976002.2976007 this Haskell Symposium paper].<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://www.haskell.org/haskellwiki/Monads_as_Containers Monads as containers],<br />
[http://en.wikibooks.org/w/index.php?title=Haskell/Understanding_monads 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://www.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://www.haskell.org/haskellwiki/Monads_as_Containers Monads as containers] and [http://www.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], Tim Newsham’s [http://www.thenewsh.com/~newsham/haskell/monad.html What’s a Monad?], and Chris Smith's excellent article [http://cdsmith.wordpress.com/2012/04/18/why-do-monads-matter/ Why Do Monads Matter?]. 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 />
For help constructing monads from scratch, and for obtaining a "deep embedding" of monad operations suitable for use in, say, compiling a domain-specific language, see [http://projects.haskell.org/operational Apfelmus's operational package].<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 [https://bentnib.org/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’ 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>. Jonathan Hill and Keith Clarke have [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.53.6497 an early paper explaining the connection between monads as they arise in category theory and as used in functional programming]. There is also a [http://okmij.org/ftp/Computation/IO-monad-history.html web page by Oleg Kiselyov] explaining the history of the IO monad.<br />
<br />
Links to many more research papers related to monads can be found under [[Research papers/Monads and arrows]].<br />
<br />
=MonadFail=<br />
<br />
Some monads support a notion of ''failure'', without necessarily supporting the notion of ''recovery'' suggested by <code>MonadPlus</code>, and possibly including a primitive error reporting mechanism. This notion is expressed by the relatively unprincipled <code>MonadFail</code>. When the <code>MonadFailDesugaring</code> language extension is enabled, the <code>fail</code> method from <code>MonadFail</code> is used for pattern match failure in <code>do</code> bindings rather than the traditional <code>fail</code> method of the <code>Monad</code> class. This language change is being implemented because there are many monads, such as <code>Reader</code>, <code>State</code>, <code>Writer</code>, <code>RWST</code>, and <code>Cont</code> that simply do not support a legitimate <code>fail</code> method.<br />
<br />
See the [https://prime.haskell.org/wiki/Libraries/Proposals/MonadFail MonadFail proposal] for more information.<br />
<br />
==Definition==<br />
<br />
<haskell><br />
class Monad m => MonadFail m where<br />
fail :: String -> m a<br />
</haskell><br />
<br />
==Law==<br />
<br />
<haskell><br />
fail s >>= m = fail s<br />
</haskell><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, when you do not actually want any extra capabilities.<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 inside the stack you get, and the effects of inner monads "have precedence" over the effects of outer ones. 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 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.<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]); see also the [[#Traversable|section on Traversable]].<br />
<br />
For a much more in-depth discussion and analysis of the failure of monads to be closed under composition, see [http://stackoverflow.com/questions/13034229/concrete-example-showing-that-monads-are-not-closed-under-composition-with-proo?lq=1 this question on StackOverflow].<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’ 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 />
See [http://archive.fo/wxSkj Edward Kmett's mailing list message] for a description of the history and relationships among monad transformer packages (<code>mtl</code>, <code>transformers</code>, <code>monads-fd</code>, <code>monads-tf</code>).<br />
<br />
There are two excellent references on monad transformers. Martin Grabmüller’s [https://github.com/mgrabmueller/TransformersStepByStep/blob/master/Transformers.lhs 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://www.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. For a more recent alternative, see Kiselyov et al's [http://okmij.org/ftp/Haskell/extensible/exteff.pdf Extensible Effects: An Alternative to Monad Transformers].<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>-XRecursiveDo</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/System-IO.html#fixIO instance for <code>IO</code>] is particularly amusing: it creates a new (empty) <code>MVar</code>, 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>MVar</code> to compute a new value, which it then writes back into the <code>MVar</code>. It almost seems, spookily, that <code>mfix</code> is sending a value back in time to itself through the <code>MVar</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 />
==<code>mdo</code> syntax==<br />
<br />
The example at the start of this section can also be written<br />
<br />
<haskell><br />
mdo { x <- foo<br />
; y <- baz<br />
; z <- bar<br />
; bob<br />
; w <- frob<br />
}<br />
</haskell><br />
<br />
which will be translated into the original example (assuming that, say, <code>bar</code> and <code>bob</code> refer to <code>y</code>. The difference is that <code>mdo</code> will analyze the code in order to find minimal recursive blocks, which will be placed in <code>rec</code> blocks, whereas <code>rec</code> blocks desugar directly into calls to <code>mfix</code> without any further analysis.<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>MonadFix</code> used to be called <code>MonadRec</code>.) You can also read the [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-RecursiveDo GHC user manual section on recursive do-notation].<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 />
==Definition==<br />
<br />
As of version 4.9 of the <code>base</code> package (which comes with GHC 8.0), semigroups are defined in the <code>Data.Semigroup</code> module. (If you are working with a previous version of base, or want to write a library that supports previous versions of base, you can use the <code>semigroups</code> package.)<br />
<br />
The definition of the <code>Semigroup</code> type class ([https://hackage.haskell.org/package/base-4.9.0.0/docs/Data-Semigroup.html haddock]) is as follows:<br />
<br />
<haskell><br />
class Semigroup a where<br />
(<>) :: a -> a -> a<br />
<br />
sconcat :: NonEmpty a -> a<br />
sconcat (a :| as) = go a as where<br />
go b (c:cs) = b <> go c cs<br />
go b [] = b<br />
<br />
stimes :: Integral b => b -> a -> a<br />
stimes = ...<br />
</haskell><br />
<br />
The really important method is <code>(<>)</code>, representing the associative binary operation. The other two methods have default implementations in terms of <code>(<>)</code>, and are included in the type class in case some instances can give more efficient implementations than the default.<br />
<br />
<code>sconcat</code> reduces a nonempty list using <code>(<>)</code>. For most instances, this is the same as <code>foldr1 (<>)</code>, but it can be constant-time for idempotent semigroups.<br />
<br />
<code>stimes n</code> is equivalent to (but sometimes considerably more efficient than) <code>sconcat . replicate n</code>. Its default definition uses multiplication by doubling (also known as exponentiation by squaring). For many semigroups, this is an important optimization; for some, such as lists, it is terrible and must be overridden.<br />
<br />
See the [https://hackage.haskell.org/package/base-4.9.0.0/docs/Data-Semigroup.html haddock documentation] for more information on <code>sconcat</code> and <code>stimes</code>.<br />
<br />
==Laws==<br />
<br />
The only law is that <code>(<>)</code> must be associative:<br />
<br />
<haskell><br />
(x <> y) <> z = x <> (y <> z)<br />
</haskell><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>; [{{HackageDocs|base|Data-Monoid}} 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://archive.fo/hkTOb Comments from OCaml Hacker Brian Hurt] on the Haskell-cafe mailing list). The situation is made somewhat better by <code>(<>)</code>, which is provided as an alias for <code>mappend</code>.<br />
<br />
Note that the <code>(<>)</code> alias for <code>mappend</code> conflicts with the <code>Semigroup</code> method of the same name. For this reason, <code>Data.Semigroup</code> re-exports much of <code>Data.Monoid</code>; to use semigroups and monoids together, just import <code>Data.Semigroup</code>, and make sure all your types have both <code>Semigroup</code> and <code>Monoid</code> instances (and that <code>(<>) = mappend</code>).<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 on <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://archive.fo/dUbHK 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 :: Monoid e => a -> (e,a)<br />
pure x = (mempty, x)<br />
<br />
(<*>) :: Monoid e => (e,a -> b) -> (e,a) -> (e,b)<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 />
==Further reading==<br />
<br />
Monoids got a fair bit of attention in 2009, when<br />
[http://blog.enfranchisedmind.com/2009/01/random-thoughts-on-haskell/ a blog post by Brian Hurt]<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://archive.fo/hkTOb 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’ [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/wikiupload/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], [http://byorgey.wordpress.com/2008/04/17/collecting-unstructured-information-with-the-monoid-of-partial-knowledge/ collecting unstructured information], [http://izbicki.me/blog/gausian-distributions-are-monoids combining probability distributions], and a brilliant series of posts by Chung-Chieh Shan and Dylan Thurston using <code>Monoid</code>s to [http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers1/ elegantly solve a difficult combinatorial puzzle] (followed by [http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers2/ part 2], [http://conway.rutgers.edu/~ccshan/wiki/blog/posts/WordNumbers3/ part 3], [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 />
=Failure and choice: Alternative, MonadPlus, ArrowPlus=<br />
<br />
Several classes (<code>Applicative</code>, <code>Monad</code>, <code>Arrow</code>) have "monoidal" subclasses, intended to model computations that support "failure" and "choice" (in some appropriate sense).<br />
<br />
==Definition==<br />
<br />
The <code>Alternative</code> type class ([{{HackageDocs|base|Control-Applicative}}#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 />
<br />
some :: f a -> f [a]<br />
many :: f a -> f [a]<br />
</haskell><br />
<br />
The basic intuition is that <code>empty</code> represents some sort of "failure", and <code>(<|>)</code> represents a choice between alternatives. (However, this intuition does not fully capture the nuance possible; see the section on Laws below.) Of course, <code>(<|>)</code> should be associative and <code>empty</code> should be the identity element for it.<br />
Instances of <code>Alternative</code> must implement <code>empty</code> and <code>(&lt;|&gt;)</code>; <code>some</code> and <code>many</code> have default implementations but are included in the class since specialized implementations may be more efficient than the default.<br />
<br />
The default definitions of <code>some</code> and <code>many</code> are essentially given by<br />
<br />
<haskell><br />
some v = (:) <$> v <*> many v<br />
many v = some v <|> pure []<br />
</haskell><br />
<br />
(though for some reason, in actual fact they are not defined via mutual recursion). The intuition is that both keep running <code>v</code>, collecting its results into a list, until it fails; <code>some v</code> requires <code>v</code> to succeed at least once, whereas <code>many v</code> does not require it to succeed at all. That is, <code>many</code> represents 0 or more repetitions of <code>v</code>, whereas <code>some</code> represents 1 or more repetitions. Note that <code>some</code> and <code>many</code> do not make sense for all instances of <code>Alternative</code>; they are discussed further below.<br />
<br />
Likewise, <code>MonadPlus</code> ([{{HackageDocs|base|Control-Monad}}#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 />
Finally, <code>ArrowZero</code> and <code>ArrowPlus</code> ([{{HackageDocs|base|Control-Arrow}}#t:ArrowZero haddock])<br />
represent <code>Arrow</code>s ([[#Arrow|see below]]) with a<br />
monoid structure:<br />
<br />
<haskell><br />
class Arrow arr => ArrowZero arr where<br />
zeroArrow :: b `arr` c<br />
<br />
class ArrowZero arr => ArrowPlus arr where<br />
(<+>) :: (b `arr` c) -> (b `arr` c) -> (b `arr` c)<br />
</haskell><br />
<br />
==Instances==<br />
<br />
Although this document typically discusses laws before presenting example instances, for <code>Alternative</code> and friends it is worth doing things the other way around, because there is some controversy over the laws and it helps to have some concrete examples in mind when discussing them. We mostly focus on <code>Alternative</code> in this section and the next; now that <code>Applicative</code> is a superclass of <code>Monad</code>, there is little reason to use <code>MonadPlus</code> any longer, and <code>ArrowPlus</code> is rather obscure.<br />
<br />
* <code>Maybe</code> is an instance of <code>Alternative</code>, where <code>empty</code> is <code>Nothing</code> and the choice operator <code>(<|>)</code> results in its first argument when it is <code>Just</code>, and otherwise results in its second argument. Hence folding over a list of <code>Maybe</code> with <code>(<|>)</code> (which can be done with <code>asum</code> from <code>Data.Foldable</code>) results in the first non-<code>Nothing</code> value in the list (or <code>Nothing</code> if there are none).<br />
<br />
* <code>[]</code> is an instance, with <code>empty</code> given by the empty list, and <code>(<|>)</code> equal to <code>(++)</code>. It is worth pointing out that this is identical to the <code>Monoid</code> instance for <code>[a]</code>, whereas the <code>Alternative</code> and <code>Monoid</code> instances for <code>Maybe</code> are different: the <code>Monoid</code> instance for <code>Maybe a</code> requires a <code>Monoid</code> instance for <code>a</code>, and monoidally combines the contained values when presented with two <code>Just</code>s.<br />
<br />
Let's think about the behavior of <code>some</code> and <code>many</code> for <code>Maybe</code> and <code>[]</code>. For <code>Maybe</code>, we have <code>some Nothing = (:) <$> Nothing <*> many Nothing = Nothing <*> many Nothing = Nothing</code>. Hence we also have <code>many Nothing = some Nothing <|> pure [] = Nothing <|> pure [] = pure [] = Just []</code>. Boring. But what about applying <code>some</code> and <code>many</code> to <code>Just</code>? In fact, <code>some (Just a)</code> and <code>many (Just a)</code> are both bottom! The problem is that since <code>Just a</code> is always "successful", the recursion will never terminate. In theory the result "should be" the infinite list <code>[a,a,a,...]</code> but it cannot even start producing any elements of this list, because there is no way for the <code>(<*>)</code> operator to yield any output until it knows that the result of the call to <code>many</code> will be <code>Just</code>.<br />
<br />
You can work out the behavior for <code>[]</code> yourself, but it ends up being quite similar: <code>some</code> and <code>many</code> yield boring results when applied to the empty list, and yield bottom when applied to any non-empty list.<br />
<br />
In the end, <code>some</code> and <code>many</code> really only make sense when used with some sort of "stateful" <code>Applicative</code> instance, for which an action <code>v</code>, when run multiple times, can succeed some finite number of times and then fail. For example, parsers have this behavior, and indeed, parsers were the original motivating example for the <code>some</code> and <code>many</code> methods; more on this below.<br />
<br />
* Since GHC 8.0 (that is, <code>base-4.9</code>), there is an instance of <code>Alternative</code> for <code>IO</code>. <code>empty</code> throws an I/O exception, and <code>(<|>)</code> works by first running its left-hand argument; if the left-hand argument throws an I/O exception, <code>(<|>)</code> catches the exception and then calls its second argument. (Note that other types of exceptions are not caught.) There are other, much better ways to handle I/O errors, but this is a quick and dirty way that may work for simple, one-off programs, such as expressions typed at the GHCi prompt. For example, if you want to read the contents of a file but use some default contents in case the file does not exist, you can just write <code>readFile "somefile.txt" <|> return "default file contents"</code>.<br />
<br />
* <code>Concurrently</code> from the <code>async</code> package has an <code>Alternative</code> instance, for which <code>c1 <|> c2</code> races <code>c1</code> and <code>c2</code> in parallel, and returns the result of whichever finishes first. <code>empty</code> corresponds to the action that runs forever without returning a value.<br />
<br />
* Practically any parser type (e.g. from <code>parsec</code>, <code>megaparsec</code>, <code>trifecta</code>, ...) has an <code>Alternative</code> instance, where <code>empty</code> is an unconditional parse failure, and <code>(<|>)</code> is left-biased choice. That is, <code>p1 <|> p2</code> first tries parsing with <code>p1</code>, and if <code>p1</code> fails then it tries <code>p2</code> instead.<br />
<br />
<code>some</code> and <code>many</code> work particularly well with parser types having an <code>Applicative</code> instance: if <code>p</code> is a parser, then <code>some p</code> parses one or more consecutive occurrences of <code>p</code> (i.e. it will parse as many occurrences of <code>p</code> as possible and then stop), and <code>many p</code> parses zero or more occurrences.<br />
<br />
==Laws==<br />
<br />
Of course, instances of <code>Alternative</code> should satisfy the monoid laws<br />
<br />
<haskell><br />
empty <|> x = x<br />
x <|> empty = x<br />
(x <|> y) <|> z = x <|> (y <|> z)<br />
</haskell><br />
<br />
The documentation for <code>some</code> and <code>many</code> states that they should be the "least solution" (i.e. least in the definedness partial order) to their characterizing, mutually recursive default definitions. However, [https://www.reddit.com/r/haskell/comments/2j8bvl/laws_of_some_and_many/ this is controversial], and probably wasn't really thought out very carefully.<br />
<br />
Since <code>Alternative</code> is a subclass of <code>Applicative</code>, a natural question is, "how should <code>empty</code> and <code>(<|>)</code> interact with <code>(<*>)</code> and <code>pure</code>?"<br />
<br />
Almost everyone agrees on the ''left zero'' law (though see the discussion of the ''right zero'' law below):<br />
<br />
<haskell><br />
empty <*> f = empty<br />
</haskell><br />
<br />
After this is where it starts to get a bit hairy though. It turns out there are several other laws one might imagine adding, and different instances satisfy different laws.<br />
<br />
* ''Right Zero'':<p>Another obvious law would be <haskell>f <*> empty = empty</haskell></p><p>This law is satisfied by most instances; however, it is not satisfied by <code>IO</code>. Once the effects in <code>f</code> have been executed, there is no way to roll them back if we later encounter an exception. Now consider the <code>Backwards</code> applicative transformer from the <code>transformers</code> package. If <code>f</code> is <code>Applicative</code>, then so is <code>Backwards f</code>; it works the same way but performs the actions of the arguments to <code>(<*>)</code> in the reverse order. There is also an instance <code>Alternative f => Alternative (Backwards f)</code>. If some <code>f</code> (such as <code>IO</code>) satisfies ''left zero'' but not ''right zero'', then <code>Backwards f</code> satisfies ''right zero'' but not ''left zero''! So even the ''left zero'' law is suspect. The point is that given the existence of <code>Backwards</code> we cannot privilege one direction or the other.</p><br />
<br />
<br />
* ''Left Distribution'':<p><haskell>(a <|> b) <*> c = (a <*> c) <|> (b <*> c)</haskell></p><p>This distributivity law is satisfied by <code>[]</code> and <code>Maybe</code>, as you may verify. However, it is ''not'' satisfied by <code>IO</code> or most parsers. The reason is that <code>a</code> and <code>b</code> can have effects which influence execution of <code>c</code>, and the left-hand side may end up failing where the right-hand side succeeds.</p><p>For example, consider <code>IO</code>, and suppose that <code>a</code> always executes successfully, but <code>c</code> throws an I/O exception after <code>a</code> has run. Concretely, say, <code>a</code> might ensure that a certain file does not exist (deleting it if it does exist or doing nothing if it does not), and then <code>c</code> tries to read that file. In that case <code>(a <|> b) <*> c</code> will first delete the file, ignoring <code>b</code> since <code>a</code> is successful, and then throw an exception when <code>c</code> tries to read the file. On the other hand, <code>b</code> might ensure that the same file in question ''does'' exist. In that case <code>(a <*> c) <|> (b <*> c)</code> would succeed: after <code>(a <*> c)</code> throws an exception, it would be caught by <code>(<|>)</code>, and then <code>(b <*> c)</code> would be tried.</p><p>This law does not hold for parsers for a similar reason: <code>(a <|> b) <*> c</code> has to "commit" to parsing with <code>a</code> or <code>b</code> before running <code>c</code>, whereas <code>(a <*> c) <|> (b <*> c)</code> allows backtracking if <code>a <*> c</code> fails. In the particular case that <code>a</code> succeeds but <code>c</code> fails after <code>a</code> but not after <code>b</code>, these may give different results. For example, suppose <code>a</code> and <code>c</code> both expect to see two asterisks, but <code>b</code> expects to see only one. If there are only three asterisks in the input, <code>b <*> c</code> will be successful whereas <code>a <*> c</code> will not.</p><br />
<br />
* ''Right Distribution'':<p><haskell>a <*> (b <|> c) = (a <*> b) <|> (a <*> c)</haskell></p><p>This law is not satisfied by very many instances, but it's still worth discussing. In particular the law is still satisfied by <code>Maybe</code>. However, it is ''not'' satisfied by, for example, lists. The problem is that the results come out in a different order. For example, suppose <code>a = [(+1), (*10)]</code>, <code>b = [2]</code>, and <code>c = [3]</code>. Then the left-hand side yields <code>[3,4,20,30]</code>, whereas the right-hand side is <code>[3,20,4,30]</code>.</p><p><code>IO</code> does not satisfy it either, since, for example, <code>a</code> may succeed only the ''second'' time it is executed. Parsers, on the other hand, may or may not satisfy this law, depending on how they handle backtracking. Parsers for which <code>(<|>)</code> by itself does full backtracking will satisfy the law; but for many parser combinator libraries this is not the case, for efficiency reasons. For example, parsec fails this law: if <code>a</code> succeeds while consuming some input, and afterwards <code>b</code> fails without consuming any input, then the left-hand side may succeed while the right-hand side fails: after <code>(a <*> b)</code> fails, the right-hand side tries to re-run <code>a</code> without backtracking over the input the original <code>a</code> consumed.</p><br />
<br />
* ''Left Catch'':<p><haskell>(pure a) <|> x = pure a</haskell></p><p>Intuitively, this law states that <code>pure</code> should always represent a "successful" computation. It is satisfied by <code>Maybe</code>, <code>IO</code>, and parsers. However, it is not satisfied by lists, since lists collect ''all'' possible results: it corresponds to <code>[a] ++ x == [a]</code> which is obviously false.</p><br />
<br />
This, then, is the situation: we have a lot of instances of <code>Alternative</code> (and <code>MonadPlus</code>), with each instance satisfying some ''subset'' of these laws. Moreover, it's not always the ''same'' subset, so there is no obvious "default" set of laws to choose. For now at least, we just have to live with the situation. When using a particular instance of <code>Alternative</code> or <code>MonadPlus</code>, it's worth thinking carefully about which laws it satisfies.<br />
<br />
==Utility functions==<br />
<br />
There are a few <code>Alternative</code>-specific utility functions worth mentioning:<br />
<br />
* <haskell>guard :: Alternative f => Bool -> f ()</haskell> checks the given condition, and evaluates to <code>pure ()</code> if the condition holds, and <code>empty</code> if not. This can be used to create a conditional failure point in the middle of a computation, where the computation only proceeds if a certain condition holds.<br />
<br />
* <haskell>optional :: Alternative f => f a -> f (Maybe a)</haskell> reifies potential failure into the <code>Maybe</code> type: that is, <code>optional x</code> is a computation which always succeeds, returning <code>Nothing</code> if <code>x</code> fails and <code>Just a</code> if <code>x</code> successfully results in <code>a</code>. It is useful, for example, in the context of parsers, where it corresponds to a production which can occur zero or one times.<br />
<br />
==Further reading==<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 />
A great introduction to the <code>MonadPlus</code> type class, with interesting examples 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 />
Another interesting use of <code>MonadPlus</code> can be found in Christiansen et al, [http://www-ps.informatik.uni-kiel.de/~sad/icfp2016-preprint.pdf All Sorts of Permutations], from ICFP 2016.<br />
<br />
The [https://hackage.haskell.org/package/logict logict package] defines a type with prominent <code>Alternative</code> and <code>MonadPlus</code> instances that can be used to efficiently enumerate possibilities subject to constraints, ''i.e.'' logic programming; it's like the list monad on steroids.<br />
<br />
=Foldable=<br />
<br />
The <code>Foldable</code> class, defined in the <code>Data.Foldable</code><br />
module ([{{HackageDocs|base|Data-Foldable}} 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 />
foldr :: (a -> b -> b) -> b -> t a -> b<br />
foldr' :: (a -> b -> b) -> b -> t a -> b<br />
foldl :: (b -> a -> b) -> b -> t a -> b<br />
foldl' :: (b -> a -> b) -> b -> t a -> b<br />
foldr1 :: (a -> a -> a) -> t a -> a<br />
foldl1 :: (a -> a -> a) -> t a -> a<br />
toList :: t a -> [a]<br />
null :: t a -> Bool<br />
length :: t a -> Int<br />
elem :: Eq a => a -> t a -> Bool<br />
maximum :: Ord a => t a -> a<br />
minimum :: Ord a => t a -> a<br />
sum :: Num a => t a -> a<br />
product :: Num 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 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 :: Monoid m => (a -> m) -> [a] -> m<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 :: Monoid m => (a -> m) -> Tree a -> m<br />
foldMap f Empty = mempty<br />
foldMap f (Leaf x) = f x<br />
foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r<br />
</haskell><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 />
{{Exercises|<br />
# Implement <code>fold</code> in terms of <code>foldMap</code>.<br />
# What would you need in order to implement <code>foldMap</code> in terms of <code>fold</code>?<br />
# Implement <code>foldMap</code> in terms of <code>foldr</code>.<br />
# Implement <code>foldr</code> in terms of <code>foldMap</code> (hint: use the <code>Endo</code> monoid).<br />
# What is the type of <code>foldMap . foldMap</code>? Or <code>foldMap . foldMap . foldMap</code>, etc.? What do they do?<br />
}}<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. These used to be generalized versions of <code>Prelude</code> functions of the<br />
same name that only worked on lists; but [https://wiki.haskell.org/Foldable_Traversable_In_Prelude as of GHC 7.10], the generalized versions themselves are now exported from the Prelude: for example, <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>. For example, before GHC 7.10, <code>length</code> used to have type <code>length :: [a] -> Int</code>; now it has type <code>Foldable t => t a -> Int</code> (and is in fact the same as the <code>containerSize</code> function shown above).<br />
<br />
The important function <code>toList</code> is also provided, which turns any <code>Foldable</code> structure into a list of its elements in left-right order; it works by folding with the list monoid.<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 <code>Monoid</code>, but we can make <code>m ()</code> into a <code>Monoid</code> for any such <code>m</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 [{{HackageDocs|base|Data-Foldable}} <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 />
{{Exercises|<br />
# Implement <code>toList :: Foldable f {{=}}> f a -> [a]</code> in terms of either <code>foldr</code> or <code>foldMap</code>.<br />
# Show how one could implement the generic version of <code>foldr</code> in terms of <code>toList</code>, assuming we had only the list-specific <code>foldr :: (a -> b -> b) -> b -> [a] -> b</code>.<br />
# Pick some of the following functions to implement: <code>concat</code>, <code>concatMap</code>, <code>and</code>, <code>or</code>, <code>any</code>, <code>all</code>, <code>sum</code>, <code>product</code>, <code>maximum</code>(<code>By</code>), <code>minimum</code>(<code>By</code>), <code>elem</code>, <code>notElem</code>, and <code>find</code>. Figure out how they generalize to <code>Foldable</code> and come up with elegant implementations using <code>fold</code> or <code>foldMap</code> along with appropriate <code>Monoid</code> instances.<br />
}}<br />
<br />
==Utility functions==<br />
<br />
* <code>asum :: (Alternative f, Foldable t) => t (f a) -> f a</code> takes a container full of computations and combines them using <code>(<|>)</code>.<br />
<br />
* <code>sequenceA_ :: (Applicative f, Foldable t) => t (f a) -> f ()</code> takes a container full of computations and runs them in sequence, discarding the results (that is, they are used only for their effects). Since the results are discarded, the container only needs to be <code>Foldable</code>. (Compare with <code>sequenceA :: (Applicative f, Traversable t) => t (f a) -> f (t a)</code>, which requires a stronger <code>Traversable</code> constraint in order to be able to reconstruct a container of results having the same shape as the original container.)<br />
<br />
* <code>traverse_ :: (Applicative f, Foldable t) => (a -> f b) -> t a -> f ()</code> applies the given function to each element in a foldable container and sequences the effects (but discards the results).<br />
<br />
* <code>for_</code> is the same as <code>traverse_</code> but with its arguments flipped. This is the moral equivalent of a "foreach" loop in an imperative language.<br />
<br />
* For historical reasons, there are also variants of all the above with overly-restrictive <code>Monad</code>(-like) constraints: <code>msum</code> is the same as <code>asum</code> specialized to <code>MonadPlus</code>, and <code>sequence_</code>, <code>mapM_</code>, and <code>forM_</code> respectively are <code>Monad</code> specializations of <code>sequenceA_</code>, <code>traverse_</code>, and <code>for_</code>.<br />
<br />
{{Exercises|<br />
# Implement <code>traverse_</code> in terms of <code>sequenceA_</code> and vice versa. One of these will need an extra constraint. What is it?<br />
}}<br />
<br />
==Foldable actually isn't==<br />
<br />
The generic term "fold" is often used to refer to the more technical concept of [[Catamorphisms|catamorphism]]. Intuitively, given a way to summarize "one level of structure" (where recursive subterms have already been replaced with their summaries), a catamorphism can summarize an entire recursive structure. It is important to realize that <code>Foldable</code> does <i>not</i> correspond to catamorphisms, but to something weaker. In particular, <code>Foldable</code> allows observing only the left-right traversal order of elements within a structure, not the actual structure itself. Put another way, every use of <code>Foldable</code> can be expressed in terms of <code>toList</code>. For example, <code>fold</code> itself is equivalent to <code>mconcat . toList</code>.<br />
<br />
This is sufficient for many tasks, but not all. For example, consider trying to compute the depth of a <code>Tree</code>: try as we might, there is no way to implement it using <code>Foldable</code>. However, it <i>can</i> be implemented as a catamorphism.<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 />
For more on the relationship between <code>fold</code>, <code>foldMap</code>, and <code>foldr</code>, see [https://byorgey.wordpress.com/2012/11/05/foldr-is-made-of-monoids/ foldr is made of monoids].<br />
<br />
There was [http://tojans.me/blog/2015/10/13/foldable-for-non-haskellers-haskells-controversial-ftp-proposal/ quite a bit of controversy] in the Haskell community about a [https://wiki.haskell.org/Foldable_Traversable_In_Prelude proposal to integrate <code>Foldable</code> (and <code>Traversable</code>) more tightly into the Prelude], known as the FTP. Some of the controversy centered around <code>Foldable</code> instances such as the one for <code>((,) a)</code>, which, together with generalized types for functions such as <code>length :: Foldable t => t a -> Int</code>, allow one to derive seemingly nonsensical results such as <code>length (2,3) = 1</code>. Here is a [https://www.youtube.com/watch?v=87re_yIQMDw humorous talk] poking fun at the situation.<br />
<br />
=Traversable=<br />
<br />
==Definition==<br />
<br />
The <code>Traversable</code> type class, defined in the <code>Data.Traversable</code><br />
module ([{{HackageDocs|base|Data-Traversable}} 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 <code>Foldable</code> <code>Functor</code>. To make a <code>Traversable</code> instance, it suffices to implement either <code>traverse</code> or<br />
<code>sequenceA</code>; the other methods all have default implementations in<br />
terms of these. Note that <code>mapM</code> and <code>sequence</code> only exist for historical reasons; especially now that <code>Applicative</code> is a superclass of <code>Monad</code>, they are nothing more than copies of <code>traverse</code> and <code>sequenceA</code>, respectively, but with more restrictive types.<br />
<br />
==Intuition==<br />
<br />
<br />
The key method of the <code>Traversable</code> class is <code>traverse</code>, which has the following type:<br />
<haskell><br />
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)<br />
</haskell><br />
This leads us to view <code>Traversable</code> as a generalization of <code>Functor</code>. <code>traverse</code> is an "effectful <code>fmap</code>": it allows us to map over a structure of type <code>t a</code>, applying a function to every element of type <code>a</code> in order to produce a new structure of type <code>t b</code>; but along the way the function may have some effects (captured by the applicative functor <code>f</code>).<br />
<br />
Alternatively, we may consider the <code>sequenceA</code> function. 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?<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’ paper] for more details.<br />
<br />
It turns out that given a <code>Functor</code> constraint on the type <code>t</code>, <code>traverse</code> and <code>sequenceA</code> are equivalent in power: either can be implemented in terms of the other.<br />
<br />
{{Exercises|<br />
# There are at least two natural ways to turn a tree of lists into a list of trees. What are they, and why?<br />
# Give a natural way to turn a list of trees into a tree of lists.<br />
# What is the type of <code>traverse . traverse</code>? What does it do?<br />
# Implement <code>traverse</code> in terms of <code>sequenceA</code>, and vice versa.<br />
}}<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 :: Applicative f => (a -> f b) -> Tree a -> f (Tree b) <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 :: (a -> b) -> Tree a -> Tree b<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 structurally 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>. This same pattern will hold 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.<br />
<br />
The standard libraries provide a number of <code>Traversable</code> instances,<br />
including instances for <code>[]</code>, <code>ZipList</code>, <code>Maybe</code>, <code>((,) e)</code>, <code>Sum</code>, <code>Product</code>, <code>Either e</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 />
{{Exercises|<br />
# Implement <code>fmap</code> and <code>foldMap</code> using only the <code>Traversable</code> methods. (Note that the <code>Traversable</code> module provides these implementations as <code>fmapDefault</code> and <code>foldMapDefault</code>.)<br />
# Implement <code>Traversable</code> instances for <code>[]</code>, <code>Maybe</code>, <code>((,) e)</code>, and <code>Either e</code>.<br />
# Explain why <code>Set</code> is <code>Foldable</code> but not <code>Traversable</code>.<br />
# Show that <code>Traversable</code> functors compose: that is, implement an instance for <code>Traversable (Compose f g)</code> given <code>Traversable</code> instances for <code>f</code> and <code>g</code>.<br />
}}<br />
<br />
==Laws==<br />
<br />
Any instance of <code>Traversable</code> must satisfy the following two laws, where <code>Identity</code> is the identity functor (as defined in the [http://hackage.haskell.org/packages/archive/transformers/latest/doc/html/Data-Functor-Identity.html <code>Data.Functor.Identity</code> module] from the <code>transformers</code> package), and <code>Compose</code> wraps the composition of two functors (as defined in [http://hackage.haskell.org/packages/archive/transformers/0.3.0.0/doc/html/Data-Functor-Compose.html <code>Data.Functor.Compose</code>]):<br />
<br />
# <code>traverse Identity = Identity</code><br />
# <code>traverse (Compose . fmap g . f) = Compose . fmap (traverse g) . traverse f</code><br />
<br />
The first law essentially says that traversals cannot make up arbitrary effects. The second law explains how doing two traversals in sequence can be collapsed to a single traversal.<br />
<br />
Additionally, suppose <code>eta</code> is an "<code>Applicative</code> morphism", that is,<br />
<haskell><br />
eta :: forall a f g. (Applicative f, Applicative g) => f a -> g a<br />
</haskell><br />
and <code>eta</code> preserves the <code>Applicative</code> operations: <code>eta (pure x) = pure x</code> and <code>eta (x <*> y) = eta x <*> eta y</code>. Then, by parametricity, any instance of <code>Traversable</code> satisfying the above two laws will also satisfy <code>eta . traverse f = traverse (eta . f)</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 />
<code>Traversable</code> forms a core component of Edward Kmett's [http://hackage.haskell.org/package/lens lens library]. Watching [https://vimeo.com/56063074 Edward's talk on the subject] is a highly recommended way to gain better insight into <code>Traversable</code>, <code>Foldable</code>, <code>Applicative</code>, and many other things besides.<br />
<br />
For references on the <code>Traversable</code> laws, see Russell O'Connor's [http://archive.fo/7XcVE mailing list post] (and subsequent thread), and [https://arxiv.org/abs/1202.2919 this paper by Jaskelioff and Rypacek] for a more in-depth discussion. Daniel Mlot also has [http://duplode.github.io/posts/traversable-a-remix.html this very nice blog post] explaining how <code>Traversable</code> arises by considering a variant on the usual Kleisli category of a monad, which also sheds light on where the <code>Traversable</code> laws come from.<br />
<br />
[http://elvishjerricco.github.io/2017/03/23/applicative-sorting.html This blog post by Will Fancher] shows how to use <code>Traversable</code> along with a clever choice of <code>Applicative</code> to efficiently sort any <code>Traversable</code> container.<br />
<br />
=Bifunctor=<br />
<br />
Recall that a <code>Functor</code> is a type of kind <code>* -> *</code> where one can "map" a function over the type parameter. <code>(Either e)</code> is a <code>Functor</code> (with <code>fmap :: (a -> b) -> Either e a -> Either e b</code>), as is <code>((,) e)</code>. But there is something oddly asymmetric about these two examples: in principle, there is no reason we can't map over the <code>e</code> instead of the <code>a</code>, for example, like so: <code>lmap :: (e -> e') -> Either e a -> Either e' a</code>. This observation leads directly to the definition of <code>Bifunctor</code>, a class for types of kind <code>* -> * -> *</code> where one can functorially map over ''both'' type parameters.<br />
<br />
==Definition==<br />
<br />
Here is the type class declaration for <code>Bifunctor</code>, defined<br />
in <code>Data.Bifunctor</code> (since <code>base-4.8</code>, which came with GHC 7.10):<br />
<br />
<haskell><br />
class Bifunctor p where<br />
bimap :: (a -> b) -> (c -> d) -> p a c -> p b d<br />
<br />
first :: (a -> b) -> p a c -> p b c<br />
second :: (b -> c) -> p a b -> p a c<br />
</haskell><br />
<br />
We can infer from the fact that <code>p</code> is applied to two type<br />
arguments that its kind must be <code>* -> * -> *</code>. The most<br />
fundamental method of the <code>Bifunctor</code> class is<br />
<code>bimap</code>, which allows mapping over both type arguments at<br />
once. For example,<br />
<br />
<haskell><br />
bimap (+1) length (4, [1,2,3]) = (5,3)<br />
</haskell><br />
<br />
<code>first</code> and <code>second</code> are also provided for<br />
mapping over only one type argument at a time. One is required to<br />
define either <code>bimap</code>, or both <code>first</code> and<br />
<code>second</code>, since default definitions are provided for each<br />
in terms of the others, namely:<br />
<br />
<haskell><br />
bimap f g = first f . second g<br />
<br />
first f = bimap f id<br />
second g = bimap id g<br />
</haskell><br />
<br />
==Laws==<br />
<br />
The laws for <code>Bifunctor</code> are entirely analogous to the laws<br />
for <code>Functor</code>. First, mapping with the identity function<br />
should have no effect:<br />
<br />
<haskell><br />
bimap id id = id<br />
first id = id<br />
second id = id<br />
</haskell><br />
<br />
Second, mapping with a composition should be the same as a composition<br />
of maps:<br />
<br />
<haskell><br />
bimap (f . g) (h . i) = bimap f h . bimap g i<br />
<br />
first (f . g) = first f . first g<br />
second (f . g) = second f . second g<br />
</haskell><br />
<br />
These composition laws actually come "for free" (that is, by<br />
parametricity) once the identity laws are satisfied. One can also<br />
check that the default implementations of <code>first</code> and<br />
<code>second</code> will satisfy the requisite laws if and only if<br />
<code>bimap</code> does, and vice versa.<br />
<br />
There is one additional law that relates <code>bimap</code>,<br />
<code>first</code>, and <code>second</code>, namely,<br />
<br />
<haskell><br />
bimap f g = first f . second g<br />
</haskell><br />
<br />
However, this law will hold automatically if one defines only<br />
<code>bimap</code>, or only <code>first</code> and<br />
<code>second</code>, using the default implementation for the others.<br />
So you only need to worry about this law if for some reason (''e.g.''<br />
efficiency) you define all three of the methods by hand.<br />
<br />
One might wonder about the symmetric law <code>bimap f g = second g<br />
. first f</code>; it turns out that once <code>bimap f g = first f<br />
. second g</code> is satisfied, the symmetric version [https://byorgey.wordpress.com/2018/03/30/parametricity-for-bifunctor/ also follows from parametricity].<br />
<br />
In summary, there are many laws that can be stated, but most of them<br />
follow automatically from default definitions or from parametricity.<br />
For example, if you define only <code>bimap</code>, then the only law<br />
you actually need to check is <code>bimap id id = id</code>; all the<br />
other laws come for free. Likewise, if you define only<br />
<code>first</code> and <code>second</code>, you only need to check<br />
that <code>first id = id</code> and <code>second id = id</code>.<br />
<br />
==Instances==<br />
<br />
* <code>(,)</code> and <code>Either</code> are instances in the evident way.<br />
<br />
* Some larger tuple constructors are also instances; for example, the instance for <code>(,,)</code> maps over the last two components, leaving the first alone. Why anyone would ever want to use this is unclear.<br />
<br />
* A value of type <code>Const a b</code> (to be discussed more in a later section) consists simply of a value of type <code>a</code>; <code>bimap f g</code> maps <code>f</code> over the <code>a</code> and ignores <code>g</code>.<br />
<br />
=Category=<br />
<br />
<code>Category</code> is a relatively recent addition to the Haskell standard libraries. It generalizes the notion of function composition to general “morphisms”.<br />
<br />
{{note|GHC 7.6.1 changed its rules regarding types and type variables. Now, any operator at the type level is treated as a type ''constructor'' rather than a type ''variable''; prior to GHC 7.6.1 it was possible to use <code>(~&gt;)</code> instead of <code>`arr`</code>. For more information, see [http://archive.fo/weS2f the discussion on the GHC-users mailing list]. For a new approach to nice arrow notation that works with GHC 7.6.1, see [http://archive.fo/HhdvB this message] and also [http://archive.fo/iGx6W this message] from Edward Kmett, though for simplicity I haven't adopted it here.}}<br />
The definition of the <code>Category</code> type class (from<br />
<code>Control.Category</code>; [{{HackageDocs|base|Control-Category}} haddock]) is shown below. For ease of reading, note that I have used an infix type variable <code>`arr`</code>, in parallel with the infix function type constructor <code>(->)</code>. {{noteref}} This syntax is not part of Haskell 2010. The second definition shown is the one used in the standard libraries. For the remainder of this document, I will use the infix type constructor <code>`arr`</code> for <code>Category</code> as well as <code>Arrow</code>.<br />
<br />
<haskell><br />
class Category arr where<br />
id :: a `arr` a<br />
(.) :: (b `arr` c) -> (a `arr` b) -> (a `arr` 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 which takes two type arguments, that is, something of kind <code>* -> * -> *</code>. It is instructive to imagine the type variable <code>cat</code> replaced by the function constructor <code>(->)</code>: indeed, in this case we recover precisely the familiar identity function <code>id</code> and function composition 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 below, which should be familiar from the previous discussion of the <code>Monad</code> laws. <code>Kleisli m a b</code>, as defined 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 m a a<br />
id = Kleisli return<br />
<br />
(.) :: Kleisli m b c -> Kleisli m a b -> Kleisli m a c<br />
Kleisli g . Kleisli h = Kleisli (h >=> g)<br />
</haskell><br />
<br />
The only laws that <code>Category</code> instances should satisfy are that <code>id</code> should be the identity of <code>(.)</code>, and <code>(.)</code> should be associative. This is kind of like being a monoid, except that, unlike with monoids, not any two values can be composed with <code>(.)</code>---their types have to match up.<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 <code>(.)</code> with its arguments reversed. (In previous versions of the 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 cannot represent arbitrary categories, but only categories whose objects are objects of <code>Hask</code>, the category of Haskell types. For a more general treatment of categories within Haskell, see the [http://hackage.haskell.org/package/category-extras category-extras package]. For more about 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], Benjamin Pierce’s [http://books.google.com/books/about/Basic_category_theory_for_computer_scien.html?id=ezdeaHfpYPwC Basic category theory for computer scientists], or [http://folli.loria.fr/cds/1999/esslli99/courses/barr-wells.html Barr and Wells 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 category theory links. You certainly don’t need to know any category theory to be a successful and productive Haskell programmer, but it does lend itself to much deeper appreciation of Haskell’s underlying 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>arr</code> is an instance of <code>Arrow</code>, a value of<br />
type <code>b `arr` 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> ([{{HackageDocs|base|Control-Arrow}} haddock]), is:<br />
<br />
<haskell><br />
class Category arr => Arrow arr where<br />
arr :: (b -> c) -> (b `arr` c)<br />
first :: (b `arr` c) -> ((b, d) `arr` (c, d))<br />
second :: (b `arr` c) -> ((d, b) `arr` (d, c))<br />
(***) :: (b `arr` c) -> (b' `arr` c') -> ((b, b') `arr` (c, c'))<br />
(&&&) :: (b `arr` c) -> (b `arr` c') -> (b `arr` (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 `arr` c</code> and <code>h :: c `arr` d</code>, we can form their<br />
composition <code>g >>> h :: b `arr` 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 />
Note that <code>first</code> and <code>second</code> conflict with methods of the same name from <code>Data.Bifunctor</code>. If you want to use both for some reason, you will need to import one or both qualified. It used to be common to import <code>Control.Arrow</code> just to get the <code>(->)</code> instance for use in editing pairs using <code>first</code> or <code>second</code>; now it is recommended to import <code>Data.Bifunctor</code> for this purpose instead. (Notice that for the <code>(->)</code> instance of <code>Arrow</code> and the <code>(,)</code> instance of <code>Bifunctor</code>, <code>first</code> and <code>second</code> specialize to the same type.)<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 `arr` 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 :: (b -> c) -> (b -> c)<br />
arr g = g<br />
<br />
first :: (b -> c) -> ((b,d) -> (c,d))<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 :: (b -> c) -> Kleisli m b c<br />
arr f = Kleisli (return . f)<br />
<br />
first :: Kleisli m b c -> Kleisli m (b,d) (c,d)<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 arr => ArrowChoice arr where<br />
left :: (b `arr` c) -> (Either b d `arr` Either c d)<br />
right :: (b `arr` c) -> (Either d b `arr` Either d c)<br />
(+++) :: (b `arr` c) -> (b' `arr` c') -> (Either b b' `arr` Either c c')<br />
(|||) :: (b `arr` d) -> (c `arr` d) -> (Either b c `arr` 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 arr => ArrowApply arr where<br />
app :: (b `arr` c, b) `arr` 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 `arr` ((b `arr` c) `arr` 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 />
class Arrow arr => ArrowApply arr where<br />
app :: (b `arr` c, b) `arr` c<br />
<br />
instance Monad m => ArrowApply (Kleisli m) where<br />
app :: Kleisli m (Kleisli m b c, b) c<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 :: b -> ArrowMonad a b<br />
return = -- exercise<br />
<br />
(>>=) :: ArrowMonad a a -> (a -> ArrowMonad a b) -> ArrowMonad a b<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 arr => ArrowCircuit arr where<br />
delay :: b -> (b `arr` b)<br />
<br />
counter :: ArrowCircuit arr => Bool `arr` 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<br />
[http://www.soi.city.ac.uk/~ross/papers/notation.html Paterson’s paper introducing the notation], or his later [http://www.soi.city.ac.uk/~ross/papers/fop.html 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’ 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’ 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]). There is also a precise technical sense in which [http://just-bottom.blogspot.de/2010/04/programming-with-effects-story-so-far.html <code>Arrow</code> can be seen as the intersection of <code>Applicative</code> and <code>Category</code>].<br />
<br />
Some examples of <code>Arrow</code>s include [https://wiki.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 />
<code>BiArrow</code>s of Alimarine et al. ([http://wiki.clean.cs.ru.nl/download/papers/2005/alia2005-biarrowsHaskellWorkshop.pdf "There and Back Again: Arrows for Invertible Programming"]), 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 w => Comonad w where<br />
extract :: w a -> a<br />
<br />
duplicate :: w a -> w (w a)<br />
duplicate = extend id<br />
<br />
extend :: (w a -> b) -> w a -> w b<br />
extend f = fmap f . duplicate<br />
</haskell><br />
<br />
As you can see, <code>extract</code> is the dual of <code>return</code>, <code>duplicate</code> is the dual of <code>join</code>, and <code>extend</code> is the dual of <code>(=<<)</code>. The definition of <code>Comonad</code> is a bit redundant, giving the programmer the choice on whether extend or duplicate are implemented; the other operation then has a default implementation.<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 />
-- '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 />
extract :: Stream a -> a<br />
extract (Cons x _) = x<br />
<br />
duplicate :: Stream a -> Stream (Stream a)<br />
duplicate s@(Cons x xs) = Cons s (duplicate xs)<br />
<br />
extend :: (Stream a -> b) -> Stream a -> Stream b<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 />
Gabriel Gonzalez's [http://www.haskellforall.com/2013/02/you-could-have-invented-comonads.html Comonads are objects] points out similarities between comonads and object-oriented programming.<br />
<br />
The [http://hackage.haskell.org/package/comonad-transformers comonad-transformers] package contains comonad transformers.<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 initially 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>Ysangkokhttps://wiki.haskell.org/index.php?title=Language_extensions&diff=63366Language extensions2020-07-23T06:01:25Z<p>Ysangkok: fix link to tuple sections</p>
<hr />
<div>Language extensions are used to enable language features in Haskell that may seem useful in certain cases. They can be used to loosen restrictions in the type system or add completely new language constructs to Haskell.<br />
<br />
They can be enabled using the [http://www.haskell.org/ghc/docs/7.0.4/html/users_guide/pragmas.html#language-pragma LANGUAGE pragma] <br />
<br />
<hask><br />
{-# LANGUAGE <Extension>, <Extension> #-}<br />
</hask> <br />
<br />
or (in GHC) using [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/lang.html flags] <code>-X<Extension></code>. <br />
<br />
Before just using the language extension that fits your need, [[Use of language extensions|think about<br />
when it is useful]] and what risk it may bring to your program.<br />
<br />
== List of language extensions by name ==<br />
<br />
This list is far from complete and needs extension.<br />
<br />
* [[Datatype contexts|DatatypeContexts]] : Add type constraints to your datatype.<br />
* [[Default signatures|DefaultSignatures]]<br />
* Derive:<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveDataTypeable]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveGeneric]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveFunctor]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveFoldable]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveTraversable]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#id616911 GeneralizedNewtypeDeriving]<br />
* [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#duplicate-record-fields DuplicateRecordFields] (GHC 8.0.1+) : Allow definition of record types with identically-named fields.<br />
* [[Existential type|ExistentialQuantification]]<br />
* [[Flexible contexts|FlexibleContexts]]<br />
* [[Flexiblae instances|FlexibleInstances]] : Allow a type parameter to occure twice within a type class instance.<br />
* [[Functional dependencies|FunctionalDependencies]] : Are used to constrain the parameters of type classes.<br />
* [[GADT]]s : Generalised algebraic datatypes - A more general approach to algebraic datatypes.<br />
* [[Implicit parameters|ImplicitParams]]<br />
* [[KindSignatures]]<br />
* [[Multi-parameter type class|MultiParamTypeClasses]] : Enable multiple type parameters in type classes.<br />
* [[Monomorphism restriction|NoMonomorphismRestriction]]<br />
* [[Overlapping instance|OverlappingInstances]]<br />
* [[Rank-N types|Rank2Types]]<br />
* [[Rank-N types|RankNTypes]]<br />
* [[Scoped type variables|ScopedTypeVariables]]<br />
* [[Template Haskell|TemplateHaskell]]<br />
* [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#tuple-sections TupleSections] : Allow tuples to be partially applied.<br />
* [[GHC/Type families|TypeFamilies]]<br />
* [[Undecidable instance|UndecidableInstances]]<br />
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#view-patterns ViewPatterns]<br />
* [[QualifiedDo]]<br />
<br />
= See also =<br />
<br />
* [[Use of language extensions]]<br />
<br />
<br />
[[Category:Language extensions]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=View_patterns&diff=63365View patterns2020-07-23T06:00:06Z<p>Ysangkok: fix link</p>
<hr />
<div>[https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#view-patterns GHC User's Guide: View Patterns]<br />
<br />
[[Category:Stub articles]]<br />
[[Category:Syntax]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=GHC/Type_families&diff=63364GHC/Type families2020-07-23T05:58:25Z<p>Ysangkok: fix link to gadt in user guide</p>
<hr />
<div>{{GHCUsersGuide|glasgow_exts|type-families|a Type Family section}}<br />
<br />
<br />
Indexed type families, or '''type families''' for short, are a Haskell extension supporting ad-hoc overloading of data types. Type families are parametric types that can be assigned specialized representations based on the type parameters they are instantiated with. They are the data type analogue of [[Type class|type classes]]: families are used to define overloaded ''data'' in the same way that classes are used to define overloaded ''functions''. Type families are useful for generic programming, for creating highly parameterised library interfaces, and for creating interfaces with enhanced static information, much like dependent types.<br />
<br />
Type families come in two flavors: ''data families'' and ''type synonym families''. Data families are the indexed form of data and newtype definitions. Type synonym families are the indexed form of type synonyms. Each of these flavors can be defined in a standalone manner or ''associated'' with a type class. Standalone definitions are more general, while associated types can more clearly express how a type is used and lead to better error messages.<br />
<br />
''NB: see also Simon's [https://www.haskell.org/ghc/blog/20100930-LetGeneralisationInGhc7.html blog entry on let generalisation] for a significant change in the policy for let generalisation, driven by the type family extension. In brief: a few programs will puzzlingly fail to compile with <tt>-XTypeFamilies</tt> even though the code is legal Haskell 98.''<br />
<br />
== What are type families? ==<br />
<br />
The concept of a type family comes from type theory. An indexed type family in type theory is a partial function at the type level. Applying the function to parameters (called ''type indices'') yields a type. Type families permit a program to compute what data constructors it will operate on, rather than having them fixed statically (as with simple type systems) or treated as opaque unknowns (as with parametrically polymorphic types).<br />
<br />
Type families are to vanilla data types what type class methods are to regular functions. Vanilla polymorphic data types and functions have a single definition, which is used at all type instances. Classes and type families, on the other hand, have an interface definition and any number of instance definitions. A type family's interface definition declares its [[kind]] and its arity, or the number of type indices it takes. Instance definitions define the type family over some part of the domain.<br />
<br />
As a simple example of how type families differ from ordinary parametric data types, consider a strict list type. We can represent a list of <hask>Char</hask> in the usual way, with cons cells. We can do the same thing to represent a list of <hask>()</hask>, but since a strict <hask>()</hask> value carries no useful information, it would be more efficient to just store the length of the list. This can't be done with an ordinary parametric data type, because the data constructors used to represent the list would depend on the list's type parameter: if it's <hask>Char</hask> then the list consists of cons cells; if it's <hask>()</hask>, then the list consists of a single integer. We basically want to select between two different data types based on a type parameter. Using type families, this list type could be declared as follows:<br />
<br />
<haskell><br />
-- Declare a list-like data family<br />
data family XList a<br />
<br />
-- Declare a list-like instance for Char<br />
data instance XList Char = XCons !Char !(XList Char) | XNil<br />
<br />
-- Declare a number-like instance for ()<br />
data instance XList () = XListUnit !Int<br />
</haskell><br />
<br />
The right-hand sides of the two <code>data instance</code> declarations are exactly ordinary data definitions. In fact, a <code>data instance</code> declaration is nothing more than a shorthand for a <code>data</code> declaration followed by a <code>type instance</code> (see below) declaration. However, they define two instances of the same parametric data type, <hask>XList Char</hask> and <hask>XList ()</hask>, whereas ordinary data declarations define completely unrelated types. A recent [[Simonpj/Talk:FunWithTypeFuns|tutorial paper]] has more in-depth examples of programming with type families. <br />
<br />
[[GADT]]s bear some similarity to type families, in the sense that they allow a parametric type's constructors to depend on the type's parameters. However, all GADT constructors must be defined in one place, whereas type families can be extended. Functional dependencies are similar to type families, and many type classes that use functional dependencies can be equivalently expressed with type families. Type families provide a more functional style of type-level programming than the relational style of functional dependencies.<br />
<br />
== Requirements to use type families ==<br />
<br />
Type families are a GHC extension enabled with the <code>-XTypeFamilies</code> flag or the <code>{-# LANGUAGE TypeFamilies #-}</code> option. The first stable release of GHC that properly supports type families is 6.10.1. Release 6.8 includes an early partial deprecated implementation.<br />
<br />
== An associated data type example ==<br />
<br />
As an example, consider Ralf Hinze's [http://www.cs.ox.ac.uk/ralf.hinze/publications/GGTries.ps.gz generalised tries], a form of generic finite maps. <br />
<br />
=== The class declaration ===<br />
<br />
We define a type class whose instances are the types that we can use as keys in our generic maps:<br />
<haskell><br />
class GMapKey k where<br />
data GMap k :: * -> *<br />
empty :: GMap k v<br />
lookup :: k -> GMap k v -> Maybe v<br />
insert :: k -> v -> GMap k v -> GMap k v<br />
</haskell><br />
The interesting part is the ''associated data family'' declaration of the class. It gives a [http://www.haskell.org/ghc/docs/latest/html/users_guide/type-families.html#data-family-declarations ''kind signature''] (here <hask>* -> *</hask>) for the associated data type <hask>GMap k</hask> - analogous to how methods receive a type signature in a class declaration.<br />
<br />
What it is important to notice is that the first parameter of the associated type <hask>GMap</hask> coincides with the class parameter of <hask>GMapKey</hask>. This indicates that also in all instances of the class, the instances of the associated data type need to have their first argument match up with the instance type. In general, the type arguments of an associated type can be a subset of the class parameters (in a multi-parameter type class) and they can appear in any order, possibly in an order other than in the class head. The latter can be useful if the associated data type is partially applied in some contexts.<br />
<br />
The second important point is that as <hask>GMap k</hask> has kind <hask>* -> *</hask> and <hask>k</hask> (implicitly) has kind <hask>*</hask>, the type constructor <hask>GMap</hask> (without an argument) has kind <hask>* -> * -> *</hask>. Consequently, we see that <hask>GMap</hask> is applied to two arguments in the signatures of the methods <hask>empty</hask>, <hask>lookup</hask>, and <hask>insert</hask>.<br />
<br />
=== An Int instance ===<br />
<br />
To use Ints as keys into generic maps, we declare an instance that simply uses <hask>Data.IntMap</hask>, thusly:<br />
<haskell><br />
instance GMapKey Int where<br />
data GMap Int v = GMapInt (Data.IntMap.IntMap v)<br />
empty = GMapInt Data.IntMap.empty<br />
lookup k (GMapInt m) = Data.IntMap.lookup k m<br />
insert k v (GMapInt m) = GMapInt (Data.IntMap.insert k v m)<br />
</haskell><br />
The <hask>Int</hask> instance of the associated data type <hask>GMap</hask> needs to have both of its parameters, but as only the first one corresponds to a class parameter, the second needs to be a type variable (here <hask>v</hask>). As mentioned before, any associated type parameter that corresponds to a class parameter must be identical to the class parameter in each instance. The right hand side of the associated data declaration is like that of any other data type.<br />
<br />
NB: At the moment, GADT syntax is not allowed for associated data types (or other indexed types). This is not a fundamental limitation, but just a shortcoming of the current implementation, which we expect to lift in the future.<br />
<br />
As an exercise, implement an instance for <hask>Char</hask> that maps back to the <hask>Int</hask> instance using the conversion functions <hask>Char.ord</hask> and <hask>Char.chr</hask>.<br />
<br />
=== A unit instance ===<br />
<br />
Generic definitions, apart from elementary types, typically cover units, products, and sums. We start here with the unit instance for <hask>GMap</hask>:<br />
<haskell><br />
instance GMapKey () where<br />
data GMap () v = GMapUnit (Maybe v)<br />
empty = GMapUnit Nothing<br />
lookup () (GMapUnit v) = v<br />
insert () v (GMapUnit _) = GMapUnit $ Just v<br />
</haskell><br />
For unit, the map is just a <hask>Maybe</hask> value.<br />
<br />
=== Product and sum instances ===<br />
<br />
Next, let us define the instances for pairs and sums (i.e., <hask>Either</hask>):<br />
<haskell><br />
instance (GMapKey a, GMapKey b) => GMapKey (a, b) where<br />
data GMap (a, b) v = GMapPair (GMap a (GMap b v))<br />
empty = GMapPair empty<br />
lookup (a, b) (GMapPair gm) = lookup a gm >>= lookup b <br />
insert (a, b) v (GMapPair gm) = GMapPair $ case lookup a gm of<br />
Nothing -> insert a (insert b v empty) gm<br />
Just gm2 -> insert a (insert b v gm2 ) gm<br />
<br />
instance (GMapKey a, GMapKey b) => GMapKey (Either a b) where<br />
data GMap (Either a b) v = GMapEither (GMap a v) (GMap b v)<br />
empty = GMapEither empty empty<br />
lookup (Left a) (GMapEither gm1 _gm2) = lookup a gm1<br />
lookup (Right b) (GMapEither _gm1 gm2 ) = lookup b gm2<br />
insert (Left a) v (GMapEither gm1 gm2) = GMapEither (insert a v gm1) gm2<br />
insert (Right b) v (GMapEither gm1 gm2) = GMapEither gm1 (insert b v gm2)<br />
</haskell><br />
If you find this code algorithmically surprising, I'd suggest to have a look at [http://www.cs.ox.ac.uk/ralf.hinze/publications/index.html#J4 Ralf Hinze's paper]. The only novelty concerning associated types, in these two instances, is that the instances have a context <hask>(GMapKey a, GMapKey b)</hask>. Consequently, the right hand sides of the associated type declarations can use <hask>GMap</hask> recursively at the key types <hask>a</hask> and <hask>b</hask> - not unlike the method definitions use the class methods recursively at the types for which the class is given in the instance context.<br />
<br />
=== Using a generic map ===<br />
<br />
Finally, some code building and querying a generic map:<br />
<haskell><br />
myGMap :: GMap (Int, Either Char ()) String<br />
myGMap = insert (5, Left 'c') "(5, Left 'c')" $<br />
insert (4, Right ()) "(4, Right ())" $<br />
insert (5, Right ()) "This is the one!" $<br />
insert (5, Right ()) "This is the two!" $<br />
insert (6, Right ()) "(6, Right ())" $<br />
insert (5, Left 'a') "(5, Left 'a')" $<br />
empty<br />
main = putStrLn $ maybe "Couldn't find key!" id $ lookup (5, Right ()) myGMap<br />
</haskell><br />
<br />
=== Download the code ===<br />
<br />
If you want to play with this example without copying it off the wiki, just download the source code[http://darcs.haskell.org/testsuite/tests/ghc-regress/indexed-types/should_run/GMapAssoc.hs] for <hask>GMap</hask> from GHC's test suite.<br />
<br />
== Detailed definition of data families ==<br />
<br />
Data families appear in two flavours: (1) they can be defined on the toplevel or (2) they can appear inside type classes (in which case they are known as associated types). The former is the more general variant, as it lacks the requirement for the type-indices to coincide with the class parameters. However, the latter can lead to more clearly structured code and compiler warnings if some type instances were - possibly accidentally - omitted. In the following, we always discuss the general toplevel form first and then cover the additional constraints placed on associated types.<br />
<br />
=== Family declarations ===<br />
<br />
Indexed data families are introduced by a signature, such as <br />
<haskell><br />
data family GMap k :: * -> *<br />
</haskell><br />
The special <hask>family</hask> distinguishes family from standard data declarations. The result kind annotation is optional and, as usual, defaults to <hask>*</hask> if omitted. An example is<br />
<haskell><br />
data family Array e<br />
</haskell><br />
Named arguments can also be given explicit kind signatures if needed. Just as with [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#generalised-algebraic-data-types-gadts GADT declarations] named arguments are entirely optional, so that we can declare <hask>Array</hask> alternatively with<br />
<haskell><br />
data family Array :: * -> *<br />
</haskell><br />
<br />
==== Associated family declarations ====<br />
<br />
When a data family is declared as part of a type class, we drop the <hask>family</hask> keyword. The <hask>GMap</hask> declaration takes the following form<br />
<haskell><br />
class GMapKey k where<br />
data GMap k :: * -> *<br />
...<br />
</haskell><br />
In contrast to toplevel declarations, named arguments must be used for all type parameters that are to be used as type-indices. Moreover, the argument names must be class parameters. Each class parameter may only be used at most once per associated type, but some may be omitted and they may be in an order other than in the class head. In other words: '''the named type parameters of the data declaration must be a permutation of a subset of the class variables'''. <br />
<br />
Example is admissible:<br />
<haskell><br />
class C a b c where { data T c a :: * } -- OK<br />
class C a b c where { data T a a :: * } -- Bad: repeated variable<br />
class D a where { data T a x :: * } -- Bad: x is not a class variable<br />
class D a where { data T a :: * -> * } -- OK<br />
</haskell><br />
<br />
=== Instance declarations ===<br />
<br />
Instance declarations of data and newtype families are very similar to standard data and newtype declarations. The only two differences are that the keyword <hask>data</hask> or <hask>newtype</hask> is followed by <hask>instance</hask> and that some or all of the type arguments can be non-variable types, but may not contain forall types or type synonym families. However, data families are generally allowed in type parameters, and type synonyms are allowed as long as they are fully applied and expand to a type that is itself admissible - exactly as this is required for occurrences of type synonyms in class instance parameters. For example, the <hask>Either</hask> instance for <hask>GMap</hask> is<br />
<haskell><br />
data instance GMap (Either a b) v = GMapEither (GMap a v) (GMap b v)<br />
</haskell><br />
In this example, the declaration has only one variant. In general, it can be any number.<br />
<br />
Data and newtype instance declarations are only legit when an appropriate family declaration is in scope - just like class instances require the class declaration to be visible. Moreover, each instance declaration has to conform to the kind determined by its family declaration. This implies that the number of parameters of an instance declaration matches the arity determined by the kind of the family. Although all data families are declared with the <hask>data</hask> keyword, instances can be either <hask>data</hask> or <hask>newtype</hask>s, or a mix of both.<br />
<br />
Even if type families are defined as toplevel declarations, functions that perform different computations for different family instances still need to be defined as methods of type classes. In particular, the following is not possible:<br />
<haskell><br />
data family T a<br />
data instance T Int = A<br />
data instance T Char = B<br />
nonsense :: T a -> Int<br />
nonsense A = 1 -- WRONG: These two equations together...<br />
nonsense B = 2 -- ...will produce a type error.<br />
</haskell><br />
Given the functionality provided by GADTs (Generalised Algebraic Data Types), it might seem as if a definition, such as the above, should be feasible. However, type families - in contrast to GADTs - are ''open''; i.e., new instances can always be added, possibly in other modules. Supporting pattern matching across different data instances would require a form of extensible case construct.<br />
<br />
==== Associated type instances ====<br />
<br />
When an associated family instance is declared within a type class instance, we drop the <hask>instance</hask> keyword in the family instance. So, the <hask>Either</hask> instance for <hask>GMap</hask> becomes:<br />
<haskell><br />
instance (GMapKey a, GMapKey b) => GMapKey (Either a b) where<br />
data GMap (Either a b) v = GMapEither (GMap a v) (GMap b v)<br />
...<br />
</haskell><br />
The most important point about associated family instances is that the type indices corresponding to class parameters must be identical to the type given in the instance head; here this is the first argument of <hask>GMap</hask>, namely <hask>Either a b</hask>, which coincides with the only class parameter. Any parameters to the family constructor that do not correspond to class parameters, need to be variables in every instance; here this is the variable <hask>v</hask>.<br />
<br />
Instances for an associated family can only appear as part of instance declarations of the class in which the family was declared - just as with the equations of the methods of a class. Also in correspondence to how methods are handled, declarations of associated types can be omitted in class instances. If an associated family instance is omitted, the corresponding instance type is not inhabited; i.e., only diverging expressions, such as <hask>undefined</hask>, can assume the type.<br />
<br />
==== Scoping of class parameters ====<br />
<br />
In the case of multi-parameter type classes, the visibility of class parameters in the right-hand side of associated family instances depends ''solely'' on the parameters of the data family. As an example, consider the simple class declaration<br />
<haskell><br />
class C a b where<br />
data T a<br />
</haskell><br />
Only one of the two class parameters is a parameter to the data family. Hence, the following instance declaration is invalid:<br />
<haskell><br />
instance C [c] d where<br />
data T [c] = MkT (c, d) -- WRONG!! 'd' is not in scope<br />
</haskell><br />
Here, the right-hand side of the data instance mentions the type variable <hask>d</hask> that does not occur in its left-hand side. We cannot admit such data instances as they would compromise type safety.<br />
<br />
==== Type class instances of family instances ====<br />
<br />
Type class instances of instances of data families can be defined as usual, and in particular data instance declarations can have <hask>deriving</hask> clauses. For example, we can write<br />
<haskell><br />
data GMap () v = GMapUnit (Maybe v)<br />
deriving Show<br />
</haskell><br />
which implicitly defines an instance of the form<br />
<haskell><br />
instance Show v => Show (GMap () v) where ...<br />
</haskell><br />
<br />
Note that class instances are always for particular ''instances'' of a data family and never for an entire family as a whole. This is for essentially the same reasons that we cannot define a toplevel function that performs pattern matching on the data constructors of ''different'' instances of a single type family. It would require a form of extensible case construct.<br />
<br />
==== Overlap ====<br />
<br />
The instance declarations of a data family used in a single program may not overlap at all, independent of whether they are associated or not. In contrast to type class instances, this is not only a matter of consistency, but one of type safety.<br />
<br />
=== Import and export ===<br />
<br />
The association of data constructors with type families is more dynamic than that is the case with standard data and newtype declarations. In the standard case, the notation <hask>T(..)</hask> in an import or export list denotes the type constructor and all the data constructors introduced in its declaration. However, a family declaration never introduces any data constructors; instead, data constructors are introduced by family instances. As a result, which data constructors are associated with a type family depends on the currently visible instance declarations for that family. Consequently, an import or export item of the form <hask>T(..)</hask> denotes the family constructor and all currently visible data constructors - in the case of an export item, these may be either imported or defined in the current module. The treatment of import and export items that explicitly list data constructors, such as <hask>GMap(GMapEither)</hask>, is analogous.<br />
<br />
==== Associated families ====<br />
<br />
As expected, an import or export item of the form <hask>C(..)</hask> denotes all of the class' methods and associated types. However, when associated types are explicitly listed as subitems of a class, we need some new syntax, as uppercase identifiers as subitems are usually data constructors, not type constructors. To clarify that we denote types here, each associated type name needs to be prefixed by the keyword <hask>type</hask>. So for example, when explicitly listing the components of the <hask>GMapKey</hask> class, we write <hask>GMapKey(type GMap, empty, lookup, insert)</hask>.<br />
<br />
==== Examples ====<br />
<br />
Assuming our running <hask>GMapKey</hask> class example, let us look at some export lists and their meaning:<br />
<br />
* <hask>module GMap (GMapKey) where...</hask>: Exports just the class name.<br />
* <hask>module GMap (GMapKey(..)) where...</hask>: Exports the class, the associated type <hask>GMap</hask> and the member functions <hask>empty</hask>, <hask>lookup</hask>, and <hask>insert</hask>. None of the data constructors is exported.<br />
* <hask>module GMap (GMapKey(..), GMap(..)) where...</hask>: As before, but also exports all the data constructors <hask>GMapInt</hask>, <hask>GMapChar</hask>, <hask>GMapUnit</hask>, <hask>GMapPair</hask>, and <hask>GMapEither</hask>.<br />
* <hask>module GMap (GMapKey(empty, lookup, insert), GMap(..)) where...</hask>: As before.<br />
* <hask>module GMap (GMapKey, empty, lookup, insert, GMap(..)) where...</hask>: As before.<br />
<br />
Finally, you can write <hask>GMapKey(type GMap)</hask> to denote both the class <hask>GMapKey</hask> as well as its associated type <hask>GMap</hask>. However, you cannot write <hask>GMapKey(type GMap(..))</hask> &mdash; i.e., sub-component specifications cannot be nested. To specify <hask>GMap</hask>'s data constructors, you have to list it separately.<br />
<br />
==== Instances ====<br />
<br />
Family instances are implicitly exported, just like class instances. However, this applies only to the heads of instances, not to the data constructors an instance defines.<br />
<br />
== An associated type synonym example ==<br />
<br />
Type synonym families are an alternative to functional dependencies, which makes functional dependency examples well suited to introduce type synonym families. In fact, type families are a more functional way to express the same as functional dependencies (despite the name!), as they replace the relational notation of functional dependencies by an expression-oriented notation; i.e., functions on types are really represented by functions and not relations.<br />
<br />
=== The <hask>class</hask> declaration ===<br />
<br />
Here's an example from Mark Jones' seminal paper on functional dependencies:<br />
<haskell><br />
class Collects e ce | ce -> e where<br />
empty :: ce<br />
insert :: e -> ce -> ce<br />
member :: e -> ce -> Bool<br />
toList :: ce -> [e]<br />
</haskell><br />
<br />
With associated type synonyms we can write this as<br />
<haskell><br />
class Collects ce where<br />
type Elem ce<br />
empty :: ce<br />
insert :: Elem ce -> ce -> ce<br />
member :: Elem ce -> ce -> Bool<br />
toList :: ce -> [Elem ce]<br />
</haskell><br />
Instead of the multi-parameter type class, we use a single parameter class, and the parameter <hask>e</hask><br />
turned into an associated type synonym <hask>Elem ce</hask>.<br />
<br />
=== An <hask>instance</hask>===<br />
<br />
Instances change correspondingly. An instance of the two-parameter class<br />
<haskell><br />
instance Eq e => Collects e [e] where<br />
empty = []<br />
insert e l = (e:l)<br />
member e [] = False<br />
member e (x:xs) <br />
| e == x = True<br />
| otherwise = member e xs<br />
toList l = l<br />
</haskell><br />
becomes an instance of a single-parameter class, where the dependent type parameter turns into an associated type instance declaration:<br />
<haskell><br />
instance Eq e => Collects [e] where<br />
type Elem [e] = e<br />
empty = []<br />
insert e l = (e:l)<br />
member e [] = False<br />
member e (x:xs) <br />
| e == x = True<br />
| otherwise = member e xs<br />
toList l = l<br />
</haskell><br />
<br />
=== Using generic collections ===<br />
<br />
With Functional Dependencies the code would be:<br />
<haskell><br />
sumCollects :: (Collects e c1, Collects e c2) => c1 -> c2 -> c2<br />
sumCollects c1 c2 = foldr insert c2 (toList c1)<br />
</haskell><br />
<br />
In contrast, with associated type synonyms, we get:<br />
<haskell><br />
sumCollects :: (Collects c1, Collects c2, Elem c1 ~ Elem c2) => c1 -> c2 -> c2<br />
sumCollects c1 c2 = foldr insert c2 (toList c1)<br />
</haskell><br />
<br />
== Detailed definition of type synonym families ==<br />
<br />
Type families appear in two flavours: (1) they can be defined on the toplevel or (2) they can appear inside type classes (in which case they are known as associated type synonyms). The former is the more general variant, as it lacks the requirement for the type-indices to coincide with the class parameters. However, the latter can lead to more clearly structured code and compiler warnings if some type instances were - possibly accidentally - omitted. In the following, we always discuss the general toplevel form first and then cover the additional constraints placed on associated types.<br />
<br />
=== Family declarations ===<br />
<br />
Indexed type families are introduced by a signature, such as <br />
<haskell><br />
type family Elem c :: *<br />
</haskell><br />
The special <hask>family</hask> distinguishes family from standard type declarations. The result kind annotation is optional and, as usual, defaults to <hask>*</hask> if omitted. An example is<br />
<haskell><br />
type family Elem c<br />
</haskell><br />
Parameters can also be given explicit kind signatures if needed. We call the number of parameters in a type family declaration, the family's arity, and all applications of a type family must be fully saturated w.r.t. to that arity. This requirement is unlike ordinary type synonyms and it implies that the kind of a type family is not sufficient to determine a family's arity, and hence in general, also insufficient to determine whether a type family application is well formed. As an example, consider the following declaration:<br />
<haskell><br />
type family F a b :: * -> * -- F's arity is 2, <br />
-- although its overall kind is * -> * -> * -> *<br />
</haskell><br />
Given this declaration the following are examples of well-formed and malformed types:<br />
<haskell><br />
F Char [Int] -- OK! Kind: * -> *<br />
F Char [Int] Bool -- OK! Kind: *<br />
F IO Bool -- WRONG: kind mismatch in the first argument<br />
F Bool -- WRONG: unsaturated application<br />
</haskell><br />
<br />
A top-level type family can be declared as open or closed. (Associated type<br />
families are always open.) A closed type family has all of its equations<br />
defined in one place and cannot be extended, whereas an open family can have<br />
instances spread across modules. The advantage of a closed family is that<br />
its equations are tried in order, similar to a term-level function definition:<br />
<haskell><br />
type family G a where<br />
G Int = Bool<br />
G a = Char<br />
</haskell><br />
With this definition, the type <hask>G Int</hask> becomes <hask>Bool</hask><br />
and, say, <hask>G Double</hask> becomes <hask>Char</hask>. See also [http://ghc.haskell.org/trac/ghc/wiki/NewAxioms here] for more information about closed type families.<br />
<br />
==== Associated family declarations ====<br />
<br />
When a type family is declared as part of a type class, we drop the <hask>family</hask> special. The <hask>Elem</hask> declaration takes the following form<br />
<haskell><br />
class Collects ce where<br />
type Elem ce :: *<br />
...<br />
</haskell><br />
Exactly as in the case of an associated data declaration, '''the named type parameters must be a permutation of a subset of the class parameters'''. Examples<br />
<haskell><br />
class C a b c where { type T c a :: * } -- OK<br />
class D a where { type T a x :: * } -- No: x is not a class parameter<br />
class D a where { type T a :: * -> * } -- OK<br />
</haskell><br />
<br />
=== Type instance declarations ===<br />
<br />
Instance declarations of open type families are very similar to standard type synonym declarations. The only two differences are that the keyword <hask>type</hask> is followed by <hask>instance</hask> and that some or all of the type arguments can be non-variable types, but may not contain forall types or type synonym families. However, data families are generally allowed, and type synonyms are allowed as long as they are fully applied and expand to a type that is admissible - these are the exact same requirements as for data instances. For example, the <hask>[e]</hask> instance for <hask>Elem</hask> is<br />
<haskell><br />
type instance Elem [e] = e<br />
</haskell><br />
<br />
A type family instance declaration must satisfy the following rules:<br />
* An appropriate family declaration is in scope - just like class instances require the class declaration to be visible. <br />
* The instance declaration conforms to the kind determined by its family declaration<br />
* The number of type parameters in an instance declaration matches the number of type parameters in the family declaration.<br />
* The right-hand side of a type instance must be a monotype (i.e., it may not include foralls) and after the expansion of all saturated vanilla type synonyms, no synonyms, except family synonyms may remain.<br />
<br />
Here are some examples of admissible and illegal type instances and closed families:<br />
<haskell><br />
type family F a :: *<br />
type instance F [Int] = Int -- OK!<br />
type instance F String = Char -- OK!<br />
type instance F (F a) = a -- WRONG: type parameter mentions a type family<br />
type instance F (forall a. (a, b)) = b -- WRONG: a forall type appears in a type parameter<br />
type instance F Float = forall a.a -- WRONG: right-hand side may not be a forall type<br />
<br />
type family F2 a where -- OK!<br />
F2 (Maybe Int) = Int<br />
F2 (Maybe Bool) = Bool<br />
F2 (Maybe a) = String<br />
<br />
type family G a b :: * -> *<br />
type instance G Int = (,) -- WRONG: must be two type parameters<br />
type instance G Int Char Float = Double -- WRONG: must be two type parameters<br />
</haskell><br />
<br />
==== Closed family simplification ====<br />
<br />
Included in ghc starting 7.8.1.<br />
<br />
When dealing with closed families, simplifying the type is harder than just finding a left-hand side that matches and replacing that with a right-hand side. GHC will select an equation to use in a given type family application (the "target") if and only if the following 2 conditions hold:<br />
<br />
# There is a substitution from the variables in the equation's LHS that makes the left-hand side of the branch coincide with the target.<br />
# For each previous equation in the family: either the LHS of that equation is ''apart'' from the type family application, '''or''' the equation is ''compatible'' with the chosen equation.<br />
<br />
Now, we define ''apart'' and ''compatible'':<br />
# Two types are ''apart'' when one cannot simplify to the other, even after arbitrary type-family simplifications<br />
# Two equations are ''compatible'' if, either, their LHSs are apart or their LHSs unify and their RHSs are the same under the substitution induced by the unification.<br />
<br />
Some examples are in order:<br />
<haskell><br />
type family F a where<br />
F Int = Bool<br />
F Bool = Char<br />
F a = Bool<br />
<br />
type family And (a :: Bool) (b :: Bool) :: Bool where<br />
And False c = False<br />
And True d = d<br />
And e False = False<br />
And f True = f<br />
And g g = g<br />
</haskell><br />
<br />
In <hask>F</hask>, all pairs of equations are compatible except the second and third. The first two are compatible because their LHSs are apart. The first and third are compatible because the unifying substitution leads the RHSs to be the same. But, the second and third are not compatible because neither of these conditions holds. As a result, GHC will not use the third equation to simplify a target unless that target is apart from <hask>Bool</hask>.<br />
<br />
In <hask>And</hask>, ''every'' pair of equations is compatible, meaning GHC never has to make the extra apartness check during simplification.<br />
<br />
Why do all of this? It's a matter of type safety. Consider this example:<br />
<br />
<haskell><br />
type family J a b where<br />
J a a = Int<br />
J a b = Bool<br />
</haskell><br />
<br />
Say GHC selected the second branch just because the first doesn't apply at the moment, because two type variables are distinct. The problem is that those variables might later be instantiated at the same value, and then the first branch would have applied. You can convince this sort of inconsistency to produce <hask>unsafeCoerce</hask>.<br />
<br />
It gets worse. GHC has no internal notion of inequality, so it can't use previous, failed term-level GADT pattern matches to refine its type assumptions. For example:<br />
<br />
<haskell><br />
data G :: * -> * where<br />
GInt :: G Int<br />
GBool :: G Bool<br />
<br />
type family Foo (a :: *) :: * where<br />
Foo Int = Char<br />
Foo a = Double<br />
<br />
bar :: G a -> Foo a<br />
bar GInt = 'x'<br />
bar _ = 3.14<br />
</haskell><br />
<br />
The last line will fail to typecheck, because GHC doesn't know that the type variable <hask>a</hask> can't be <hask>Int</hask> here, even though it's obvious. The only general way to fix this is to have inequality evidence introduced into GHC, and that's a big deal and we don't know if we have the motivation for such a change yet.<br />
<br />
==== Associated type instances ====<br />
<br />
When an associated family instance is declared within a type class instance, we drop the <hask>instance</hask> keyword in the family instance. So, the <hask>[e]</hask> instance for <hask>Elem</hask> becomes:<br />
<haskell><br />
instance (Eq (Elem [e])) => Collects ([e]) where<br />
type Elem [e] = e<br />
...<br />
</haskell><br />
The most important point about associated family instances is that the type indexes corresponding to class parameters must be identical to the type given in the instance head; here this is <hask>[e]</hask>, which coincides with the only class parameter.<br />
<br />
Instances for an associated family can only appear as part of instance declarations of the class in which the family was declared - just as with the equations of the methods of a class. Also in correspondence to how methods are handled, declarations of associated types can be omitted in class instances. If an associated family instance is omitted, the corresponding instance type is not inhabited; i.e., only diverging expressions, such as <hask>undefined</hask>, can assume the type.<br />
<br />
==== Overlap ====<br />
<br />
The instance declarations of an open type family used in a single program must be compatible, in the form defined above. This condition is independent of whether the type family is associated or not, and it is not only a matter of consistency, but one of type safety. <br />
<br />
Here are two examples to illustrate the condition under which overlap is permitted.<br />
<haskell><br />
type instance F (a, Int) = [a]<br />
type instance F (Int, b) = [b] -- overlap permitted<br />
<br />
type instance G (a, Int) = [a]<br />
type instance G (Char, a) = [a] -- ILLEGAL overlap, as [Char] /= [Int]<br />
</haskell><br />
<br />
==== Decidability ====<br />
<br />
In order to guarantee that type inference in the presence of type families is decidable, we need to place a number of additional restrictions on the formation of type instance declarations (c.f., Definition 5 (Relaxed Conditions) of [http://www.cse.unsw.edu.au/~chak/papers/SPCS08.html Type Checking with Open Type Functions]). Instance declarations have the general form<br />
<haskell><br />
type instance F t1 .. tn = t<br />
</haskell><br />
where we require that for every type family application <hask>(G s1 .. sm)</hask> in <hask>t</hask>, <br />
# <hask>s1 .. sm</hask> do not contain any type family constructors,<br />
# the total number of symbols (data type constructors and type variables) in <hask>s1 .. sm</hask> is strictly smaller than in <hask>t1 .. tn</hask>, and<br />
# for every type variable <hask>a</hask>, <hask>a</hask> occurs in <hask>s1 .. sm</hask> at most as often as in <hask>t1 .. tn</hask>.<br />
These restrictions are easily verified and ensure termination of type inference. However, they are not sufficient to guarantee completeness of type inference in the presence of, so called, ''loopy equalities'', such as <hask>a ~ [F a]</hask>, where a recursive occurrence of a type variable is underneath a family application and data constructor application - see the above mentioned paper for details. <br />
<br />
If the option <tt>-XUndecidableInstances</tt> is passed to the compiler, the above restrictions are not enforced and it is on the programmer to ensure termination of the normalisation of type families during type inference.<br />
<br />
=== Equality constraints ===<br />
<br />
Type context can include equality constraints of the form <hask>t1 ~ t2</hask>, which denote that the types <hask>t1</hask> and <hask>t2</hask> need to be the same. In the presence of type families, whether two types are equal cannot generally be decided locally. Hence, the contexts of function signatures may include equality constraints, as in the following example:<br />
<haskell><br />
sumCollects :: (Collects c1, Collects c2, Elem c1 ~ Elem c2) => c1 -> c2 -> c2<br />
</haskell><br />
where we require that the element type of <hask>c1</hask> and <hask>c2</hask> are the same. In general, the types <hask>t1</hask> and <hask>t2</hask> of an equality constraint may be arbitrary monotypes; i.e., they may not contain any quantifiers, independent of whether higher-rank types are otherwise enabled.<br />
<br />
Equality constraints can also appear in class and instance contexts. The former enable a simple translation of programs using functional dependencies into programs using family synonyms instead. The general idea is to rewrite a class declaration of the form<br />
<haskell><br />
class C a b | a -> b<br />
</haskell><br />
to<br />
<haskell><br />
class (F a ~ b) => C a b where<br />
type F a<br />
</haskell><br />
That is, we represent every functional dependency (FD) <hask>a1 .. an -> b</hask> by an FD type family <hask>F a1 .. an</hask> and a superclass context equality <hask>F a1 .. an ~ b</hask>, essentially giving a name to the functional dependency. In class instances, we define the type instances of FD families in accordance with the class head. Method signatures are not affected by that process.<br />
<br />
== Frequently asked questions ==<br />
<br />
=== Comparing type families and functional dependencies ===<br />
<br />
Functional dependencies cover some of the same territory as type families. How do the two compare?<br />
There are some articles about this question:<br />
<br />
* Experiences in converting functional dependencies to type families: "[[Functional dependencies vs. type families]]"<br />
* [https://ghc.haskell.org/trac/ghc/wiki/TFvsFD GHC trac] on a comparison of functional dependencies and type families<br />
<br />
=== Injectivity, type inference, and ambiguity ===<br />
<br />
A common problem is if:<br />
<br />
<haskell><br />
type family F a<br />
<br />
f :: F a -> F a<br />
f = undefined<br />
<br />
g :: F Int -> F Int<br />
g x = f x<br />
</haskell><br />
<br />
Then compiler complains about the definition of <tt>g</tt>:<br />
<br />
<code><br />
Couldn't match expected type `F Int' against inferred type `F a1'.<br />
</code><br />
<br />
In type-checking <tt>g</tt>'s right hand side GHC discovers (by instantiating <tt>f</tt>'s type with a fresh type variable) that it has type <tt>F a1 -> F a1</tt> for some as-yet-unknown type <tt>a1</tt>. Now it tries to make the inferred type match <tt>g</tt>'s type signature. Well, you say, just make <tt>a1</tt> equal to <tt>Int</tt> and you are done. True, but what if there were these instances<br />
<haskell><br />
type instance F Int = Bool<br />
type instance F Char = Bool<br />
</haskell><br />
Then making <tt>a1</tt> equal to <tt>Char</tt> would ''also'' make the two types equal. Because there is (potentially) more than one choice, the program is rejected.<br />
<br />
However (and confusingly) if you omit the type signature on <tt>g</tt> altogether, thus<br />
<haskell><br />
f :: F a -> F a<br />
f = undefined<br />
<br />
g x = f x<br />
</haskell><br />
GHC will happily infer the type <tt>g :: F a -> F a</tt>. But you can't ''write'' that type signature or, indeed, the more specific one above. (Arguably this behaviour, where GHC ''infers'' a type it can't ''check'', is very confusing. I suppose we could make GHC reject both programs, with and without type signatures.)<br />
<br />
'''What is the problem?''' The nub of the issue is this: knowing that <tt>F t1</tt>=<tt>F t2</tt> does ''not'' imply that <tt>t1</tt> = <tt>t2</tt>.<br />
The difficulty is that the type function <tt>F</tt> need not be ''injective''; it can map two distinct types to the same type. For an injective type constructor like <tt>Maybe</tt>, if we know that <tt>Maybe t1</tt> = <tt>Maybe t2</tt>, then we know that <tt>t1</tt> = <tt>t2</tt>. But not so for non-injective type functions.<br />
<br />
The problem starts with <tt>f</tt>. Its type is ''ambiguous''; even if I know the argument and result types for <tt>f</tt>, I cannot use that to find the type at which <tt>a</tt> should be instantiated. (So arguably, <tt>f</tt> should be rejected as having an ambiguous type, and probably will be in future.) The situation is well known in type classes: <br />
<haskell><br />
bad :: (Read a, Show a) => String -> String<br />
bad x = show (read x)<br />
</haskell><br />
At a call of <tt>bad</tt> one cannot tell at what type <tt>a</tt> should be instantiated.<br />
<br />
The only solution is to avoid ambiguous types. In the type signature of a function, <br />
* Ensure that every type variable occurs in the part after the "<tt>=></tt>"<br />
* Ensure that every type variable appears at least once outside a type function call.<br />
Alternatively, you can use data families, which create new types and are therefore injective. The following code works:<br />
<br />
<haskell>data family F a<br />
<br />
f :: F a -> F a<br />
f = undefined<br />
<br />
g :: F Int -> F Int<br />
g x = f x</haskell><br />
<br />
== References ==<br />
<br />
* [http://www.cse.unsw.edu.au/~chak/papers/CKPM05.html Associated Types with Class.] Manuel M. T. Chakravarty, Gabriele Keller, Simon Peyton Jones, and Simon Marlow. In ''Proceedings of The 32nd Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL'05)'', pages 1-13, ACM Press, 2005.<br />
* [http://www.cse.unsw.edu.au/~chak/papers/CKP05.html Associated Type Synonyms.] Manuel M. T. Chakravarty, Gabriele Keller, and Simon Peyton Jones. In ''Proceedings of The Tenth ACM SIGPLAN International Conference on Functional Programming'', ACM Press, pages 241-253, 2005.<br />
* [http://www.cse.unsw.edu.au/~chak/papers/SCPD07.html System F with Type Equality Coercions.] Martin Sulzmann, Manuel M. T. Chakravarty, Simon Peyton Jones, and Kevin Donnelly. In ''Proceedings of The Third ACM SIGPLAN Workshop on Types in Language Design and Implementation'', ACM Press, 2007.<br />
* [http://www.cse.unsw.edu.au/~chak/papers/SPCS08.html Type Checking With Open Type Functions.] Tom Schrijvers, Simon Peyton-Jones, Manuel M. T. Chakravarty, Martin Sulzmann. In ''Proceedings of The 13th ACM SIGPLAN International Conference on Functional Programming'', ACM Press, pages 51-62, 2008.<br />
* [[Simonpj/Talk:FunWithTypeFuns | Fun with Type Functions]] Oleg Kiselyov, Simon Peyton Jones, Chung-chieh Shan (the source for this paper can be found at http://patch-tag.com/r/schoenfinkel/typefunctions/wiki ) <br />
<br />
[[Category:Type-level programming]]<br />
[[Category:Language extensions]]<br />
[[Category:GHC|Indexed types]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=GHC/FAQ&diff=63363GHC/FAQ2020-07-23T05:57:05Z<p>Ysangkok: fix link to ghc user guide ffi chapter</p>
<hr />
<div>[[Category:GHC]] [[Category:FAQ]]<br />
Please feel free to add stuff here.<br />
<br />
This page is rather long. We've started to add some sub-headings, but would welcome your help in making it better organised.<br />
<br />
= GHC (Platform-specific Issues) =<br />
<br />
== Porting GHC ==<br />
<br />
=== How do I port GHC to platform X? ===<br />
<br />
There are two distinct possibilities: either<br />
<br />
* The hardware architecture for your system is already supported by GHC, but you're running an OS that isn't supported (or perhaps has been supported in the past, but currently isn't). This is the easiest type of porting job, but it still requires some careful bootstrapping.<br />
<br />
* Your system's hardware architecture isn't supported by GHC. This will be a more difficult port (though by comparison perhaps not as difficult as porting gcc).<br />
<br />
Both ways require you to bootstrap from intermediate HC files: these are the stylised C files generated by GHC when it compiles Haskell source. Basically the idea is to take the HC files for GHC itself to the target machine and compile them with gcc to get a working GHC, and go from there.<br />
<br />
The [http://hackage.haskell.org/trac/ghc/wiki/Building Building Guide] has all the details on how to bootstrap GHC on a new platform.<br />
<br />
<br />
== Linux-related ==<br />
<br />
=== Missing libreadline.so.x Errors ===<br />
<br />
==== I Can't run GHCi on Linux, because it complains about a missing <tt>libreadline.so.3</tt>. ====<br />
<br />
The "correct" fix for this problem is to install the correct package for the particular flavour of Linux on your machine. If this isn't an option, however, there is a hack that might work: make a symbolic link from <tt>libreadline.so.4</tt> to <tt>libreadline.so.3</tt> in <tt>/usr/lib</tt>. We tried this on a SuSE 7.1 box and it seemed to work, but YMMV.<br />
<br />
=== Linking Errors ===<br />
<br />
==== Linking a program causes the following error on Linux: <tt>/usr/bin/ld: cannot open -lgmp: No such file or directory</tt> ====<br />
<br />
The problem is that your system doesn't have the GMP library installed. If this is a RedHat distribution, install the RedHat-supplied gmp-devel package, and the gmp package if you don't already have it. There have been reports that installing the RedHat packages also works for SuSE (SuSE doesn't supply a shared gmp library).<br />
<br />
=== SELinux-related ===<br />
<br />
==== Memory Allocation Errors ====<br />
<br />
If you have SELinux enabled on your system, then GHC may fail with a memory allocation error:<br />
<br />
ghc-6.4.1: internal error: mallocBytesRWX: failed to protect 0x0x1660730<br />
<br />
or maybe<br />
<br />
ghc: internal error: getMBlock: mmap: Permission denied <br />
<br />
The reason for this is that SELinux prevents allocation of writeable/executable memory regions, which GHC needs in order to implement certain parts of the FFI that require dynamic code generation. (See [http://hackage.haskell.org/trac/ghc/ticket/738 this bug report]).<br />
<br />
In GHC 6.4.2 we improved the situation somewhat, but not completely.<br />
<br />
Workarounds:<br />
<br />
* Set <tt>allow_execmem</tt> to 0, with the <tt>setsebool</tt> command.<br />
* do this on a per-program basis, for GHC and GHC-compiled programs. Apparently this is done by:<br />
<br />
<tt>/usr/bin/chcon -t unconfined_execmem_exec_t /path/to/binary/prog</tt><br />
<br />
== Solaris-related ==<br />
<br />
=== Link Errors ===<br />
<br />
==== Solaris users may sometimes get link errors due to libraries needed by GNU Readline. ====<br />
<br />
We suggest you try linking in some combination of the termcap, curses and ncurses libraries, by giving <tt>-ltermcap</tt>, <tt>-lcurses</tt> and <tt>-lncurses</tt> respectively. If you encounter this problem, we would appreciate feedback on it, since we don't fully understand what's going on here.<br />
The build fails in readline.<br />
<br />
It has been reported that if you have multiple versions of the readline library installed on Linux, then this may cause the build to fail. If you have multiple versions of readline, try uninstalling all except the most recent version.<br />
<br />
== Windows-related ==<br />
<br />
=== Heapsize-related Crashes ===<br />
<br />
==== My program that uses a really large heap crashes on Windows. ====<br />
<br />
For utterly horrible reasons, programs that use more than 128Mb of heap won't work when compiled dynamically on Windows (they should be fine statically compiled).<br />
<br />
=== Ctrl-C Not Working ===<br />
<br />
When running GHC under a Cygwin shell on Windows, Ctrl-C sometimes doesn't work. A workaround is to use Ctrl-Break instead. Another workaround is to use the rlwrap program (cygwin package available) to invoke ghci : In addition to proper Ctrl-C, you also get emacs (or vi) key bindings and command history across sessions. <br />
<br />
=== Linking with Visual Studio C++ Code ===<br />
<br />
==== How do I link Haskell with C++ code compiled by Visual Studio? ====<br />
<br />
===== Prerequisites =====<br />
<br />
It is assumed that the reader is familiar with the Haskell <br />
[https://downloads.haskell.org/ghc/latest/docs/html/users_guide/ffi-chap.html#foreign-function-interface-ffi Foreign function interface (FFI)],<br />
and is able to compile Haskell programs with GHC and C++ programs with Visual Studio.<br />
<br />
===== Background =====<br />
<br />
GHC has two modes of code generation. It either compiles Haskell straight into object code<br />
(native mode), or translates Haskell into intermediate C code, and uses a C compiler as backend.<br />
<br />
The Windows distribution of GHC comes bundled with the GCC compiler, which is used as backend.<br />
That's why linking Haskell with Visual C++ is no different from linking GCC-generated code with<br />
the code generated by Visual C++.<br />
<br />
One cannot statically link together object files produced by those two compilers,<br />
but they can be linked dynamically: an executable produced by Visual C++ can invoke a DLL<br />
produced by GCC, and vice versa. Likewise, we can link Haskell with Visual C++ in one of these ways.<br />
<br />
''Note:'' when Haskell becomes able to use Visual C++ as a backend (see [http://hackage.haskell.org/trac/ghc/ticket/989]), we would not need to go via a DLL anymore. Instead, we would simply list<br />
all source files (Haskell and C++) on the command line of GHC.<br />
<br />
===== Invoking a Haskell DLL =====<br />
<br />
====== From a C++ executable ======<br />
<br />
#Make a Haskell DLL as explained in [http://www.haskell.org/ghc/docs/latest/html/users_guide/win32-dlls.html#win32-dlls-foreign]<br />
#Make a module definition file, such as<tt><br>LIBRARY Adder<br>EXPORTS<br>&nbsp;&nbsp;&nbsp;&nbsp;adder</tt><br />
#Create an import library using Visual Studio's <tt>lib.exe:<br>lib /DEF:adder.def /OUT:adder.lib</tt><br />
#Link the C++ program against the import library.<br />
<br />
====== From a Haskell executable ======<br />
<br />
#Make a DLL project in Visual Studio. It will create a <tt>.vcproj</tt> and <tt>.sln</tt> files for you. Add your C++ source files to this project. <br />
#Create a <tt>.def</tt> file for your DLL. It might look like<tt><br>LIBRARY MyDLL<br>EXPORTS<br>&nbsp;&nbsp;&nbsp;&nbsp;function1<br>&nbsp;&nbsp;&nbsp;&nbsp;function2<br></tt> where <tt>function1</tt> and <tt>function2</tt> are the names of the C++ functions that you want to invoke from Haskell (there can be more of them, of course), <tt>MyDLL</tt> is the name of your DLL.<br />
#Create an import library that can be used by <tt>ghc:<br>dlltool -d MyDLL.def -l libMyDLL.a</tt> <br />
#Link your Haskell project, adding the library:<tt><br>ghc --make main.hs -optl-lMyDLL -optl-L.<br></tt>''mind the dot at the end of the command line!''<br> (<tt>[https://ghc.readthedocs.io/en/latest/phases.html#forcing-options-to-a-particular-phase -optl]</tt> switch passes its argument as an option to the linker).<br />
<br />
=== GHCi Hanging Issues ===<br />
<br />
==== GHCi hangs after "Loading package base ... linking ... done." ====<br />
<br />
On a small number of systems GHCi will fail to start, hanging after loading the base package. The "Prelude>" prompt is never reached.<br />
<br />
This is believed to be due to a bug in Windows thought to affect tablet PCs, although the details are not fully understood.<br />
<br />
A workaround is to open a command prompt, enter "chcp 28591" - if this hangs hit Ctrl-C - and then run "ghci". Some users may find this [http://support.microsoft.com/kb/925271 hotfix] useful.<br />
<br />
=== A console window opens when my application is supposed to be GUI only ===<br />
<br />
Windows has several different "subsystems", the default subsystem which the mingw linker uses is console, so that stdout/stderr can be printed on screen and stdin be read from the console window.<br />
<br />
This can be solved by giving the option -optl-mwindows with the compile command:<br />
ghc --make -optl-mwindows MyProgramWithGUI.lhs<br />
With this option, the option -mwindows is passed to the linker.<br />
<br />
Caveat: attempting to read from stdin with -mwindows set may cause a runtime error, any output on stdout/stderr will be lost.<br />
<br />
== .NET/JVM Availability ==<br />
<br />
=== Why isn't GHC available for .NET or on the JVM? ===<br />
<br />
It would make a lot of sense to give GHC a .NET or JVM back end, and it's a<br />
question that comes up regularly. The reason that we haven't done it<br />
here, at GHC HQ, is because it's a more substantial undertaking than<br />
might at first appear (see below). Furthermore, it'd permanently add a<br />
complete new back-end platform for us to maintain. Given our rather<br />
limited development effort, we have so far not bitten<br />
the bullet, and we have no immediate plans to do so.<br />
<br />
It would be a good, well-defined project for someone else to tackle, and<br />
we would love to see it done. There is some good groundwork already done:<br />
<br />
* Ashley Yakeley worked on a [http://sourceforge.net/projects/jvm-bridge/ Haskell-JVM bridge]<br />
<br />
* Sigbjorn Finne did a simple interop implementation ([http://hackage.haskell.org/package/hs-dotnet the hs-dotnet package]) that allows a Haskell program to be compiled to native code (as now) but to call .NET programs via a variant of the FFI. I don't think this work is in active use, and I'd be surprised if it worked out of the box, but it could probably be revived with modest effort<br />
<br />
* Andre Santos and his colleagues at UFPE in Brazil are working on a .NET back end, that generates CLR IL, though I don't know where they are up to.<br />
<br />
* Nigel Perry and Oliver Hunt have a Haskell.NET prototype that works using GHC to compile to Core, and then compiling Core to NET. I'm not sure what stage it is at.<br />
<br />
* GHC.Net would be extra attractive if there was a Visual Studio integration for GHC. Substantial progress on this has been made in 2004 by Simon Marlow, Krasimir Angelov, and Andre Santos and colleagues.<br />
<br />
* Brian Alliet created a patch for GHC called LambdaVM that compiles programs into JVM bytecode. [http://wiki.brianweb.net/LambdaVM/LambdaVM]<br />
<br />
* Not GHC but [[UHC]]: the Jazy backend of UHC generates Java class files to allow Haskell programs to run on the Java Virtual Machine (JVM). Jazy is [http://www.cs.uu.nl/wiki/bin/view/Ehc/UhcJazyDocumentation#2_Status not fully functional yet].<br />
<br />
<br />
There may be others that I don't know of. If anyone wants to join in<br />
this effort, do contact the above folk. And please keep us informed!<br />
<br />
Here's a summary of why it's a non-trivial thing to do (using .NET language, but it mostly applies to the JVM too):<br />
<br />
* The first thing is to generate native CLR Intermediate Language (IL). That's not really hard. Requires thinking about representations for thunks and functions, and it may not be particularly efficient, but it can surely be done. <br />
: An open question is about whether to generate ''verifiable'' IL or not. The trouble here is that Haskell's type system is more expressive than the CLR's in some ways, notably the use of higher-kinded type variables. So, to generate verifiable IL one is bound to need some run-time casts, and it's not clear how to minimise these.<br />
<br />
At first blush this is ''all'' you need do. But it isn't!<br />
<br />
* Next, you need to think about how to inter-operate with .NET libraries. You don't really want to write "foreign import..." for each and every import. You'd like GHC to read the CLR meta-data directly. But there are lots of tricky issues here; see the paper that Mark Shields and I wrote about "Object-oriented style overloading for Haskell".<br />
<br />
* A closely-related question is this: how to make the type systems of Java/.NET and Haskell "line up"? For example, when importing a Java procedure, what is the Haskell type that corresponds to its .NET/JVM type? How do you sub-class a .NET class in Haskell? For example [http://research.microsoft.com/en-us/um/people/simonpj/papers/oo-haskell/index.htm Object-Oriented Style Overloading for Haskell] gives one "take" on the subject, but there are plenty of other possibilities. <br />
<br />
* Now you need to figure out how to implement GHC's primitive operations:<br />
** the I/O monad<br />
** arbitrary precision arithmetic<br />
** concurrency<br />
** exceptions<br />
** finalisers<br />
** stable pointers<br />
** [[Software transactional memory]]<br />
<br />
:: Not all of these are necessary, of course, but many are used in the libraries. The CLR supports many of them (e.g. concurrency) but with a very different cost model.<br />
<br />
* Last, you have to figure out what to do for the libraries. GHC has a pretty large library, and you either have to implement the primops on which the library is based (see previous point), or re-implement it. For example, GHC's implementation of I/O uses mutable state, concurrency, and more besides. For each module, you need to decide either to re-implement it using .NET primitives, or to implement the stuff the module is based on.<br />
<br />
These challenges are mostly broad rather than deep. But to get a<br />
production quality implementation that runs a substantial majority of<br />
Haskell programs "out of the box" requires a decent stab at all of them.<br />
<br />
== Mac OS X-related ==<br />
<br />
=== Linking with GHC ===<br />
<br />
==== Linking with ghc produces <tt>ld: Undefined symbols: _sprintf$LDBLStub ...</tt> ====<br />
<br />
This happens on a PowerPC Mac OS X 10.4 if gcc-3.3 is the default compiler and you try to compile with a ghc that has been built with gcc-4.0. For example:<br />
<br />
$ cat t2.hs <br />
module Main where<br />
main = putStr ("t2: Hello trac 1066 2007-Feb-17 19.48\n")<br />
$ gcc --version<br />
gcc (GCC) 3.3 20030304 (Apple Computer, Inc. build 1819)<br />
...<br />
$ ghc --make t2.hs<br />
[1 of 1] Compiling Main ( t2.hs, t2.o )<br />
Linking t2 ...<br />
ld: Undefined symbols:<br />
_sprintf$LDBLStub<br />
_fprintf$LDBLStub<br />
_vfprintf$LDBLStub<br />
_sscanf$LDBLStub<br />
$ <br />
<br />
To correct this, set the default compiler to gcc-4.0 (<tt>sudo gcc_select 4.0</tt>) or include linking options <tt>-lHSrts -lSystemStubs</tt> in that order on the ghc command:<br />
<br />
$ ghc --make t2.hs -lHSrts -lSystemStubs<br />
[1 of 1] Skipping Main ( t2.hs, t2.o )<br />
Linking t2 ...<br />
$ <br />
<br />
The command<br />
<br />
for l in <ghc installation directory>/lib/ghc-<ghc version>/*.a; do nm $l 2>&1 | if grep LDBLStub 1>/dev/null; then echo $l; fi; done<br />
<br />
prints the list of libraries that may be needed instead of or in addition to <tt>-lHSrts</tt> before <tt>-lSystemStubs</tt> on the ghc command. For example:<br />
<br />
$ for l in /Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/*.a; do nm $l 2>&1 | if grep LDBLStub 1>/dev/null; then echo $l; fi; done<br />
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSX11_cbits.a<br />
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts.a<br />
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_debug.a<br />
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_p.a<br />
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_thr.a<br />
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_thr_debug.a<br />
/Users/thorkilnaur/tn/install/ghc-HEAD-for-1066-20070211_1657/lib/ghc-6.7.20070209/libHSrts_thr_p.a<br />
$ <br />
<br />
[http://hackage.haskell.org/trac/ghc/ticket/1066] has additional details.<br />
<br />
=== Linking with C++ ===<br />
<br />
==== Linking with a C++ library gives: <tt>Undefined symbols: __Unwind_Resume</tt> ====<br />
<br />
You need to pass the <tt>-fexceptions</tt> to the linker. Use <tt>-optl -fexceptions</tt>.<br />
<br />
---------------------------------------<br />
= Running GHC =<br />
<br />
== Filenames Containing '+' ==<br />
<br />
=== GHC doesn't like filenames containing '+'. ===<br />
<br />
Indeed not. You could change <tt>+</tt> to <tt>p</tt> or <tt>plus</tt>.<br />
<br />
== Linking ==<br />
<br />
=== Why does linking take so long? ===<br />
<br />
Linking a small program should take no more than a few seconds. Larger programs can take longer, but even linking GHC itself only takes 3-4 seconds on our development machines.<br />
<br />
Long link times have been attributed to using Sun's linker on Solaris, as compared to GNU ld which appears to be much faster. So if you're on a Sun box, try switching to GNU ld. [http://www.haskell.org/pipermail/glasgow-haskell-users/2002-November/004477.html This article] from the mailing list has more information.<br />
<br />
One huge slowdown is also working on remote filesystem, e.g., nfs. <br />
Work on a local machine, preferably.<br />
<br />
You may also speed up linking by enabling dynamic linking with the <code>-dynamic</code> option of GHC or <code>--enable-executable-dynamic</code> of [[Cabal]].<br />
<br />
== Missing Include Files ==<br />
<br />
=== Why do I get errors about missing include files when compiling with -O or -prof? ===<br />
<br />
Certain options, such as -O, turn on via-C compilation, instead of using the native code generator. Include files named by -#include options or in foreign import declarations are only used in via-C compilation mode. See [http://www.haskell.org/ghc/docs/latest/html/users_guide/sec-ffi-ghc.html#finding-header-files Section 8.2.2.1, ´Finding Header files] for more details.<br />
<br />
== Compiling for Profiling ==<br />
<br />
=== How do I compile my program for profiling without overwriting the object files and hi files I've already built? ===<br />
<br />
You can select alternative suffixes for object files and interface files, so you can have several builds of the same code coexisting in the same directory. For example, to compile with profiling, you might do this:<br />
<br />
<pre><br />
ghc --make -prof -o foo-prof -osuf p.o -hisuf p.hi Main<br />
</pre><br />
<br />
See [http://www.haskell.org/ghc/docs/latest/html/users_guide/separate-compilation.html#options-output Section 4.6.4, ´Redirecting the compilation output(s)] for more details on the <tt>-osuf</tt> and <tt>-hisuf</tt> options.<br />
<br />
---------------------------------------<br />
= Syntax =<br />
<br />
== String Gaps ==<br />
<br />
=== I can't get string gaps to work ===<br />
<br />
If you're also using CPP, beware of the known pitfall with string gaps mentioned in [http://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#cpp-string-gaps Section 4.10.3.1, CPP and string gaps].<br />
<br />
---------------------------------------<br />
= GHCi =<br />
<br />
== Error Messages ==<br />
<br />
=== Missing Symbols ===<br />
<br />
==== GHCi complains about missing symbols like CC_LIST when loading a previously compiled .o file. ====<br />
<br />
This probably means the .o files in question were compiled for profiling (with -prof). Workaround: recompile them without profiling. We really ought to detect this situation and give a proper error message.<br />
<br />
=== Starting GHCi ===<br />
<br />
==== When I try to start ghci (probably one I compiled myself) it says <tt>ghc-5.02: not built for interactive use</tt> ====<br />
To build a working ghci, you need to build GHC 5.02 with itself; the above message appears if you build it with 4.08.X, for example. It'll still work fine for batch-mode compilation, though. Note that you really must build with exactly the same version of the compiler. Building 5.02 with 5.00.2, for example, may or may not give a working interactive system; it probably won't, and certainly isn't supported. Note also that you can build 5.02 with any older compiler, back to 4.08.1, if you don't want a working interactive system; that's OK, and supported.<br />
<br />
=== Duplicate Definitions ===<br />
<br />
==== I get an error message from GHCi about a "<tt>duplicate definition for symbol __module_registered</tt>" ====<br />
<br />
An error message like this:<br />
<br />
<pre><br />
GHCi runtime linker: fatal error: I found a duplicate definition for symbol<br />
__module_registered<br />
whilst processing object file<br />
/usr/local/lib/ghc-6.2/HSfgl.o<br />
</pre><br />
<br />
probably indicates that when building a library for GHCi (<tt>HSfgl.o</tt> in the above example), you should use the <tt>-x</tt> option to <tt>ld</tt>.<br />
<br />
== REPL Workarounds ==<br />
<br />
=== Why doesn't "x=1" work at the ghci prompt? ===<br />
<br />
Type<br />
<pre><br />
let x = 1<br />
</pre><br />
<br />
instead.<br />
<br />
From IRC: "But in general, it's tricky to define function interactively. You can do simple stuff easily enough: "let f x = x * x" or whatever; but for anything other than a simple one-liner, I usually stick it into a file and then load it with ghci.<br />
<br />
---------------------------------------<br />
= The Foreign Function Interface =<br />
<br />
== Blocking ==<br />
<br />
=== When do other Haskell threads get blocked by an FFI call? ===<br />
<br />
{| border="1" align="center"<br />
|<br />
! safe<br />
! unsafe<br />
|-<br />
! -threaded<br />
| NO <br />
| YES<br />
|-<br />
! no -threaded<br />
| YES<br />
| YES<br />
|}<br />
<br />
The <tt>-threaded</tt> flag (given when linking; see the <br />
[http://www.haskell.org/ghc/docs/latest/html/users_guide/flag-reference.html manual])<br />
allows other Haskell threads to run concurrently with a thread making an FFI call.<br />
This nice behaviour does not happen for foreign calls marked as `unsafe` (see<br />
the [https://www.haskell.org/onlinereport/haskell2010/haskellch8.html#x15-1490008 Foreign Function Interface description] in the Haskell 2010 Language Report).<br />
<br />
There used to be another modifier, <tt>threadsafe</tt>, which is now deprecated. Use `safe` instead.<br />
<br />
== Using Floats ==<br />
<br />
=== When I use a foreign function that takes or returns a float, it gives the wrong answer, or crashes. ===<br />
<br />
You should use the <tt>-#include</tt> option to bring the correct prototype into scope (see [http://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#options-C-compiler Section 4.10.5, ´Options affecting the C compiler (if applicable)]).<br />
<br />
== Propagating Run-time Errors as Exceptions ==<br />
<br />
=== How can I propagate a Haskell run-time error (e.g. pattern match failure) as an exception to a foreign caller of the Haskell function. ===<br />
<br />
If a runtime error occurs inside a DLL compiled by ghc (like <br />
"irrefutable pattern match failed" or exceptions caused by error),<br />
the application that called the DLL function dies. This is ok for <br />
development but unacceptable when it happens with a user sitting in <br />
front of the display. <br />
So the question is: Is there any way to catch and process runtime errors? <br />
I am looking for some way to map those errors to exceptions on the C++ <br />
side that can be caught if required. It would be ok to kill the Haskell <br />
runtime system and unload the DLL if necessary.<br />
<br />
Answer: The FFI doesn't provide any way to propagate exceptions from Haskell to <br />
the caller of a foreign export, because there's no standard way to do <br />
this. It is your responsibility to catch the exception in Haskell and <br />
return an appropriate error code to the caller. To raise a C++ <br />
exception, you would probably need another C++ wrapper around each <br />
foreign export, translating an error code into the C++ exception.<br />
<br />
== Calling C Procedures ==<br />
<br />
=== How do I call a C procedure from a Haskell program? ===<br />
<br />
First, you'll want to keep open <br />
the [http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi.html GHC user manual section on foreign function calling], and the <br />
[http://www.cse.unsw.edu.au/~chak/haskell/ffi/ Haskell FFI addendum].<br />
<br />
Now, let's assume you got this c-program ffi.c which writes THE answer to a file:<br />
<br />
<pre><br />
#include <stdlib.h><br />
#include <stdio.h><br />
<br />
write_answer(char *userfilename)<br />
{<br />
FILE *userfile;<br />
userfile=fopen(userfilename,"w");<br />
fprintf(userfile,"42");<br />
fclose(userfile);<br />
}<br />
</pre><br />
You also need a header file ffi.h.<br />
<pre><br />
void write_answer(char *userfilename)<br />
</pre><br />
Next Step: Write the according Haskell program to include the function<br />
<tt>write_answer</tt> in your Haskell code:<br />
<haskell><br />
{-# INCLUDE <ffi.h> #-}<br />
{-# LANGUAGE ForeignFunctionInterface #-}<br />
module Main where<br />
<br />
import Foreign<br />
import Foreign.C.String <br />
<br />
foreign import ccall "ffi.h write_answer" cwrite_answer :: CString -> IO ()<br />
<br />
write_answer :: String -> IO ()<br />
write_answer s = do<br />
s' <- newCString s<br />
cwrite_answer s'<br />
<br />
main = write_answer "ffi.dat"<br />
</haskell><br />
<br />
Now we get to compiling (assume that <tt>/tmp/ffi/</tt> is the current path).<br />
<pre><br />
cc -fPIC -c ffi.c<br />
ar rc libffi.a ffi.o<br />
ghc -lffi -L/tmp/ffi --make Main<br />
</pre><br />
And the resulting executable should write the file.<br />
<br />
The <tt>-fPIC</tt> parameter to the c compiler is not strictly necessary. <br />
But the result will help us in the next step which is to dynamically link the library for use in GHCi.<br />
<br />
== Compiling C Programs ==<br />
<br />
=== How do I compile my C program to use in GHCi? ===<br />
<br />
Suppose you got your c-program compiled (with <tt>-fPIC</tt> parameter) as described above. If you try to load your file <tt>Main.hs</tt> in GHCi you get an error similar to this:<br />
<pre><br />
Loading object (dynamic) ffi ... failed.<br />
Dynamic linker error message was:<br />
libffi.so: cannot open shared object file: No such file or directory<br />
Whilst trying to load: (dynamic) ffi<br />
</pre><br />
What you need is a shared library. To get it you compile once more:<br />
<pre><br />
cc -shared -o libffi.so ffi.o<br />
</pre><br />
And now it all works fine:<br />
<pre><br />
$ ghci -lffi -L/tmp/ffi Main.hs<br />
GHCi, version 6.8.2: http://www.haskell.org/ghc/ :? for help<br />
Loading package base ... linking ... done.<br />
Loading object (dynamic) ffi ... done<br />
final link ... done<br />
Ok, modules loaded: Main.<br />
Prelude Main> write_answer "test"<br />
Prelude Main> :! cat test<br />
42<br />
Prelude Main> <br />
</pre><br />
<br />
---------------------------------------<br />
<br />
= Input/Output =<br />
<br />
== Strings ==<br />
<br />
=== If I print out a string using <tt>putStr</tt>, and then attempt to read some input using <tt>hGetLine</tt>, I don't see the output from the <tt>putStr</tt>. ===<br />
<br />
The <tt>stdout</tt> handle is line-buffered by default, which means that output sent to the handle is only flushed when a newline (<tt>\n</tt>) is output, the buffer is full, or <tt>hFlush</tt> is called on the <tt>Handle</tt>. The right way to make the text appear without sending a newline is to use <tt>hFlush</tt>:<br />
<br />
<haskell><br />
import System.IO<br />
main = do<br />
putStr "how are you today? "<br />
hFlush stdout<br />
input <- hGetLine stdin<br />
process input<br />
</haskell><br />
<br />
You'll probably find that the behaviour differs when using GHCi: the hFlush isn't necessary to make the text appear. This is because in GHCi we turn off the buffering on stdout, because this is normally what you want in an interpreter: output appears as it is generated.<br />
<br />
=== If I use the above fix, but check for EOF with <tt>isEOF</tt> before prompting for user input, the above problem still happens (GHC 6.12.1) ===<br />
<br />
== Buffering on Handles ==<br />
<br />
=== If I explicitly set the buffering on a Handle to <tt>NoBuffering</tt> I'm not able to enter EOF by typing "Ctrl-D". ===<br />
<br />
This is a consequence of Unixy terminal semantics. Unix does line buffering on terminals in the kernel as part of the terminal processing, unless you turn it off. However, the Ctrl-D processing is also part of the terminal processing which gets turned off when the kernel line buffering is disabled. So GHC tries its best to get NoBuffering semantics by turning off the kernel line buffering, but as a result you lose Ctrl-D. C'est la vie.<br />
<br />
== FIFOs (Named Pipes) ==<br />
<br />
=== When I open a FIFO (named pipe) and try to read from it, I get EOF immediately. ===<br />
<br />
This is a consequence of the fact that GHC opens the FIFO in non-blocking mode. The behaviour varies from OS to OS: on Linux and Solaris you can wait for a writer by doing an explicit threadWaitRead on the file descriptor (gotten from <tt>Posix.handleToFd</tt>) before the first read, but this doesn't work on FreeBSD (although rumour has it that recent versions of FreeBSD changed the behaviour to match other OSs). A workaround for all systems is to open the FIFO for writing yourself, before (or at the same time as) opening it for reading.<br />
<br />
== Importing Functions Returning Char/Short ==<br />
<br />
=== When I foreign import a function that returns char or short, I get garbage back. ===<br />
<br />
This is a known bug in GHC versions prior to 5.02.2. GHC doesn't mask out the more significant bits of the result. It doesn't manifest with gcc 2.95, but apparently shows up with g++ and gcc 3.0.<br />
<br />
---------------------------------------<br />
= Optimization =<br />
<br />
== Garbage Collection ==<br />
<br />
=== My program spent too much time doing garbage collection ===<br />
<br />
Add the "+RTS -A10m" option to the command line when you run your<br />
program. This sets the allocation area size used by the garbage<br />
collector to 10M, which should sufficiently decrease GC times (the<br />
default is 256K; see the section "Running a compiled program" in the<br />
users' guide). You can also add to your program C module containing<br />
statement<br />
<br />
char *ghc_rts_opts = "-A10m";<br />
<br />
to force your program to use this setting on each run.<br />
<br />
== Subexpression Elimination ==<br />
<br />
=== Does GHC do common subexpression elimination? ===<br />
<br />
In general, GHC does not do CSE.<br />
It'd be a relatively easy pass for someone to add, but it can cause space leaks. And it can replace two strictly-evaluated calls with one lazy thunk:<br />
<haskell><br />
let { x = case e of ...; y = case e of ... } in ...<br />
==><br />
let { v = e; x = case v of ...; y = case v of ... } in ...<br />
</haskell><br />
Now <hask>v</hask> is allocated as a thunk. (Of course, that might be well worth it if <hask>e</hask> is an expensive expression.)<br />
<br />
Instead GHC does "opportunistic CSE". If you have <br />
<haskell><br />
let x = e in .... let y = e in ....<br />
</haskell><br />
then it'll discard the duplicate binding. This can still cause space<br />
leaks but it guarantees never to create a new thunk, and it turns out <br />
to be very useful in practice.<br />
<br />
Bottom line: if you care about sharing, do it yourself using <hask>let</hask> <br />
or <hask>where</hask>.<br />
<br />
== Laziness ==<br />
<br />
=== When can I rely on full laziness? ===<br />
<br />
Consider this program<br />
<haskell><br />
f x y = let r = expensive x <br />
in r+y<br />
g vs = map (f 2) vs<br />
</haskell><br />
Since r depends only on x, you might hope that <tt>(expensive 2)</tt> is computed just once. And that is indeed what will happen if you write<br />
<haskell><br />
f_opt x = let r = expensive x <br />
in \y -> r+y<br />
g_opt vs = map (f_opt 2) vs<br />
</haskell><br />
It's easy enough for a compiler to transform f into f_opt. (This is called the "full laziness" transformation.) BUT in the cases when f is fully-applied, f_opt is *less* efficient than f; consider<br />
<haskell><br />
h ys zs = zipWith f_opt ys zs<br />
</haskell><br />
Reason: it's much less efficient to have separate lambdas <tt>\x-> let ... in \y -> e</tt> than one compound lambda <tt>\xy -> e</tt>.<br />
<br />
So the best way to transform f depends on how it is used. When it's used locally and just once, GHC inlines it at the call site and all is good. But when it's exported or called many times, GHC's full laziness transformation uses the following rule: never "float" a let <em>between</em> two lambdas. So it won't transform f into f_opt. <br />
<br />
On the other hand, if you write f_opt, GHC will keep it that way. Furthermore, if a sub-expression can be floated right out of a complete lambda group, GHC will float it out. For example<br />
<haskell><br />
f x vs = map (\y -> y + expensive x) vs<br />
</haskell><br />
Here, the <tt>(expensive x)</tt> can be floated out of the <tt>\x->...</tt> lambda without separating two lambdas, and the full laziness transfom will do just that.<br />
<br />
---------------------------------------<br />
<br />
= Miscellaneous =<br />
<br />
== Upgrading GHC ==<br />
<br />
=== Do I have to recompile all my code if I upgrade GHC? ===<br />
<br />
Yes. There are two reasons for this:<br />
<br />
* GHC does a lot of cross-module optimisation, so compiled code will include parts of the libraries it was compiled against (including the Prelude), so will be deeply tied to the actual version of those libraries it was compiled against. When you upgrade GHC, the libraries may change; even if the external interface of the libraries doesn't change, sometimes internal details may change because GHC optimised the code in the library differently. <br />
* We sometimes change the ABI (application binary interface) between versions of GHC. Code compiled with one version of GHC is not necessarily compatible with code compiled by a different version, even if you arrange to keep the same libraries.<br />
<br />
== Shared Libraries ==<br />
<br />
=== Why doesn't GHC use shared libraries? ===<br />
<br />
GHC does provide shared libraries, currently only on MacOS X. We are working on making shared libraries work on other platforms.<br />
<br />
However, GHC-compiled libraries are very tightly coupled, which means it's unlikely you'd be able to swap out a shared library for a newer version unless it was compiled with exactly the same compiler and set of libraries as the old version.<br />
<br />
== Debugging ==<br />
<br />
=== My program is failing with head [], or an array bounds error, or some other random error, and I have no idea how to find the bug. Can you help? ===<br />
<br />
Try the [http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci-debugger.html GHCi Debugger], in particular look at the section on "Debugging Exceptions".<br />
<br />
Alternatively, compile your program with <tt>-prof -auto-all</tt> (make sure you have the profiling libraries installed), and run it with <tt>+RTS -xc -RTS</tt> to get a ´stack trace at the point at which the exception was raised. See [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-debugging Section 4.14.4, ´RTS options for hackers, debuggers, and over-interested souls] for more details.<br />
<br />
== Increasing Heap Size ==<br />
<br />
=== How do I increase the heap size permanently for a given binary? ===<br />
<br />
See [http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-hooks Section 4.14.5, ´´Hooks to change RTS behaviour].<br />
<br />
== Compiling for Parallel Execution ==<br />
<br />
=== I'm trying to compile my program for parallel execution with the -parallel, and GHC complains with an error like 'failed to load interface file for Prelude'. ===<br />
<br />
GHC doesn't ship with support for parallel execution; that support is provided separately by the [http://www.macs.hw.ac.uk/~dsg/gph/ GPH] project.<br />
<br />
== Using Unsafe Functions ==<br />
<br />
=== When is it safe to use [[unsafe functions]] such as <hask>unsafePerformIO</hask>? ===<br />
<br />
We'll give two answers to this question, each of which may be helpful. These criteria are not rigorous in any real sense (you'd need a formal semantics for Haskell in order to give a proper answer to this question), but should give you a feel for the kind of things you can and cannot do with unsafePerformIO.<br />
<br />
* It is safe to implement a function or API using unsafePerformIO if you could imagine also implementing the same function or API in Haskell without using unsafePerformIO (forget about efficiency, just consider the semantics).<br />
* In pure Haskell, the value of a function depends only on the values of its arguments (and free variables, if it has any). If you can implement the function using unsafePerformIO and still retain this invariant, then you're probably using unsafePerformIO in a safe way. Note that you need only consider the observable values of the arguments and result.<br />
<br />
For more information, see [http://www.haskell.org/pipermail/glasgow-haskell-users/2002-July/003681.html this thread].<br />
<br />
== Using Finalizers ==<br />
<br />
=== I can't get finalizers to work properly. My program sometimes just prints <tt><<loop>></tt>. ===<br />
<br />
Chances are that your program is trying to write a message to stdout or stderr in the finalizer. Handles have finalizers themselves, and since finalizers don't keep other finalized values alive, the stdout and stderr Handles may be finalized before your finalizer runs. If this happens, your finalizer will block on the handle, and probably end up receiving a NonTermination exception (which is printed as <tt><<loop>></tt>).<br />
<br />
== Extensible Records ==<br />
<br />
=== Does GHC implement any kind of extensible records? ===<br />
<br />
No, extensible records are not implemented in GHC. [http://www.haskell.org/hugs/ Hugs] implements TRex, one extensible record variant. The problem is that the record design space is large, and seems to lack local optima. And all reasonable variants break backward compatibility. As a result, nothing much happens.<br />
<br />
== Using Extra GCC/Linker Options ==<br />
<br />
=== How can I make GHC always use some extra gcc or linker option? ===<br />
<br />
If you want to *always* use an extra option then you can edit the package configuration for the 'rts' or 'base' package since these packages are used by every program that you compile with GHC. You might want to do this if you had installed something that ghc needs but into a non-standard directory, thus requiring special compilation or linking options.<br />
<br />
All you need to do is to dump out the configuration into a human readable form, edit it and re-register the modified package configuration. The exact commands to do that are below, but first here are the fields in the file that you might want to modify:<br />
<br />
; include-dirs: directories to search for .h files<br />
; library-dirs: directories to search for libraries<br />
; extra-libraries: extra C libs to link with<br />
; cc-options: extra flags to pass to gcc when compiling C code or assembly<br />
; ld-options: extra flags to pass to '''gcc''' when linking<br />
<br />
to edit the rts package (or base) confiuration just do:<br />
# <tt>ghc-pkg describe rts > rts.package.conf</tt><br />
# edit <tt>rts.package.conf</tt> with your favourite text editor<br />
# <tt>ghc-pkg update rts.package.conf</tt><br />
<br />
On Unix systems and Windows, some options can also be set with environment variables such as LIBRARY_PATH and C_INCLUDE_PATH.</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Keywords&diff=63362Keywords2020-07-23T05:54:47Z<p>Ysangkok: /* forall */ better link for forall introduction</p>
<hr />
<div>This page lists all Haskell keywords, feel free to edit. [[Hoogle]] searches will return results from this page. Please respect the Anchor macros.<br />
<br />
For additional information you might want to look at [http://www.haskell.org/onlinereport/haskell2010/ the Haskell 2010 report].<br />
<br />
== ! ==<br />
<br />
Whenever a data [[constructor]] is applied, each argument to the<br />
constructor is evaluated if and only if the corresponding type in the<br />
algebraic data[[type]] declaration has a strictness flag, denoted by an<br />
exclamation point. For example:<br />
<br />
<haskell><br />
data STList a <br />
= STCons a !(STList a) -- the second argument to STCons will be <br />
-- evaluated before STCons is applied<br />
| STNil<br />
</haskell><br />
<br />
to illustrate the difference between strict versus lazy constructor<br />
application, consider the following:<br />
<br />
<haskell><br />
stList = STCons 1 undefined<br />
lzList = (:) 1 undefined<br />
stHead (STCons h _) = h -- this evaluates to undefined when applied to stList<br />
lzHead (h : _) = h -- this evaluates to 1 when applied to lzList<br />
</haskell><br />
<br />
! is also used in the [https://downloads.haskell.org/~ghc/7.8.4/docs/html/users_guide/bang-patterns.html "bang patterns"] (GHC extension), to indicate<br />
strictness in patterns:<br />
<br />
<haskell><br />
f !x !y = x + y<br />
</haskell><br />
<br />
== ' ==<br />
* Character literal: <hask>'a'</hask><br />
* [[Template Haskell]]: Name of a (value) variable or data constructor: <hask>'length</hask>, <hask>'Left</hask><br />
* (in types, GHC specific) Promoted data constructor: <hask>'True</hask><br />
<br />
== <nowiki>''</nowiki> ==<br />
* [[Template Haskell]]: Name of a type constructor or class: <hask>''Int</hask>, <hask>''Either</hask>, <hask>''Show</hask><br />
<br />
== - ==<br />
This operator token is magic/irregular in the sense that<br />
<haskell>(- 1)</haskell><br />
is parsed as the negative integer -1, rather than as an operator [[Section of an infix operator|section]], as it would be for any other operator:<br />
<haskell>(* 1) :: Num a => a -> a</haskell><br />
<haskell>(++ "foo") :: String -> String</haskell><br />
<br />
It is syntactic sugar for the <hask>negate</hask> function in Prelude. See [[unary operator]].<br />
If you want the section, you can use the <hask>subtract</hask> function or <hask>(+(-1))</hask>.<br />
<br />
== -- ==<br />
<br />
Starts a single-line comment, unless immediately followed by an operator character other than <hask>-</hask>:<br />
<br />
<haskell><br />
main = print "hello world" -- this is a comment<br />
--this is a comment as well<br />
---this too<br />
foobar --+ this_is_the_second_argument_of_the_dash_dash_plus_operator<br />
</haskell><br />
<br />
The multi-line variant for comments is <hask>{- comment -}</hask>.<br />
<br />
== -< ==<br />
[http://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#arrow-notation Arrow notation]<br />
<br />
== -<< ==<br />
[http://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#arrow-notation Arrow notation]<br />
<br />
== -> ==<br />
<br />
* The function type constructor:<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
* In lambda functions:<br />
<haskell><br />
\x -> x + 1<br />
</haskell><br />
<br />
* To denote alternatives in case statements:<br />
<haskell><br />
case Just 3 of<br />
Nothing -> False<br />
Just x -> True<br />
</haskell><br />
<br />
or with LambdaCase:<br />
<haskell><br />
(\ case 1 -> 0<br />
; _ -> 1 )<br />
</haskell><br />
<br />
or with MultiWayIf:<br />
<haskell><br />
if | 1 == 0 -> 1 <br />
| 1 == 2 -> 2 <br />
| otherwise -> 3<br />
</haskell><br />
<br />
* On the kind level (GHC specific):<br />
<haskell><br />
ghci> :kind (->)<br />
(->) :: * -> * -> *<br />
</haskell><br />
<br />
* [[Functional dependencies]]<br />
<haskell><br />
-- This examples assumes that each type 'c' can "contain" only one type<br />
-- i.e. type 'c' uniquely determines type 'elt'<br />
class Contains c elt | c -> elt where<br />
...<br />
</haskell><br />
<br />
* [[View patterns]]<br />
<br />
== :: ==<br />
<br />
Read as "has type":<br />
<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
"Length has type list-of-'a' to Int"<br />
<br />
Or "has kind" (GHC specific):<br />
<br />
<haskell><br />
Either :: * -> * -> *<br />
</haskell><br />
<br />
== ; ==<br />
* Statement separator in an explicit block (see [[layout]])<br />
<br />
== <- ==<br />
<br />
* In do-notation, "draw from":<br />
<haskell><br />
do x <- getChar<br />
putChar x<br />
</haskell><br />
<br />
* In list comprehension generators, "in":<br />
<haskell><br />
[ (x,y) | x <- [1..10], y <- ['a'..'z'] ]<br />
</haskell><br />
<br />
* In [[pattern guard]]s, "matches":<br />
<haskell><br />
f x y | Just z <- g x = True<br />
| otherwise = False<br />
</haskell><br />
<br />
== , ==<br />
<br />
Separator in lists, tuples, records.<br />
<br />
<haskell><br />
[1,2,3]<br />
(1,2,3)<br />
Point {x = 1, y = 2}<br />
</haskell><br />
<br />
In list comprehensions before generators, "and" (the first comma after <code>|</code>):<br />
<haskell><br />
[ (x,y) | x <- [1..10], y <- ['a'..'z'], x > 42 ]<br />
</haskell><br />
<br />
In list comprehensions before Boolean tests, "when" (the second comma after <code>|</code>):<br />
<haskell><br />
[ (x,y) | x <- [1..10], y <- ['a'..'z'], x > 42 ]<br />
</haskell><br />
<br />
In guards inside case expressions, "and when":<br />
<haskell><br />
case [1,3,9] of xs | (x:ys) <- xs, (y:_) <- ys, let z=x+1, z /= y -> [x,y,z]<br />
</haskell><br />
<br />
In module import and export lists:<br />
<br />
<haskell><br />
module MyModule<br />
( MyData (C1,C2)<br />
, myFun ) where<br />
<br />
import MyModule (MyData (C1,C2), myFun)<br />
</haskell><br />
<br />
== = ==<br />
Used in definitions.<br />
<br />
<haskell><br />
x = 4<br />
</haskell><br />
<br />
Also in pattern-matching records:<br />
<br />
<haskell><br />
case point of<br />
Point {x = x0, y = y0} -> f x0 y0<br />
</haskell><br />
<br />
== => ==<br />
<br />
Used to indicate instance contexts, for example:<br />
<br />
<haskell><br />
sort :: Ord a => [a] -> [a]<br />
</haskell><br />
<br />
== > ==<br />
<br />
In a Bird's style [[Literate_programming|Literate Haskell file]], the > character is used to introduce a code line.<br />
<br />
<haskell><br />
comment line<br />
<br />
> main = print "hello world"<br />
</haskell><br />
<br />
== ? ==<br />
<br />
* [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#implicit-parameters Implicit parameters]<br />
<br />
<haskell><br />
ghci> :t ?foo ++ "bar"<br />
?foo ++ "bar" :: (?foo::[Char]) => [Char]<br />
</haskell><br />
<br />
== # ==<br />
<br />
* [https://downloads.haskell.org/~ghc/7.6.2/docs/html/users_guide/syntax-extns.html MagicHash]<br />
<br />
== * ==<br />
<br />
* Is an ordinary operator name on the value level<br />
<br />
* On the [[kind]] level: The kind of boxed types (GHC-specific) <br />
<br />
<haskell><br />
ghci> :kind Int<br />
Int :: *<br />
</haskell><br />
<br />
== @ ==<br />
<br />
Patterns of the form <hask>var@pat</hask> are called as-patterns, and allow one to<br />
use <hask>var</hask> as a name for the value being matched by <hask>pat</hask>. For example:<br />
<haskell><br />
case e of { xs@(x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
let { xs = e } in<br />
case xs of { (x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
== [|, |] ==<br />
* [[Template Haskell]]<br />
** Expression quotation: <hask> [| print 1 |] </hask><br />
** Declaration quotation: <hask> [d| main = print 1 |] </hask><br />
** Type quotation: <hask> [t| Either Int () |] </hask> <br />
** Pattern quotation: <hask> [p| (x,y) |] </hask><br />
** [[Quasiquotation]]: <hask> [nameOfQuasiQuoter| ... |] </hask><br />
<br />
== \ ==<br />
The backslash "\" is used<br />
<br />
* in multiline strings<br />
<haskell><br />
"foo\<br />
\bar"<br />
</haskell><br />
<br />
* in lambda functions<br />
<haskell><br />
\x -> x + 1<br />
</haskell><br />
<br />
<br />
== _ ==<br />
<br />
Patterns of the form _ are wildcards and are useful when some part of a<br />
pattern is not referenced on the right-hand-side. It is as if an<br />
identifier not used elsewhere were put in its place. For example,<br />
<br />
<haskell><br />
case e of { [x,_,_] -> if x==0 then True else False }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
case e of { [x,y,z] -> if x==0 then True else False }<br />
</haskell><br />
<br />
<br />
<br />
<br />
<br />
== ` ==<br />
<br />
A function enclosed in back ticks "`" can be used as an infix operator.<br />
<br />
<haskell>2 `subtract` 10</haskell><br />
is the same as<br />
<haskell>subtract 2 10</haskell><br />
<br />
== {, } ==<br />
* Explicit block (disable [[layout]]), possibly with ";" .<br />
<br />
* Record update notation<br />
<haskell><br />
changePrice :: Thing -> Price -> Thing<br />
changePrice x new = x { price = new }<br />
</haskell><br />
<br />
* Comments (see below)<br />
<br />
== {-, -} ==<br />
<br />
Everything between "{-" followed by a space and "-}" is a block comment.<br />
<br />
<haskell><br />
{-<br />
hello<br />
world<br />
-}<br />
</haskell><br />
<br />
== | ==<br />
<br />
The "pipe" is used in several places<br />
<br />
* Data type definitions, "or"<br />
<haskell><br />
data Maybe a = Just a | Nothing<br />
</haskell><br />
<br />
* List comprehensions, "for" (as in, "list of <code>a*a</code> for <code>a</code> in <code>[1..]</code>)<br />
<haskell><br />
squares = [a*a | a <- [1..]]<br />
</haskell><br />
<br />
* Guards, "when"<br />
<haskell><br />
safeTail x | null x = []<br />
| otherwise = tail x<br />
</haskell><br />
<br />
* [[Functional dependencies]], "where"<br />
<haskell><br />
class Contains c elt | c -> elt where<br />
...<br />
</haskell><br />
<br />
== ~ ==<br />
<br />
* Lazy pattern bindings. Matching the pattern <hask>~pat</hask> against a value always succeeds, and matching will only diverge when one of the variables bound in the pattern is used.<br />
<br />
<haskell><br />
f1, f2 :: Maybe Int -> String<br />
f1 x = case x of <br />
Just n -> "Got it"<br />
f2 x = case x of<br />
~(Just n) -> "Got it"<br />
<br />
(+++), (++++) :: (a -> b) -> (c -> d) -> (a, c) -> (b, d) <br />
(f +++ g) ~(x, y) = (f x, g y)<br />
(f ++++ g) (x, y) = (f x, g y)<br />
</haskell><br />
<br />
Then we have:<br />
<br />
<haskell><br />
f1 Nothing<br />
Exception: Non-exhaustive patterns in case<br />
<br />
f2 Nothing<br />
"Got it"<br />
<br />
(const 1 +++ const 2) undefined<br />
(1,2)<br />
<br />
(const 1 ++++ const 2) undefined<br />
Exception: Prelude.undefined<br />
</haskell><br />
<br />
For more details see [http://en.wikibooks.org/wiki/Haskell/Laziness#Lazy_pattern_matching the Haskell Wikibook].<br />
<br />
* Equality constraints. Assert that two types in a context must be the same:<br />
<br />
<haskell><br />
example :: F a ~ b => a -> b<br />
</haskell><br />
<br />
Here the type "F a" must be the same as the type "b", which allows one to constrain polymorphism (especially where type families are involved), but to a lesser extent than functional dependencies. See [[Type_families#Equality_constraints|Type Families]].<br />
<br />
== as ==<br />
<br />
Renaming module imports. Like <hask>qualified</hask> and <hask>hiding</hask>, <hask>as</hask> is not a reserved word but may be used as function or variable name.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
main = print (M.empty :: M.Map Int ())<br />
</haskell><br />
<br />
== <span id="case">case</span>, <span id="of">of</span> ==<br />
<br />
A case expression has the general form<br />
<br />
<haskell><br />
case e of { p1 match1 ; ... ; pn matchn }<br />
</haskell><br />
<br />
where each <code>match</code><sub>i</sub> is of the general form<br />
<br />
<haskell><br />
| g1 -> e1<br />
...<br />
| gm -> em<br />
where decls<br />
</haskell><br />
<br />
Each alternative consists of patterns <code>p</code><sub>i</sub> and their matches, <code>match</code><sub>i</sub>. Each<br />
<code>match</code><sub>i</sub> in turn consists of a sequence of pairs of guards <code>g</code><sub>ij</sub> and bodies <code>e</code><sub>ij</sub><br />
(expressions), followed by optional bindings (<code>decls</code><sub>i</sub>) that scope over all<br />
of the guards and expressions of the alternative. An alternative of the<br />
form<br />
<br />
<haskell><br />
pat -> exp where decls<br />
</haskell><br />
<br />
is treated as shorthand for:<br />
<br />
<haskell><br />
pat | True -> exp<br />
where decls<br />
</haskell><br />
<br />
A case expression must have at least one alternative and each<br />
alternative must have at least one body. Each body must have the same<br />
type, and the type of the whole expression is that type.<br />
<br />
A case expression is evaluated by pattern matching the expression <code>e</code><br />
against the individual alternatives. The alternatives are tried<br />
sequentially, from top to bottom. If <code>e</code> matches the pattern in the<br />
alternative, the guards for that alternative are tried sequentially from<br />
top to bottom, in the environment of the case expression extended first<br />
by the bindings created during the matching of the pattern, and then by<br />
the <code>decls</code><sub>i</sub>&nbsp; in the <code>where</code> clause associated with that alternative. If one<br />
of the guards evaluates to <code>True</code>, the corresponding right-hand side is<br />
evaluated in the same environment as the guard. If all the guards<br />
evaluate to <code>False</code>, matching continues with the next alternative. If no<br />
match succeeds, the result is _|_.<br />
<br />
== class ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html#class-decls class declaration] <br />
introduces a new type class and the overloaded operations that must be<br />
supported by any type that is an instance of that class.<br />
<haskell><br />
class Num a where<br />
(+) :: a -> a -> a<br />
negate :: a -> a<br />
</haskell><br />
<br />
== data ==<br />
<br />
The [http://haskell.org/onlinereport/decls.html#user-defined-datatypes data] <br />
declaration is how one introduces new algebraic data [[type]]s into<br />
Haskell. For example:<br />
<br />
<haskell><br />
data Set a = NilSet <br />
| ConsSet a (Set a)<br />
</haskell><br />
<br />
Another example, to create a datatype to hold an [[Abstract_syntax_tree|abstract syntax tree]] for an expression, one could use:<br />
<br />
<haskell><br />
data Exp = Ebin Operator Exp Exp <br />
| Eunary Operator Exp <br />
| Efun FunctionIdentifier [Exp] <br />
| Eid SimpleIdentifier<br />
</haskell><br />
<br />
where the [[type]]s <code>Operator, FunctionIdentifier</code> and <code>SimpleIdentifier</code> are defined elsewhere. <br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
== data family ==<br />
Declares a datatype family (see [[type families]]). GHC language extension.<br />
<br />
== data instance ==<br />
Declares a datatype family instance (see [[type families]]). GHC language extension.<br />
<br />
<br />
== default ==<br />
<br />
Ambiguities in the class Num are most common, so Haskell provides<br />
a way to resolve them---with a default declaration:<br />
<br />
<haskell><br />
default (Int)<br />
</haskell><br />
<br />
Only one default declaration is permitted per module, and its effect is<br />
limited to that module. If no default declaration is given in a module<br />
then it assumed to be:<br />
<br />
<haskell><br />
default (Integer, Double)<br />
</haskell><br />
<br />
== deriving ==<br />
<br />
data and newtype declarations contain an optional deriving form. If the<br />
form is included, then derived instance declarations are automatically<br />
generated for the datatype in each of the named classes.<br />
<br />
[http://haskell.org/onlinereport/decls.html#derived-decls Derived instances] provide convenient commonly-used operations for user-defined<br />
datatypes. For example, derived instances for datatypes in the class Eq<br />
define the operations == and /=, freeing the programmer from the need to<br />
define them.<br />
<br />
<haskell><br />
data T = A<br />
| B<br />
| C<br />
deriving (Eq, Ord, Show)<br />
</haskell><br />
<br />
In the case of newtypes, GHC extends this mechanism to [[Cunning Newtype Deriving]].<br />
<br />
== deriving instance ==<br />
<br />
Standalone deriving (GHC language extension).<br />
<br />
<haskell><br />
{-# LANGUAGE StandaloneDeriving #-}<br />
data A = A<br />
<br />
deriving instance Show A<br />
</haskell><br />
<br />
== do ==<br />
<br />
Syntactic sugar for use with monadic expressions. For example:<br />
<br />
<haskell><br />
do { x ; result <- y ; foo result }<br />
</haskell><br />
<br />
is shorthand for:<br />
<br />
<haskell><br />
x >> <br />
y >>= \result -><br />
foo result<br />
</haskell><br />
<br />
== forall ==<br />
<br />
This is a GHC/Hugs extension, and as such is not portable Haskell 98/2010. <br />
It is only a reserved word within types. <br />
<br />
Type variables in a Haskell type expression are all assumed to be<br />
universally quantified; there is no explicit syntax for universal<br />
quantification, in standard Haskell 98/2010. For example, the type expression<br />
<hask>a -> a</hask> denotes the type <hask>forall a. a ->a</hask>. <br />
For clarity, however, we often write quantification explicitly when<br />
discussing the types of Haskell programs. When we write an explicitly<br />
quantified type, the scope of the forall extends as far to the right as<br />
possible; for example, <br />
<haskell><br />
forall a. a -> a<br />
</haskell><br />
means <br />
<haskell><br />
forall a. (a -> a)<br />
</haskell><br />
<br />
GHC [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#inferring-dependency-in-user-written-foralls introduces] a <hask>forall</hask> keyword, allowing explicit quantification, for example, to encode <br />
[https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#existentially-quantified-data-constructors existential types]: <br />
<haskell><br />
data Foo = forall a. MkFoo a (a -> Bool)<br />
| Nil<br />
<br />
MkFoo :: forall a. a -> (a -> Bool) -> Foo<br />
Nil :: Foo<br />
<br />
[MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]<br />
</haskell><br />
<br />
== foreign ==<br />
<br />
A keyword for the [[Foreign Function Interface]] (commonly called the FFI) that introduces either a <hask>foreign import</hask> declaration, which makes a function from a non-Haskell library available in a Haskell program, or a <hask>foreign export</hask> declaration, which allows a function from a Haskell module to be called in non-Haskell contexts.<br />
<br />
== hiding ==<br />
<br />
When importing modules, without introducing a name into scope, entities can be excluded by using the form<br />
<haskell><br />
hiding (import1 , ... , importn )<br />
</haskell><br />
which specifies that all entities exported by the named module should be<br />
imported except for those named in the list.<br />
<br />
For example:<br />
<haskell><br />
import Prelude hiding (lookup,filter,foldr,foldl,null,map)<br />
</haskell><br />
<br />
== <span id="if">if</span>, <span id="then">then</span>, <span id="else">else</span> ==<br />
<br />
A conditional expression has the form:<br />
<br />
<haskell><br />
if e1 then e2 else e3<br />
</haskell><br />
<br />
and returns the value of e2 if the value of e1 is True, e3 if e1 is False, and _|_ otherwise.<br />
<br />
<haskell><br />
max a b = if a > b then a else b<br />
</haskell><br />
<br />
== import ==<br />
<br />
[http://haskell.org/onlinereport/modules.html Modules] may reference<br />
other modules via explicit import declarations, each giving the name of<br />
a module to be imported and specifying its entities to be imported.<br />
<br />
For example:<br />
<haskell><br />
module Main where<br />
import A<br />
import B<br />
main = A.f >> B.f<br />
<br />
module A where<br />
f = ...<br />
<br />
module B where<br />
f = ...<br />
</haskell><br />
<br />
See also [[#as | as]], [[#hiding | hiding]] , [[#qualified | qualified]] and the page [[Import]]<br />
<br />
== <span id="infix">infix</span>, <span id="infixl">infixl</span>, <span id="infixr">infixr</span> ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html fixity declaration] gives<br />
the fixity and binding precedence of one or more operators. The integer<br />
in a fixity declaration must be in the range 0 to 9. A fixity<br />
declaration may appear anywhere that a [[type signature]] appears and, like<br />
a type signature, declares a property of a particular operator.<br />
<br />
There are three kinds of fixity, non-, left- and right-associativity<br />
(infix, infixl, and infixr, respectively), and ten precedence levels, 0<br />
to 9 inclusive (level 0 binds least tightly, and level 9 binds most<br />
tightly).<br />
<br />
<haskell><br />
module Bar where<br />
infixr 7 `op`<br />
op = ...<br />
</haskell><br />
<br />
== instance ==<br />
<br />
An instance declaration declares that a type is an instance of a class<br />
and includes the definitions of the overloaded operations - called class<br />
methods - instantiated on the named type.<br />
<br />
<haskell><br />
instance Num Int where<br />
x + y = addInt x y<br />
negate x = negateInt x<br />
</haskell><br />
<br />
== <span id="let">let</span>, <span id="in">in</span> ==<br />
<br />
Let expressions have the general form:<br />
<br />
<haskell>let { d1 ; ... ; dn } in e</haskell><br />
<br />
They introduce a nested, lexically-scoped, mutually-recursive list of declarations (let is often called letrec in other languages). The scope of the declarations is the expression e and the right hand side of the declarations.<br />
<br />
Within <hask>do</hask>-blocks or list comprehensions <hask>let { d1 ; ... ; dn }</hask> without <hask>in</hask> serves to introduce local bindings.<br />
<br />
== [http://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#the-mdo-notation mdo] ==<br />
<br />
The recursive <hask>do</hask> keyword enabled by -fglasgow-exts.<br />
<br />
== module ==<br />
<br />
Taken from: [http://www.haskell.org/tutorial/modules.html A Gentle Introduction to Haskell, Version 98]<br />
<br />
Technically speaking, a module is really just one big declaration which begins with the keyword module; here's an example for a module whose name is Tree:<br />
<br />
<haskell><br />
module Tree ( Tree(Leaf,Branch), fringe ) where<br />
<br />
data Tree a = Leaf a | Branch (Tree a) (Tree a) <br />
<br />
fringe :: Tree a -> [a]<br />
fringe (Leaf x) = [x]<br />
fringe (Branch left right) = fringe left ++ fringe right<br />
</haskell><br />
<br />
== newtype ==<br />
<br />
The <code>newtype</code> declaration is how one introduces a renaming for an algebraic data [[type]] into Haskell. This is different from <code>type</code> below, as a <code>newtype</code> requires a new [[constructor]] as well. As an example, when writing a compiler<br />
one sometimes further qualifies <code>Identifier</code>s to assist in type safety checks:<br />
<br />
newtype SimpleIdentifier = SimpleIdentifier Identifier<br />
newtype FunctionIdentifier = FunctionIdentifier Identifier<br />
<br />
Most often, one supplies [[smart constructors]] and [[smart destructors|destructors]] for these to ease working with them.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
For the differences between <code>newtype</code> and <code>data</code>, see [[Newtype]].<br />
<br />
== proc ==<br />
proc (arrow abstraction)<br />
is a kind of lambda, except that it constructs an arrow instead of a function.<br />
<br />
[[Arrow notation]]<br />
<br />
== qualified ==<br />
<br />
Used to import a module, but not introduce a name into scope. For example, Data.Map exports lookup, which would clash with the Prelude version of lookup, to fix this:<br />
<br />
<haskell><br />
import qualified Data.Map<br />
<br />
f x = lookup x -- use the Prelude version<br />
g x = Data.Map.lookup x -- use the Data.Map version<br />
</haskell><br />
<br />
Of course, Data.Map is a bit of a mouthful, so qualified also allows the use of as.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
f x = lookup x -- use Prelude version<br />
g x = M.lookup x -- use Data.Map version<br />
</haskell><br />
<br />
== rec ==<br />
The [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#mdo-notation rec] keyword can be used when the <code>-XDoRec</code> flag is given; it allows recursive bindings in a do-block.<br />
<br />
<haskell><br />
{-# LANGUAGE DoRec #-}<br />
justOnes = do { rec { xs <- Just (1:xs) }<br />
; return (map negate xs) }<br />
</haskell><br />
<br />
== type ==<br />
<br />
The <code>type</code> declaration is how one introduces an alias for an algebraic data [[type]] into Haskell. As an example, when writing a compiler<br />
one often creates an alias for identifiers:<br />
<br />
<haskell><br />
type Identifier = String<br />
</haskell><br />
<br />
This allows you to use <code>Identifer</code> wherever you had used <code>String</code> and if something is of type <code>Identifier</code> it<br />
may be used wherever a <code>String</code> is expected.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
Some common <code>type</code> declarations in the Prelude include:<br />
<br />
<haskell><br />
type FilePath = String<br />
type String = [Char]<br />
type Rational = Ratio Integer<br />
type ReadS a = String -> [(a,String)]<br />
type ShowS = String -> String<br />
</haskell><br />
<br />
== type family ==<br />
Declares a type synonym family (see [[type families]]). GHC language extension.<br />
<br />
== type instance ==<br />
Declares a type synonym family instance (see [[type families]]). GHC language extension.<br />
<br />
<br />
<br />
== where ==<br />
<br />
Used to introduce a module, instance, class or [[GADT]]:<br />
<haskell><br />
module Main where<br />
<br />
class Num a where<br />
...<br />
<br />
instance Num Int where<br />
...<br />
<br />
data Something a where<br />
...<br />
</haskell><br />
<br />
And to bind local variables:<br />
<haskell><br />
f x = y<br />
where y = x * 2<br />
<br />
g z | z > 2 = y<br />
where y = x * 2<br />
</haskell><br />
<br />
<br />
[[Category:Language]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Keywords&diff=63361Keywords2020-07-23T05:53:25Z<p>Ysangkok: /* forall */ fix link to existentially quantified data constructors</p>
<hr />
<div>This page lists all Haskell keywords, feel free to edit. [[Hoogle]] searches will return results from this page. Please respect the Anchor macros.<br />
<br />
For additional information you might want to look at [http://www.haskell.org/onlinereport/haskell2010/ the Haskell 2010 report].<br />
<br />
== ! ==<br />
<br />
Whenever a data [[constructor]] is applied, each argument to the<br />
constructor is evaluated if and only if the corresponding type in the<br />
algebraic data[[type]] declaration has a strictness flag, denoted by an<br />
exclamation point. For example:<br />
<br />
<haskell><br />
data STList a <br />
= STCons a !(STList a) -- the second argument to STCons will be <br />
-- evaluated before STCons is applied<br />
| STNil<br />
</haskell><br />
<br />
to illustrate the difference between strict versus lazy constructor<br />
application, consider the following:<br />
<br />
<haskell><br />
stList = STCons 1 undefined<br />
lzList = (:) 1 undefined<br />
stHead (STCons h _) = h -- this evaluates to undefined when applied to stList<br />
lzHead (h : _) = h -- this evaluates to 1 when applied to lzList<br />
</haskell><br />
<br />
! is also used in the [https://downloads.haskell.org/~ghc/7.8.4/docs/html/users_guide/bang-patterns.html "bang patterns"] (GHC extension), to indicate<br />
strictness in patterns:<br />
<br />
<haskell><br />
f !x !y = x + y<br />
</haskell><br />
<br />
== ' ==<br />
* Character literal: <hask>'a'</hask><br />
* [[Template Haskell]]: Name of a (value) variable or data constructor: <hask>'length</hask>, <hask>'Left</hask><br />
* (in types, GHC specific) Promoted data constructor: <hask>'True</hask><br />
<br />
== <nowiki>''</nowiki> ==<br />
* [[Template Haskell]]: Name of a type constructor or class: <hask>''Int</hask>, <hask>''Either</hask>, <hask>''Show</hask><br />
<br />
== - ==<br />
This operator token is magic/irregular in the sense that<br />
<haskell>(- 1)</haskell><br />
is parsed as the negative integer -1, rather than as an operator [[Section of an infix operator|section]], as it would be for any other operator:<br />
<haskell>(* 1) :: Num a => a -> a</haskell><br />
<haskell>(++ "foo") :: String -> String</haskell><br />
<br />
It is syntactic sugar for the <hask>negate</hask> function in Prelude. See [[unary operator]].<br />
If you want the section, you can use the <hask>subtract</hask> function or <hask>(+(-1))</hask>.<br />
<br />
== -- ==<br />
<br />
Starts a single-line comment, unless immediately followed by an operator character other than <hask>-</hask>:<br />
<br />
<haskell><br />
main = print "hello world" -- this is a comment<br />
--this is a comment as well<br />
---this too<br />
foobar --+ this_is_the_second_argument_of_the_dash_dash_plus_operator<br />
</haskell><br />
<br />
The multi-line variant for comments is <hask>{- comment -}</hask>.<br />
<br />
== -< ==<br />
[http://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#arrow-notation Arrow notation]<br />
<br />
== -<< ==<br />
[http://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#arrow-notation Arrow notation]<br />
<br />
== -> ==<br />
<br />
* The function type constructor:<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
* In lambda functions:<br />
<haskell><br />
\x -> x + 1<br />
</haskell><br />
<br />
* To denote alternatives in case statements:<br />
<haskell><br />
case Just 3 of<br />
Nothing -> False<br />
Just x -> True<br />
</haskell><br />
<br />
or with LambdaCase:<br />
<haskell><br />
(\ case 1 -> 0<br />
; _ -> 1 )<br />
</haskell><br />
<br />
or with MultiWayIf:<br />
<haskell><br />
if | 1 == 0 -> 1 <br />
| 1 == 2 -> 2 <br />
| otherwise -> 3<br />
</haskell><br />
<br />
* On the kind level (GHC specific):<br />
<haskell><br />
ghci> :kind (->)<br />
(->) :: * -> * -> *<br />
</haskell><br />
<br />
* [[Functional dependencies]]<br />
<haskell><br />
-- This examples assumes that each type 'c' can "contain" only one type<br />
-- i.e. type 'c' uniquely determines type 'elt'<br />
class Contains c elt | c -> elt where<br />
...<br />
</haskell><br />
<br />
* [[View patterns]]<br />
<br />
== :: ==<br />
<br />
Read as "has type":<br />
<br />
<haskell><br />
length :: [a] -> Int<br />
</haskell><br />
<br />
"Length has type list-of-'a' to Int"<br />
<br />
Or "has kind" (GHC specific):<br />
<br />
<haskell><br />
Either :: * -> * -> *<br />
</haskell><br />
<br />
== ; ==<br />
* Statement separator in an explicit block (see [[layout]])<br />
<br />
== <- ==<br />
<br />
* In do-notation, "draw from":<br />
<haskell><br />
do x <- getChar<br />
putChar x<br />
</haskell><br />
<br />
* In list comprehension generators, "in":<br />
<haskell><br />
[ (x,y) | x <- [1..10], y <- ['a'..'z'] ]<br />
</haskell><br />
<br />
* In [[pattern guard]]s, "matches":<br />
<haskell><br />
f x y | Just z <- g x = True<br />
| otherwise = False<br />
</haskell><br />
<br />
== , ==<br />
<br />
Separator in lists, tuples, records.<br />
<br />
<haskell><br />
[1,2,3]<br />
(1,2,3)<br />
Point {x = 1, y = 2}<br />
</haskell><br />
<br />
In list comprehensions before generators, "and" (the first comma after <code>|</code>):<br />
<haskell><br />
[ (x,y) | x <- [1..10], y <- ['a'..'z'], x > 42 ]<br />
</haskell><br />
<br />
In list comprehensions before Boolean tests, "when" (the second comma after <code>|</code>):<br />
<haskell><br />
[ (x,y) | x <- [1..10], y <- ['a'..'z'], x > 42 ]<br />
</haskell><br />
<br />
In guards inside case expressions, "and when":<br />
<haskell><br />
case [1,3,9] of xs | (x:ys) <- xs, (y:_) <- ys, let z=x+1, z /= y -> [x,y,z]<br />
</haskell><br />
<br />
In module import and export lists:<br />
<br />
<haskell><br />
module MyModule<br />
( MyData (C1,C2)<br />
, myFun ) where<br />
<br />
import MyModule (MyData (C1,C2), myFun)<br />
</haskell><br />
<br />
== = ==<br />
Used in definitions.<br />
<br />
<haskell><br />
x = 4<br />
</haskell><br />
<br />
Also in pattern-matching records:<br />
<br />
<haskell><br />
case point of<br />
Point {x = x0, y = y0} -> f x0 y0<br />
</haskell><br />
<br />
== => ==<br />
<br />
Used to indicate instance contexts, for example:<br />
<br />
<haskell><br />
sort :: Ord a => [a] -> [a]<br />
</haskell><br />
<br />
== > ==<br />
<br />
In a Bird's style [[Literate_programming|Literate Haskell file]], the > character is used to introduce a code line.<br />
<br />
<haskell><br />
comment line<br />
<br />
> main = print "hello world"<br />
</haskell><br />
<br />
== ? ==<br />
<br />
* [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#implicit-parameters Implicit parameters]<br />
<br />
<haskell><br />
ghci> :t ?foo ++ "bar"<br />
?foo ++ "bar" :: (?foo::[Char]) => [Char]<br />
</haskell><br />
<br />
== # ==<br />
<br />
* [https://downloads.haskell.org/~ghc/7.6.2/docs/html/users_guide/syntax-extns.html MagicHash]<br />
<br />
== * ==<br />
<br />
* Is an ordinary operator name on the value level<br />
<br />
* On the [[kind]] level: The kind of boxed types (GHC-specific) <br />
<br />
<haskell><br />
ghci> :kind Int<br />
Int :: *<br />
</haskell><br />
<br />
== @ ==<br />
<br />
Patterns of the form <hask>var@pat</hask> are called as-patterns, and allow one to<br />
use <hask>var</hask> as a name for the value being matched by <hask>pat</hask>. For example:<br />
<haskell><br />
case e of { xs@(x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
let { xs = e } in<br />
case xs of { (x:rest) -> if x==0 then rest else xs }<br />
</haskell><br />
<br />
== [|, |] ==<br />
* [[Template Haskell]]<br />
** Expression quotation: <hask> [| print 1 |] </hask><br />
** Declaration quotation: <hask> [d| main = print 1 |] </hask><br />
** Type quotation: <hask> [t| Either Int () |] </hask> <br />
** Pattern quotation: <hask> [p| (x,y) |] </hask><br />
** [[Quasiquotation]]: <hask> [nameOfQuasiQuoter| ... |] </hask><br />
<br />
== \ ==<br />
The backslash "\" is used<br />
<br />
* in multiline strings<br />
<haskell><br />
"foo\<br />
\bar"<br />
</haskell><br />
<br />
* in lambda functions<br />
<haskell><br />
\x -> x + 1<br />
</haskell><br />
<br />
<br />
== _ ==<br />
<br />
Patterns of the form _ are wildcards and are useful when some part of a<br />
pattern is not referenced on the right-hand-side. It is as if an<br />
identifier not used elsewhere were put in its place. For example,<br />
<br />
<haskell><br />
case e of { [x,_,_] -> if x==0 then True else False }<br />
</haskell><br />
<br />
is equivalent to:<br />
<br />
<haskell><br />
case e of { [x,y,z] -> if x==0 then True else False }<br />
</haskell><br />
<br />
<br />
<br />
<br />
<br />
== ` ==<br />
<br />
A function enclosed in back ticks "`" can be used as an infix operator.<br />
<br />
<haskell>2 `subtract` 10</haskell><br />
is the same as<br />
<haskell>subtract 2 10</haskell><br />
<br />
== {, } ==<br />
* Explicit block (disable [[layout]]), possibly with ";" .<br />
<br />
* Record update notation<br />
<haskell><br />
changePrice :: Thing -> Price -> Thing<br />
changePrice x new = x { price = new }<br />
</haskell><br />
<br />
* Comments (see below)<br />
<br />
== {-, -} ==<br />
<br />
Everything between "{-" followed by a space and "-}" is a block comment.<br />
<br />
<haskell><br />
{-<br />
hello<br />
world<br />
-}<br />
</haskell><br />
<br />
== | ==<br />
<br />
The "pipe" is used in several places<br />
<br />
* Data type definitions, "or"<br />
<haskell><br />
data Maybe a = Just a | Nothing<br />
</haskell><br />
<br />
* List comprehensions, "for" (as in, "list of <code>a*a</code> for <code>a</code> in <code>[1..]</code>)<br />
<haskell><br />
squares = [a*a | a <- [1..]]<br />
</haskell><br />
<br />
* Guards, "when"<br />
<haskell><br />
safeTail x | null x = []<br />
| otherwise = tail x<br />
</haskell><br />
<br />
* [[Functional dependencies]], "where"<br />
<haskell><br />
class Contains c elt | c -> elt where<br />
...<br />
</haskell><br />
<br />
== ~ ==<br />
<br />
* Lazy pattern bindings. Matching the pattern <hask>~pat</hask> against a value always succeeds, and matching will only diverge when one of the variables bound in the pattern is used.<br />
<br />
<haskell><br />
f1, f2 :: Maybe Int -> String<br />
f1 x = case x of <br />
Just n -> "Got it"<br />
f2 x = case x of<br />
~(Just n) -> "Got it"<br />
<br />
(+++), (++++) :: (a -> b) -> (c -> d) -> (a, c) -> (b, d) <br />
(f +++ g) ~(x, y) = (f x, g y)<br />
(f ++++ g) (x, y) = (f x, g y)<br />
</haskell><br />
<br />
Then we have:<br />
<br />
<haskell><br />
f1 Nothing<br />
Exception: Non-exhaustive patterns in case<br />
<br />
f2 Nothing<br />
"Got it"<br />
<br />
(const 1 +++ const 2) undefined<br />
(1,2)<br />
<br />
(const 1 ++++ const 2) undefined<br />
Exception: Prelude.undefined<br />
</haskell><br />
<br />
For more details see [http://en.wikibooks.org/wiki/Haskell/Laziness#Lazy_pattern_matching the Haskell Wikibook].<br />
<br />
* Equality constraints. Assert that two types in a context must be the same:<br />
<br />
<haskell><br />
example :: F a ~ b => a -> b<br />
</haskell><br />
<br />
Here the type "F a" must be the same as the type "b", which allows one to constrain polymorphism (especially where type families are involved), but to a lesser extent than functional dependencies. See [[Type_families#Equality_constraints|Type Families]].<br />
<br />
== as ==<br />
<br />
Renaming module imports. Like <hask>qualified</hask> and <hask>hiding</hask>, <hask>as</hask> is not a reserved word but may be used as function or variable name.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
main = print (M.empty :: M.Map Int ())<br />
</haskell><br />
<br />
== <span id="case">case</span>, <span id="of">of</span> ==<br />
<br />
A case expression has the general form<br />
<br />
<haskell><br />
case e of { p1 match1 ; ... ; pn matchn }<br />
</haskell><br />
<br />
where each <code>match</code><sub>i</sub> is of the general form<br />
<br />
<haskell><br />
| g1 -> e1<br />
...<br />
| gm -> em<br />
where decls<br />
</haskell><br />
<br />
Each alternative consists of patterns <code>p</code><sub>i</sub> and their matches, <code>match</code><sub>i</sub>. Each<br />
<code>match</code><sub>i</sub> in turn consists of a sequence of pairs of guards <code>g</code><sub>ij</sub> and bodies <code>e</code><sub>ij</sub><br />
(expressions), followed by optional bindings (<code>decls</code><sub>i</sub>) that scope over all<br />
of the guards and expressions of the alternative. An alternative of the<br />
form<br />
<br />
<haskell><br />
pat -> exp where decls<br />
</haskell><br />
<br />
is treated as shorthand for:<br />
<br />
<haskell><br />
pat | True -> exp<br />
where decls<br />
</haskell><br />
<br />
A case expression must have at least one alternative and each<br />
alternative must have at least one body. Each body must have the same<br />
type, and the type of the whole expression is that type.<br />
<br />
A case expression is evaluated by pattern matching the expression <code>e</code><br />
against the individual alternatives. The alternatives are tried<br />
sequentially, from top to bottom. If <code>e</code> matches the pattern in the<br />
alternative, the guards for that alternative are tried sequentially from<br />
top to bottom, in the environment of the case expression extended first<br />
by the bindings created during the matching of the pattern, and then by<br />
the <code>decls</code><sub>i</sub>&nbsp; in the <code>where</code> clause associated with that alternative. If one<br />
of the guards evaluates to <code>True</code>, the corresponding right-hand side is<br />
evaluated in the same environment as the guard. If all the guards<br />
evaluate to <code>False</code>, matching continues with the next alternative. If no<br />
match succeeds, the result is _|_.<br />
<br />
== class ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html#class-decls class declaration] <br />
introduces a new type class and the overloaded operations that must be<br />
supported by any type that is an instance of that class.<br />
<haskell><br />
class Num a where<br />
(+) :: a -> a -> a<br />
negate :: a -> a<br />
</haskell><br />
<br />
== data ==<br />
<br />
The [http://haskell.org/onlinereport/decls.html#user-defined-datatypes data] <br />
declaration is how one introduces new algebraic data [[type]]s into<br />
Haskell. For example:<br />
<br />
<haskell><br />
data Set a = NilSet <br />
| ConsSet a (Set a)<br />
</haskell><br />
<br />
Another example, to create a datatype to hold an [[Abstract_syntax_tree|abstract syntax tree]] for an expression, one could use:<br />
<br />
<haskell><br />
data Exp = Ebin Operator Exp Exp <br />
| Eunary Operator Exp <br />
| Efun FunctionIdentifier [Exp] <br />
| Eid SimpleIdentifier<br />
</haskell><br />
<br />
where the [[type]]s <code>Operator, FunctionIdentifier</code> and <code>SimpleIdentifier</code> are defined elsewhere. <br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
== data family ==<br />
Declares a datatype family (see [[type families]]). GHC language extension.<br />
<br />
== data instance ==<br />
Declares a datatype family instance (see [[type families]]). GHC language extension.<br />
<br />
<br />
== default ==<br />
<br />
Ambiguities in the class Num are most common, so Haskell provides<br />
a way to resolve them---with a default declaration:<br />
<br />
<haskell><br />
default (Int)<br />
</haskell><br />
<br />
Only one default declaration is permitted per module, and its effect is<br />
limited to that module. If no default declaration is given in a module<br />
then it assumed to be:<br />
<br />
<haskell><br />
default (Integer, Double)<br />
</haskell><br />
<br />
== deriving ==<br />
<br />
data and newtype declarations contain an optional deriving form. If the<br />
form is included, then derived instance declarations are automatically<br />
generated for the datatype in each of the named classes.<br />
<br />
[http://haskell.org/onlinereport/decls.html#derived-decls Derived instances] provide convenient commonly-used operations for user-defined<br />
datatypes. For example, derived instances for datatypes in the class Eq<br />
define the operations == and /=, freeing the programmer from the need to<br />
define them.<br />
<br />
<haskell><br />
data T = A<br />
| B<br />
| C<br />
deriving (Eq, Ord, Show)<br />
</haskell><br />
<br />
In the case of newtypes, GHC extends this mechanism to [[Cunning Newtype Deriving]].<br />
<br />
== deriving instance ==<br />
<br />
Standalone deriving (GHC language extension).<br />
<br />
<haskell><br />
{-# LANGUAGE StandaloneDeriving #-}<br />
data A = A<br />
<br />
deriving instance Show A<br />
</haskell><br />
<br />
== do ==<br />
<br />
Syntactic sugar for use with monadic expressions. For example:<br />
<br />
<haskell><br />
do { x ; result <- y ; foo result }<br />
</haskell><br />
<br />
is shorthand for:<br />
<br />
<haskell><br />
x >> <br />
y >>= \result -><br />
foo result<br />
</haskell><br />
<br />
== forall ==<br />
<br />
This is a GHC/Hugs extension, and as such is not portable Haskell 98/2010. <br />
It is only a reserved word within types. <br />
<br />
Type variables in a Haskell type expression are all assumed to be<br />
universally quantified; there is no explicit syntax for universal<br />
quantification, in standard Haskell 98/2010. For example, the type expression<br />
<hask>a -> a</hask> denotes the type <hask>forall a. a ->a</hask>. <br />
For clarity, however, we often write quantification explicitly when<br />
discussing the types of Haskell programs. When we write an explicitly<br />
quantified type, the scope of the forall extends as far to the right as<br />
possible; for example, <br />
<haskell><br />
forall a. a -> a<br />
</haskell><br />
means <br />
<haskell><br />
forall a. (a -> a)<br />
</haskell><br />
<br />
GHC [http://www.haskell.org/ghc/docs/latest/html/users_guide/data-type-extensions.html#type-synonyms introduces] a <hask>forall</hask> keyword, allowing explicit quantification, for example, to encode <br />
[https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#existentially-quantified-data-constructors existential types]: <br />
<haskell><br />
data Foo = forall a. MkFoo a (a -> Bool)<br />
| Nil<br />
<br />
MkFoo :: forall a. a -> (a -> Bool) -> Foo<br />
Nil :: Foo<br />
<br />
[MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]<br />
</haskell><br />
<br />
== foreign ==<br />
<br />
A keyword for the [[Foreign Function Interface]] (commonly called the FFI) that introduces either a <hask>foreign import</hask> declaration, which makes a function from a non-Haskell library available in a Haskell program, or a <hask>foreign export</hask> declaration, which allows a function from a Haskell module to be called in non-Haskell contexts.<br />
<br />
== hiding ==<br />
<br />
When importing modules, without introducing a name into scope, entities can be excluded by using the form<br />
<haskell><br />
hiding (import1 , ... , importn )<br />
</haskell><br />
which specifies that all entities exported by the named module should be<br />
imported except for those named in the list.<br />
<br />
For example:<br />
<haskell><br />
import Prelude hiding (lookup,filter,foldr,foldl,null,map)<br />
</haskell><br />
<br />
== <span id="if">if</span>, <span id="then">then</span>, <span id="else">else</span> ==<br />
<br />
A conditional expression has the form:<br />
<br />
<haskell><br />
if e1 then e2 else e3<br />
</haskell><br />
<br />
and returns the value of e2 if the value of e1 is True, e3 if e1 is False, and _|_ otherwise.<br />
<br />
<haskell><br />
max a b = if a > b then a else b<br />
</haskell><br />
<br />
== import ==<br />
<br />
[http://haskell.org/onlinereport/modules.html Modules] may reference<br />
other modules via explicit import declarations, each giving the name of<br />
a module to be imported and specifying its entities to be imported.<br />
<br />
For example:<br />
<haskell><br />
module Main where<br />
import A<br />
import B<br />
main = A.f >> B.f<br />
<br />
module A where<br />
f = ...<br />
<br />
module B where<br />
f = ...<br />
</haskell><br />
<br />
See also [[#as | as]], [[#hiding | hiding]] , [[#qualified | qualified]] and the page [[Import]]<br />
<br />
== <span id="infix">infix</span>, <span id="infixl">infixl</span>, <span id="infixr">infixr</span> ==<br />
<br />
A [http://haskell.org/onlinereport/decls.html fixity declaration] gives<br />
the fixity and binding precedence of one or more operators. The integer<br />
in a fixity declaration must be in the range 0 to 9. A fixity<br />
declaration may appear anywhere that a [[type signature]] appears and, like<br />
a type signature, declares a property of a particular operator.<br />
<br />
There are three kinds of fixity, non-, left- and right-associativity<br />
(infix, infixl, and infixr, respectively), and ten precedence levels, 0<br />
to 9 inclusive (level 0 binds least tightly, and level 9 binds most<br />
tightly).<br />
<br />
<haskell><br />
module Bar where<br />
infixr 7 `op`<br />
op = ...<br />
</haskell><br />
<br />
== instance ==<br />
<br />
An instance declaration declares that a type is an instance of a class<br />
and includes the definitions of the overloaded operations - called class<br />
methods - instantiated on the named type.<br />
<br />
<haskell><br />
instance Num Int where<br />
x + y = addInt x y<br />
negate x = negateInt x<br />
</haskell><br />
<br />
== <span id="let">let</span>, <span id="in">in</span> ==<br />
<br />
Let expressions have the general form:<br />
<br />
<haskell>let { d1 ; ... ; dn } in e</haskell><br />
<br />
They introduce a nested, lexically-scoped, mutually-recursive list of declarations (let is often called letrec in other languages). The scope of the declarations is the expression e and the right hand side of the declarations.<br />
<br />
Within <hask>do</hask>-blocks or list comprehensions <hask>let { d1 ; ... ; dn }</hask> without <hask>in</hask> serves to introduce local bindings.<br />
<br />
== [http://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#the-mdo-notation mdo] ==<br />
<br />
The recursive <hask>do</hask> keyword enabled by -fglasgow-exts.<br />
<br />
== module ==<br />
<br />
Taken from: [http://www.haskell.org/tutorial/modules.html A Gentle Introduction to Haskell, Version 98]<br />
<br />
Technically speaking, a module is really just one big declaration which begins with the keyword module; here's an example for a module whose name is Tree:<br />
<br />
<haskell><br />
module Tree ( Tree(Leaf,Branch), fringe ) where<br />
<br />
data Tree a = Leaf a | Branch (Tree a) (Tree a) <br />
<br />
fringe :: Tree a -> [a]<br />
fringe (Leaf x) = [x]<br />
fringe (Branch left right) = fringe left ++ fringe right<br />
</haskell><br />
<br />
== newtype ==<br />
<br />
The <code>newtype</code> declaration is how one introduces a renaming for an algebraic data [[type]] into Haskell. This is different from <code>type</code> below, as a <code>newtype</code> requires a new [[constructor]] as well. As an example, when writing a compiler<br />
one sometimes further qualifies <code>Identifier</code>s to assist in type safety checks:<br />
<br />
newtype SimpleIdentifier = SimpleIdentifier Identifier<br />
newtype FunctionIdentifier = FunctionIdentifier Identifier<br />
<br />
Most often, one supplies [[smart constructors]] and [[smart destructors|destructors]] for these to ease working with them.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
For the differences between <code>newtype</code> and <code>data</code>, see [[Newtype]].<br />
<br />
== proc ==<br />
proc (arrow abstraction)<br />
is a kind of lambda, except that it constructs an arrow instead of a function.<br />
<br />
[[Arrow notation]]<br />
<br />
== qualified ==<br />
<br />
Used to import a module, but not introduce a name into scope. For example, Data.Map exports lookup, which would clash with the Prelude version of lookup, to fix this:<br />
<br />
<haskell><br />
import qualified Data.Map<br />
<br />
f x = lookup x -- use the Prelude version<br />
g x = Data.Map.lookup x -- use the Data.Map version<br />
</haskell><br />
<br />
Of course, Data.Map is a bit of a mouthful, so qualified also allows the use of as.<br />
<br />
<haskell><br />
import qualified Data.Map as M<br />
<br />
f x = lookup x -- use Prelude version<br />
g x = M.lookup x -- use Data.Map version<br />
</haskell><br />
<br />
== rec ==<br />
The [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#mdo-notation rec] keyword can be used when the <code>-XDoRec</code> flag is given; it allows recursive bindings in a do-block.<br />
<br />
<haskell><br />
{-# LANGUAGE DoRec #-}<br />
justOnes = do { rec { xs <- Just (1:xs) }<br />
; return (map negate xs) }<br />
</haskell><br />
<br />
== type ==<br />
<br />
The <code>type</code> declaration is how one introduces an alias for an algebraic data [[type]] into Haskell. As an example, when writing a compiler<br />
one often creates an alias for identifiers:<br />
<br />
<haskell><br />
type Identifier = String<br />
</haskell><br />
<br />
This allows you to use <code>Identifer</code> wherever you had used <code>String</code> and if something is of type <code>Identifier</code> it<br />
may be used wherever a <code>String</code> is expected.<br />
<br />
See the page on [[type]]s for more information, links and examples.<br />
<br />
Some common <code>type</code> declarations in the Prelude include:<br />
<br />
<haskell><br />
type FilePath = String<br />
type String = [Char]<br />
type Rational = Ratio Integer<br />
type ReadS a = String -> [(a,String)]<br />
type ShowS = String -> String<br />
</haskell><br />
<br />
== type family ==<br />
Declares a type synonym family (see [[type families]]). GHC language extension.<br />
<br />
== type instance ==<br />
Declares a type synonym family instance (see [[type families]]). GHC language extension.<br />
<br />
<br />
<br />
== where ==<br />
<br />
Used to introduce a module, instance, class or [[GADT]]:<br />
<haskell><br />
module Main where<br />
<br />
class Num a where<br />
...<br />
<br />
instance Num Int where<br />
...<br />
<br />
data Something a where<br />
...<br />
</haskell><br />
<br />
And to bind local variables:<br />
<haskell><br />
f x = y<br />
where y = x * 2<br />
<br />
g z | z > 2 = y<br />
where y = x * 2<br />
</haskell><br />
<br />
<br />
[[Category:Language]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Pronunciation&diff=63360Pronunciation2020-07-23T05:50:03Z<p>Ysangkok: fix link to bang patterns</p>
<hr />
<div>There was a thread on Haskell-Cafe about [http://www.haskell.org/pipermail/haskell-cafe/2008-January/038756.html how to pronounce Haskell].<br />
<br />
Below are some notes for beginners on how to pronounce those strange Haskell operators and 'read' Haskell programs.<br />
<br />
This is meant to be a table with formal and informal ways of saying various operators and code snippets.<br />
<br />
{|<br />
! Symbol<br />
! Pronunciation<br />
! References<br />
|-<br />
| <hask>::</hask><br />
| has type (in definitions); at type (in expressions or patterns)<br />
|-<br />
| <hask>-></hask><br />
| maps to, to<br />
|-<br />
| <hask>=</hask><br />
| is<br />
|-<br />
| <hask>==</hask><br />
| equals<br />
| [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3A-61--61- Prelude]<br />
|-<br />
| <hask>/=</hask><br />
| not equals<br />
| [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3A-61--61- Prelude]<br />
|-<br />
| <hask>=></hask><br />
| is a witness for, implies<br />
| [http://www.haskell.org/tutorial/classes.html Type Classes and Overloading]<br />
|-<br />
| <hask>.</hask><br />
| dot (could be used anywhere, but especially in, for example, Data.Char.ord), ring, compose (for example, negate . (+1)), (silent) (for example, forall a. (Num a) => a)<br />
|-<br />
| <hask><-</hask><br />
| drawn from, from<br />
|-<br />
| <hask>-<</hask><br />
| arrow application<br />
| [http://haskell.org/arrows/syntax.html Arrows syntax]<br />
|-<br />
| <hask>&&&</hask><br />
| both, fanout<br />
| [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html Control.Arrow]<br />
|-<br />
| <hask>|||</hask><br />
| either, fanin<br />
| [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Arrow.html#v%3A%7C%7C%7C Control.Arrow]<br />
|<br />
|-<br />
| <hask>++</hask><br />
| append<br />
| [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3A-43--43- Prelude]<br />
|-<br />
| <hask>>>=</hask><br />
| bind<br />
| [http://www.haskell.org/tutorial/monads.html About monads]<br />
[[Monads as containers]]<br />
|-<br />
| <hask>>></hask><br />
| then, sequence<br />
| [http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:-62--62- Prelude]<br />
|-<br />
| <hask><*></hask><br />
| applied over<br />
| [http://www.haskell.org/haskellwiki/Applicative_functor Applicative Functors]<br />
|-<br />
| <hask><|></hask><br />
| or/alternative<br />
| [https://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Applicative.html#t:Alternative]<br />
|-<br />
| <hask>\</hask><br />
| lambda<br />
| [[Lambda abstraction]]<br />
[http://www.haskell.org/onlinereport/exps.html#sect3.3 Haskell 98 Report]<br />
|-<br />
| <hask>!</hask><br />
| bang; strict (in patterns or data definitions); index (in expressions)<br />
| [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#bang-patterns-and-strict-haskell Bang Patterns]<br />
[[Keywords]]<br />
|-<br />
| <hask>~</hask><br />
| irrefutable, lazy (in patterns)<br />
|-<br />
| <hask>:</hask><br />
| cons<br />
|-<br />
| <hask>[]</hask><br />
| nil<br />
|-<br />
| <hask>()</hask><br />
| unit<br />
|-<br />
| <hask>(,)</hask><br />
| 2-tuple, pair<br />
|-<br />
| <hask>(a,b,c)</hask><br />
| [3-]tuple [of] a, b, and c<br />
|-<br />
| <hask>({)}</hask><br />
| just as inconvenient to convey grouping verbally, whether it's layout or punctuation<br />
|}<br />
<br />
{|<br />
! Example<br />
! Pronunciation<br />
|-<br />
| <hask>f :: Int -> Int</hask><br />
| f has type Int to Int<br />
|}<br />
<br />
Thoughts on improving this page:<br />
<br />
The tables above would be best split into more columns to distinguish Informal, possibly bad suggestions like "then", "is", "gets", from Formal correct ways of saying the same thing. The Symbols could also be named in a literal way in another column, such as "arrow" or "double-colon". The Description column can be quite brief and a link provided to the relevant wiki page for the operator.<br />
<br />
Some words, particularly the informal ones, may be good for several different symbols, but these can hopefully be arranged so that their context will make them unambiguous when reading a code snippet.<br />
<br />
[[Category:Syntax]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Benchmarks_Game&diff=63359Benchmarks Game2020-07-23T05:48:51Z<p>Ysangkok: /* Submitting guide */ fix links to bytestring and text.regex</p>
<hr />
<div>This is for entries to [https://salsa.debian.org/benchmarksgame-team/benchmarksgame The Computer Language Benchmarks Game] (Formerly known as The Great Language Shootout). You can see [https://salsa.debian.org/benchmarksgame-team/benchmarksgame/tree/master/public/data the current results as data files].<br />
<br />
The old site was closed at 2018-05-01, the new site is not fully functional yet (at 2018-05-17), see the <br />
[https://www.reddit.com/r/programming/comments/88jg07/the_computer_language_benchmarks_games/ announcement].<br />
<br />
[[Image:Chartvs.png|center|frame|Haskell entries compared to C on the quad core, Feb 2009]]<br />
<br />
== Parallel implementations ==<br />
New implementations written for parallelism. You should almost certainly<br />
be working on these only:<br />
<br />
* [[/Parallel]]<br />
<br />
== Submitting guide ==<br />
<br />
Now that GHC 8.8.1 is installed on the Benchmarks Game servers, please make full use of it! There is an immediate need for a complete revamp of all the entries to fix and optimise them for this version of GHC. Please pick a program and contribute!<br />
<br />
GHC change information since version 8.0.1 can be found on the [https://www.haskell.org/ghc/blog.html GHC Developer Blog]<br />
<br />
GHC 6.10 gave us the option of<br />
* parallel garbage collector<br />
<br />
GHC 6.8 gave us the option of <br />
* `par`<br />
* SMP runtime<br />
* new regex libs<br />
* lots of other stuff<br />
<br />
GHC 6.6 gave the option of using:<br />
* [https://hackage.haskell.org/package/bytestring/docs/Data-ByteString.html Data.ByteString]<br />
* [https://hackage.haskell.org/package/regex-posix/docs/Text-Regex-Posix-ByteString-Lazy.html Text.Regex.*]<br />
* [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#bang-patterns-and-strict-haskell bang patterns]<br />
which should greatly improve clarity and brevity. Line count is not<br />
significant now (code is gzipped to determine size), so aim for maximum<br />
clarity.<br />
<br />
Suggested best practices for submitting an entry to the Benchmarks Game include:<br />
<br />
* Posting the proposed code to the community to allow for a best of breed entry. Proposed code is here on the wiki and often in the Haskell-cafe mailing list. This has already helped improve the submitted code.<br />
<br />
* Provide complete performance measurements against the current best entry.<br />
<br />
* Creating clean, functional-style code or fast, imperative-style code. There are multiple versions ("GHC", "GHC#2", "GHC#3", "GHC#4") of GHC codes on many of the benchmarks with no clear rational for the different versions. It'd be better to have entries for "GHC" be clean, short, functional code and entries for "GHC-#2" be fastest, probably-ugliest code.<br />
<br />
* When you submit via the trac system, record in the wiki section for that entry a link to the submission.<br />
<br />
* Check for gzip file size before you submit -- lots of points to be had there.<br />
<br />
* Try different compile options and the other ideas on the [[Performance/GHC]] page.<br />
<br />
<haskell><br />
--<br />
-- The Computer Language Benchmarks Game, https://benchmarksgame-team.pages.debian.net/benchmarksgame/<br />
-- Haskell Benchmarks Game entries, https://wiki.haskell.org/Benchmarks_Game<br />
-- <br />
-- Simon Marlow<br />
-- Shortened by Don Stewart<br />
--<br />
</haskell><br />
<br />
== Results ==<br />
<br />
Results for all benchmarks: [https://salsa.debian.org/benchmarksgame-team/benchmarksgame/tree/master/public/data]<br />
<br />
== Todo ==<br />
<br />
The current benchmarks can highlight weak spots in libraries and<br />
compilers that need improving. Some things noticed included:<br />
<br />
* hashtable performance is poor. A simple binding to a basic C hashtable would be very useful<br />
* it would be nice to have tre regexes in the core libs (instead of POSIX ones)<br />
<br />
''Why tre regexes? The libtre code is buggy, though if the shootout avoids the bugs then I guess one might want to use it. Would libpcre be a better choice?''--[[User:ChrisKuklewicz|ChrisKuklewicz]] 00:21, 24 February 2009 (UTC)<br />
<br />
<br />
== Obsolete benchmarks ==<br />
<br />
* [[Shootout/Takfp | Takfp]]<br />
<br />
* [[Shootout/Ack | Ack]] <br />
<br />
* [[Shootout/Harmonic | Harmonic]]<br />
<br />
* [[Shootout/Healthcare | Healthcare]]<br />
<br />
* [[Shootout/Nsieve | N-sieve]]<br />
<br />
* [[Shootout/Nsieve Bits | N-sieve Bits]]<br />
<br />
* [[Shootout/Partial sums | Partial sums]]<br />
<br />
* [[Shootout/Cheap concurrency | Cheap concurrency]]<br />
<br />
* [[Shootout/Chameneos | Chameneos]]<br />
<br />
* [[Shootout/Random | Random]]<br />
<br />
* [[Shootout/Recursive | Recursive]]<br />
<br />
* [[Shootout/SumFile | SumFile]]<br />
<br />
<br />
[[Category:Contests]]<br />
[[Category:Code]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Benchmarks_Game&diff=63358Benchmarks Game2020-07-23T05:46:31Z<p>Ysangkok: /* Submitting guide */ fix link to bang patterns in user guide</p>
<hr />
<div>This is for entries to [https://salsa.debian.org/benchmarksgame-team/benchmarksgame The Computer Language Benchmarks Game] (Formerly known as The Great Language Shootout). You can see [https://salsa.debian.org/benchmarksgame-team/benchmarksgame/tree/master/public/data the current results as data files].<br />
<br />
The old site was closed at 2018-05-01, the new site is not fully functional yet (at 2018-05-17), see the <br />
[https://www.reddit.com/r/programming/comments/88jg07/the_computer_language_benchmarks_games/ announcement].<br />
<br />
[[Image:Chartvs.png|center|frame|Haskell entries compared to C on the quad core, Feb 2009]]<br />
<br />
== Parallel implementations ==<br />
New implementations written for parallelism. You should almost certainly<br />
be working on these only:<br />
<br />
* [[/Parallel]]<br />
<br />
== Submitting guide ==<br />
<br />
Now that GHC 8.8.1 is installed on the Benchmarks Game servers, please make full use of it! There is an immediate need for a complete revamp of all the entries to fix and optimise them for this version of GHC. Please pick a program and contribute!<br />
<br />
GHC change information since version 8.0.1 can be found on the [https://www.haskell.org/ghc/blog.html GHC Developer Blog]<br />
<br />
GHC 6.10 gave us the option of<br />
* parallel garbage collector<br />
<br />
GHC 6.8 gave us the option of <br />
* `par`<br />
* SMP runtime<br />
* new regex libs<br />
* lots of other stuff<br />
<br />
GHC 6.6 gave the option of using:<br />
* [http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-ByteString.html Data.ByteString]<br />
* [http://www.haskell.org/ghc/docs/latest/html/libraries/regex-posix/Text-Regex-Posix-ByteString.html Text.Regex.*]<br />
* [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#bang-patterns-and-strict-haskell bang patterns]<br />
which should greatly improve clarity and brevity. Line count is not<br />
significant now (code is gzipped to determine size), so aim for maximum<br />
clarity.<br />
<br />
Suggested best practices for submitting an entry to the Benchmarks Game include:<br />
<br />
* Posting the proposed code to the community to allow for a best of breed entry. Proposed code is here on the wiki and often in the Haskell-cafe mailing list. This has already helped improve the submitted code.<br />
<br />
* Provide complete performance measurements against the current best entry.<br />
<br />
* Creating clean, functional-style code or fast, imperative-style code. There are multiple versions ("GHC", "GHC#2", "GHC#3", "GHC#4") of GHC codes on many of the benchmarks with no clear rational for the different versions. It'd be better to have entries for "GHC" be clean, short, functional code and entries for "GHC-#2" be fastest, probably-ugliest code.<br />
<br />
* When you submit via the trac system, record in the wiki section for that entry a link to the submission.<br />
<br />
* Check for gzip file size before you submit -- lots of points to be had there.<br />
<br />
* Try different compile options and the other ideas on the [[Performance/GHC]] page.<br />
<br />
<haskell><br />
--<br />
-- The Computer Language Benchmarks Game, https://benchmarksgame-team.pages.debian.net/benchmarksgame/<br />
-- Haskell Benchmarks Game entries, https://wiki.haskell.org/Benchmarks_Game<br />
-- <br />
-- Simon Marlow<br />
-- Shortened by Don Stewart<br />
--<br />
</haskell><br />
<br />
== Results ==<br />
<br />
Results for all benchmarks: [https://salsa.debian.org/benchmarksgame-team/benchmarksgame/tree/master/public/data]<br />
<br />
== Todo ==<br />
<br />
The current benchmarks can highlight weak spots in libraries and<br />
compilers that need improving. Some things noticed included:<br />
<br />
* hashtable performance is poor. A simple binding to a basic C hashtable would be very useful<br />
* it would be nice to have tre regexes in the core libs (instead of POSIX ones)<br />
<br />
''Why tre regexes? The libtre code is buggy, though if the shootout avoids the bugs then I guess one might want to use it. Would libpcre be a better choice?''--[[User:ChrisKuklewicz|ChrisKuklewicz]] 00:21, 24 February 2009 (UTC)<br />
<br />
<br />
== Obsolete benchmarks ==<br />
<br />
* [[Shootout/Takfp | Takfp]]<br />
<br />
* [[Shootout/Ack | Ack]] <br />
<br />
* [[Shootout/Harmonic | Harmonic]]<br />
<br />
* [[Shootout/Healthcare | Healthcare]]<br />
<br />
* [[Shootout/Nsieve | N-sieve]]<br />
<br />
* [[Shootout/Nsieve Bits | N-sieve Bits]]<br />
<br />
* [[Shootout/Partial sums | Partial sums]]<br />
<br />
* [[Shootout/Cheap concurrency | Cheap concurrency]]<br />
<br />
* [[Shootout/Chameneos | Chameneos]]<br />
<br />
* [[Shootout/Random | Random]]<br />
<br />
* [[Shootout/Recursive | Recursive]]<br />
<br />
* [[Shootout/SumFile | SumFile]]<br />
<br />
<br />
[[Category:Contests]]<br />
[[Category:Code]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Ternary_operator&diff=63357Ternary operator2020-07-23T05:44:21Z<p>Ysangkok: /* Further reading */ fix user guide link</p>
<hr />
<div>With a bit of work, we can define a ternary conditional operator in<br />
Haskell. Courtesy of Andrew Baumann. This appears only to be valid in<br />
Hugs?<br />
<br />
<haskell><br />
import qualified Prelude<br />
<br />
data Cond a = a : a<br />
<br />
infixl 0 ?<br />
infixl 1 :<br />
<br />
(?) :: Prelude.Bool -> Cond a -> a<br />
Prelude.True ? (x : _) = x<br />
Prelude.False ? (_ : y) = y<br />
<br />
test = 1 Prelude.< 2 ? "yeah" : "no!"<br />
</haskell><br />
<br />
Another version that works in GHC.<br />
<br />
<haskell><br />
data Cond a = a :? a<br />
<br />
infixl 0 ?<br />
infixl 1 :?<br />
<br />
(?) :: Bool -> Cond a -> a<br />
True ? (x :? _) = x<br />
False ? (_ :? y) = y<br />
<br />
test = 1 < 2 ? "Yes" :? "No"<br />
</haskell><br />
== Further reading ==<br />
<br />
* [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-RebindableSyntax Rebindable syntax]<br />
* [http://www.eecs.usma.edu/webs/people/okasaki/pubs.html#hw02 Techniques for Embedding Postfix Languages in Haskell]<br />
<br />
[[Category:Code]]<br />
[[Category:Idioms]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=QualifiedDo&diff=63356QualifiedDo2020-07-23T04:31:38Z<p>Ysangkok: add category Language extensions</p>
<hr />
<div>This extension was [https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3436 merged] in 2020, and it is available in GHC 8.12 and later releases.<br />
<br />
* [https://www.youtube.com/watch?v=TH3cYp3349A Talk from ZuriHac 2020 on Youtube]<br />
* [https://www.tweag.io/blog/2020-07-13-qualified-do-announcement/ Article on Tweag.io]<br />
<br />
[[Category:Language extensions]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Language_extensions&diff=63355Language extensions2020-07-23T04:31:08Z<p>Ysangkok: /* List of language extensions by name */ add QualifiedDo</p>
<hr />
<div>Language extensions are used to enable language features in Haskell that may seem useful in certain cases. They can be used to loosen restrictions in the type system or add completely new language constructs to Haskell.<br />
<br />
They can be enabled using the [http://www.haskell.org/ghc/docs/7.0.4/html/users_guide/pragmas.html#language-pragma LANGUAGE pragma] <br />
<br />
<hask><br />
{-# LANGUAGE <Extension>, <Extension> #-}<br />
</hask> <br />
<br />
or (in GHC) using [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/lang.html flags] <code>-X<Extension></code>. <br />
<br />
Before just using the language extension that fits your need, [[Use of language extensions|think about<br />
when it is useful]] and what risk it may bring to your program.<br />
<br />
== List of language extensions by name ==<br />
<br />
This list is far from complete and needs extension.<br />
<br />
* [[Datatype contexts|DatatypeContexts]] : Add type constraints to your datatype.<br />
* [[Default signatures|DefaultSignatures]]<br />
* Derive:<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveDataTypeable]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveGeneric]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveFunctor]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveFoldable]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#deriving-typeable DeriveTraversable]<br />
** [http://www.haskell.org/ghc/docs/latest/html/users_guide/deriving.html#id616911 GeneralizedNewtypeDeriving]<br />
* [https://downloads.haskell.org/ghc/latest/docs/html/users_guide/glasgow_exts.html#duplicate-record-fields DuplicateRecordFields] (GHC 8.0.1+) : Allow definition of record types with identically-named fields.<br />
* [[Existential type|ExistentialQuantification]]<br />
* [[Flexible contexts|FlexibleContexts]]<br />
* [[Flexiblae instances|FlexibleInstances]] : Allow a type parameter to occure twice within a type class instance.<br />
* [[Functional dependencies|FunctionalDependencies]] : Are used to constrain the parameters of type classes.<br />
* [[GADT]]s : Generalised algebraic datatypes - A more general approach to algebraic datatypes.<br />
* [[Implicit parameters|ImplicitParams]]<br />
* [[KindSignatures]]<br />
* [[Multi-parameter type class|MultiParamTypeClasses]] : Enable multiple type parameters in type classes.<br />
* [[Monomorphism restriction|NoMonomorphismRestriction]]<br />
* [[Overlapping instance|OverlappingInstances]]<br />
* [[Rank-N types|Rank2Types]]<br />
* [[Rank-N types|RankNTypes]]<br />
* [[Scoped type variables|ScopedTypeVariables]]<br />
* [[Template Haskell|TemplateHaskell]]<br />
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#tuple-sections TupleSections] : Allow tuples to be partially applied.<br />
* [[GHC/Type families|TypeFamilies]]<br />
* [[Undecidable instance|UndecidableInstances]]<br />
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#view-patterns ViewPatterns]<br />
* [[QualifiedDo]]<br />
<br />
= See also =<br />
<br />
* [[Use of language extensions]]<br />
<br />
<br />
[[Category:Language extensions]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=QualifiedDo&diff=63354QualifiedDo2020-07-23T04:30:34Z<p>Ysangkok: link tweag blog post and youtube talk</p>
<hr />
<div>This extension was [https://gitlab.haskell.org/ghc/ghc/-/merge_requests/3436 merged] in 2020, and it is available in GHC 8.12 and later releases.<br />
<br />
* [https://www.youtube.com/watch?v=TH3cYp3349A Talk from ZuriHac 2020 on Youtube]<br />
* [https://www.tweag.io/blog/2020-07-13-qualified-do-announcement/ Article on Tweag.io]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Base_package&diff=63353Base package2020-07-22T20:30:58Z<p>Ysangkok: /* Versions */ add 8.10 with 4.14.0.0</p>
<hr />
<div>The '''base package''' contains the [[Prelude]] and its support libraries, and a large collection of useful libraries ranging from data structures to parsing combinators and debugging utilities. It is specific to the GHC implementation of Haskell.<br />
<br />
This package includes the following: <br />
<br />
*[[Arrays]]<br />
<br />
*[[Arrow]]s<br />
<br />
*[[Functor]]s<br />
<br />
*[[Maybe]]<br />
<br />
*[[Monad]]s<br />
<br />
and many others.<br />
<br />
== Versions ==<br />
<br />
The [https://hackage.haskell.org/package/base base] package is shipped alongside the GHC compiler itself, but version numbers for the base package do not match the GHC version number. Here is a table indicating which base package versions ship with which GHC.<br />
<br />
Data is taken from GHC release notes, and, since base 4.7.0.0, the [https://hackage.haskell.org/package/base/changelog changelog.md] file in the base package's source code. Only GHC versions in which the base package's version number was bumped are listed here.<br />
<br />
On the GHC Trac wiki, one can find a more comprehensive [https://ghc.haskell.org/trac/ghc/wiki/Commentary/Libraries/VersionHistory table of versions] that includes ''all'' boot libraries.<br />
<br />
{|<br />
|-<br />
! GHC version<br />
! base version<br />
|-<br />
| 6.10.1 (Nov 2008)<br />
| 4.0.0.0<br />
|-<br />
| 6.10.2 (Apr 2009)<br />
| 4.1.0.0<br />
|-<br />
| 6.12.1 (Dec 2009)<br />
| 4.2.0.0<br />
|-<br />
| 6.12.2 (Apr 2010)<br />
| 4.2.0.1<br />
|-<br />
| 6.12.3 (Jun 2010)<br />
| 4.2.0.2<br />
|-<br />
| 7.0.1 (Nov 2010)<br />
| 4.3.0.0<br />
|-<br />
| 7.0.2 (Mar 2011)<br />
| 4.3.1.0<br />
|-<br />
| 7.2.1 (Aug 2011)<br />
| 4.4.0.0<br />
|-<br />
| 7.2.2 (Nov 2011)<br />
| 4.4.1.0<br />
|-<br />
| 7.4.1 (Feb 2012)<br />
| 4.5.0.0<br />
|-<br />
| 7.4.2 (Jun 2012)<br />
| 4.5.1.0<br />
|-<br />
| 7.6.1 (Sep 2012)<br />
| 4.6.0.0<br />
|-<br />
| 7.6.2 (Jan 2013)<br />
| 4.6.0.1<br />
|-<br />
| 7.8.1 (Apr 2014)<br />
| 4.7.0.0<br />
|-<br />
| 7.8.3 (Jul 2014)<br />
| 4.7.0.1<br />
|-<br />
| 7.8.4 (Dec 2014)<br />
| 4.7.0.2<br />
|-<br />
| 7.10.1 (Apr 2015)<br />
| 4.8.0.0<br />
|-<br />
| 7.10.2 (Jul 2015)<br />
| 4.8.1.0<br />
|-<br />
| 7.10.3 (Dec 2015)<br />
| 4.8.2.0<br />
|-<br />
| 8.0.1 (May 2016)<br />
| 4.9.0.0<br />
|-<br />
| 8.0.2 (Jan 2017)<br />
| 4.9.1.0<br />
|-<br />
| 8.2.1 (Jul 2017)<br />
| 4.10.0.0<br />
|-<br />
| 8.2.2 (Nov 2017)<br />
| 4.10.1.0<br />
|-<br />
| 8.4.1 (Mar 2018)<br />
| 4.11.0.0<br />
|-<br />
| 8.4.2 (Apr 2018)<br />
| 4.11.1.0<br />
<!--<br />
|-<br />
| 8.4.3 (May 2018)<br />
| 4.11.1.0<br />
--><br />
|-<br />
| 8.6.1 (Sep 2018)<br />
| 4.12.0.0<br />
|-<br />
| 8.8.1 (Jul 2019)<br />
| 4.13.0.0<br />
|-<br />
| 8.10.1 (Mar 2020)<br />
| 4.14.0.0<br />
|}<br />
<br />
See also the [https://hackage.haskell.org/package/base hackage page for the base package].<br />
<br />
[[Category:Standard packages]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=IRC_channel&diff=63351IRC channel2020-07-22T06:18:47Z<p>Ysangkok: /* Bots */ document yahb a bit</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 1046<br />
concurrent users, making the channel consistently<br />
[https://netsplit.de/channels/details.php?room=%23haskell&net=freenode one of the most popular]<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 />
{| border="0" <br />
|+ '''#haskell visualized'''<br />
|-<br />
| [[Image:Haskell-current.png|thumb|The social graph, Jan 2008]]<br />
| [[Image:Irc-raw.png|thumb|Daily traffic since 2004]]<br />
|-<br />
| [[Image:Nick-activity.png|thumb|Growth]]<br />
| [[Image:Haskell-wordle-irc.png|thumb|Noun map]]<br />
|}<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://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 fact that the community<br />
is quite tight knit &mdash; we know each other &mdash; 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. New Haskell users should feel entirely comfortable asking questions.<br />
<br />
* Helpful answers should be encouraged with <code>name++</code> karma points, in public, as a reward for providing a good answer.<br />
<br />
* Avoid getting frustrated by negative comments and ambiguous questions. Approach them by asking for details (i.e. [http://en.wikipedia.org/wiki/Socratic_method Socratic questioning]), rather than challenging the competence of the writer (ad hominem). As the channel grows, we see a diverse range of people with different programming backgrounds getting accustomed to Haskell. Be patient and take satisfaction from spreading knowledge.<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 />
== Related channels ==<br />
<br />
In addition to the main Haskell channel there are also:<br />
<br />
=== Language/Country specific ===<br />
<br />
The Freenode staff have asked us to consolidate language channels into the "#haskell-" namespace rather than have them continue on in the "#haskell." namespace. Eventually the language channels below listed with "#haskell." will have to move.<br />
<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #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<br />
| French speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.hr<br />
| Croatian speakers<br />
|-<br />
| #haskell-id<br />
| Indonesian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell-it <br />
| Italian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.jp <br />
| Japanese speakers<br />
|-<br />
| #haskell.scandinavian<br />
| Scandinavian speakers<br />
|-<br />
| #haskell-kr<br />
| Korean speakers<br />
|-<br />
| #haskell.no <br />
| Norwegian speakers<br />
|-<br />
| #haskell.pt<br />
| Portuguese speakers<br />
|-<br />
| #haskell-pl<br />
| Polish 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-ro<br />
| Romanian speakers.<br />
|-<br />
| #haskell.se <br />
| Swedish speakers<br />
|-<br />
| #haskell.tw<br />
| Chinese speakers (mainly in Taiwan)<br />
|-<br />
| #haskell.vn<br />
| Vietnamese speakers<br />
|-<br />
| #chicagohaskell<br />
| [http://chicagohaskell.com Chicago Haskell] programmers group<br />
|}<br />
<br />
=== Platform-specific ===<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #haskell-beginners<br />
| Haskell people focused on teaching and learning Haskell, not just beginners.<br />
|-<br />
| #haskell-offtopic<br />
| Haskell people talking about anything except Haskell itself (no TLS required)<br />
|-<br />
| #haskell-blah <br />
| Haskell people talking about anything except Haskell itself (TLS required)<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-apple<br />
| projects that target iOS or OS X using Haskell. <br />
|-<br />
| #haskell-lisp<br />
| [[Haskell Lisp]] - projects that are creating Lisps written in Haskell, or Haskell implementations written in Lisps. <br />
|-<br />
| #haskell-llvm<br />
| For projects using Haskell and LLVM<br />
|-<br />
| #haskell-overflow<br />
| Overflow conversations<br />
|-<br />
| #haskell-web<br />
| Friendly, practical discussion of haskell web app/framework/server development<br />
|-<br />
| #haskell-robotics<br />
| Discussion about the use of Haskell for robotics applications.<br />
|-<br />
| #arch-haskell <br />
| [[Arch Linux]]/ specific Haskell conversations<br />
|-<br />
| #fedora-haskell<br />
| [https://fedoraproject.org/wiki/Haskell Fedora] Haskell SIG<br />
|-<br />
| #gentoo-haskell <br />
| [[Gentoo]]/Linux specific Haskell conversations<br />
|}<br />
<br />
=== Projects using haskell ===<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel <br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #darcs <br />
| [[Darcs]] revision control system<br />
|-<br />
| #diagrams<br />
| [[Diagrams]] EDSL<br />
|-<br />
| #hackage<br />
| Haskell's software distribution infrastructure<br />
|-<br />
| #haskell-lens<br />
| [[Lens]] discussions<br />
|-<br />
| #haskell-stack<br />
| [https://github.com/commercialhaskell/stack/tree/master/doc Stack] discussions<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 />
| #snowdrift <br />
| [https://snowdrift.coop Snowdrift.coop] Yesod-based web platform for funding free/libre/open works, welcomes Haskell volunteer devs including beginners<br />
|-<br />
| #snapframework<br />
| [http://snapframework.com/ Snap] web framework<br />
|-<br />
| #xmonad<br />
| [http://xmonad.org Xmonad] tiling window manager<br />
|-<br />
| #yesod<br />
| [http://yesodweb.com Yesod] web framework<br />
|-<br />
| #yampa<br />
| [https://wiki.haskell.org/Yampa Yampa] Arrowized FRP<br />
|}<br />
<br />
== Logs ==<br />
<br />
'''Logs''' are kept at http://tunes.org/~nef/logs/haskell/ and can be searched at http://ircbrowse.net/browse/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"<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 />
| @tell <nick> <msg> -- same as @ask<br />
| Next time <nick> speaks in channel they will be notified they have a message pending and how to receive it.<br />
|}<br />
<br />
=== yahb ===<br />
If lambdabot doesn't cut it for you, there is a bot called yahb which runs your request in an actual GHCi prompt, so you can use IO.<br />
<br />
Try e.g. <tt>% readFile "/proc/self/environ"</tt><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>Ysangkokhttps://wiki.haskell.org/index.php?title=IRC_channel&diff=63350IRC channel2020-07-22T06:16:56Z<p>Ysangkok: remove section preflex since bot is gone. revert if it comes back</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 1046<br />
concurrent users, making the channel consistently<br />
[https://netsplit.de/channels/details.php?room=%23haskell&net=freenode one of the most popular]<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 />
{| border="0" <br />
|+ '''#haskell visualized'''<br />
|-<br />
| [[Image:Haskell-current.png|thumb|The social graph, Jan 2008]]<br />
| [[Image:Irc-raw.png|thumb|Daily traffic since 2004]]<br />
|-<br />
| [[Image:Nick-activity.png|thumb|Growth]]<br />
| [[Image:Haskell-wordle-irc.png|thumb|Noun map]]<br />
|}<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://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 fact that the community<br />
is quite tight knit &mdash; we know each other &mdash; 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. New Haskell users should feel entirely comfortable asking questions.<br />
<br />
* Helpful answers should be encouraged with <code>name++</code> karma points, in public, as a reward for providing a good answer.<br />
<br />
* Avoid getting frustrated by negative comments and ambiguous questions. Approach them by asking for details (i.e. [http://en.wikipedia.org/wiki/Socratic_method Socratic questioning]), rather than challenging the competence of the writer (ad hominem). As the channel grows, we see a diverse range of people with different programming backgrounds getting accustomed to Haskell. Be patient and take satisfaction from spreading knowledge.<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 />
== Related channels ==<br />
<br />
In addition to the main Haskell channel there are also:<br />
<br />
=== Language/Country specific ===<br />
<br />
The Freenode staff have asked us to consolidate language channels into the "#haskell-" namespace rather than have them continue on in the "#haskell." namespace. Eventually the language channels below listed with "#haskell." will have to move.<br />
<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #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<br />
| French speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.hr<br />
| Croatian speakers<br />
|-<br />
| #haskell-id<br />
| Indonesian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell-it <br />
| Italian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.jp <br />
| Japanese speakers<br />
|-<br />
| #haskell.scandinavian<br />
| Scandinavian speakers<br />
|-<br />
| #haskell-kr<br />
| Korean speakers<br />
|-<br />
| #haskell.no <br />
| Norwegian speakers<br />
|-<br />
| #haskell.pt<br />
| Portuguese speakers<br />
|-<br />
| #haskell-pl<br />
| Polish 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-ro<br />
| Romanian speakers.<br />
|-<br />
| #haskell.se <br />
| Swedish speakers<br />
|-<br />
| #haskell.tw<br />
| Chinese speakers (mainly in Taiwan)<br />
|-<br />
| #haskell.vn<br />
| Vietnamese speakers<br />
|-<br />
| #chicagohaskell<br />
| [http://chicagohaskell.com Chicago Haskell] programmers group<br />
|}<br />
<br />
=== Platform-specific ===<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #haskell-beginners<br />
| Haskell people focused on teaching and learning Haskell, not just beginners.<br />
|-<br />
| #haskell-offtopic<br />
| Haskell people talking about anything except Haskell itself (no TLS required)<br />
|-<br />
| #haskell-blah <br />
| Haskell people talking about anything except Haskell itself (TLS required)<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-apple<br />
| projects that target iOS or OS X using Haskell. <br />
|-<br />
| #haskell-lisp<br />
| [[Haskell Lisp]] - projects that are creating Lisps written in Haskell, or Haskell implementations written in Lisps. <br />
|-<br />
| #haskell-llvm<br />
| For projects using Haskell and LLVM<br />
|-<br />
| #haskell-overflow<br />
| Overflow conversations<br />
|-<br />
| #haskell-web<br />
| Friendly, practical discussion of haskell web app/framework/server development<br />
|-<br />
| #haskell-robotics<br />
| Discussion about the use of Haskell for robotics applications.<br />
|-<br />
| #arch-haskell <br />
| [[Arch Linux]]/ specific Haskell conversations<br />
|-<br />
| #fedora-haskell<br />
| [https://fedoraproject.org/wiki/Haskell Fedora] Haskell SIG<br />
|-<br />
| #gentoo-haskell <br />
| [[Gentoo]]/Linux specific Haskell conversations<br />
|}<br />
<br />
=== Projects using haskell ===<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel <br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #darcs <br />
| [[Darcs]] revision control system<br />
|-<br />
| #diagrams<br />
| [[Diagrams]] EDSL<br />
|-<br />
| #hackage<br />
| Haskell's software distribution infrastructure<br />
|-<br />
| #haskell-lens<br />
| [[Lens]] discussions<br />
|-<br />
| #haskell-stack<br />
| [https://github.com/commercialhaskell/stack/tree/master/doc Stack] discussions<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 />
| #snowdrift <br />
| [https://snowdrift.coop Snowdrift.coop] Yesod-based web platform for funding free/libre/open works, welcomes Haskell volunteer devs including beginners<br />
|-<br />
| #snapframework<br />
| [http://snapframework.com/ Snap] web framework<br />
|-<br />
| #xmonad<br />
| [http://xmonad.org Xmonad] tiling window manager<br />
|-<br />
| #yesod<br />
| [http://yesodweb.com Yesod] web framework<br />
|-<br />
| #yampa<br />
| [https://wiki.haskell.org/Yampa Yampa] Arrowized FRP<br />
|}<br />
<br />
== Logs ==<br />
<br />
'''Logs''' are kept at http://tunes.org/~nef/logs/haskell/ and can be searched at http://ircbrowse.net/browse/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"<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 />
| @tell <nick> <msg> -- same as @ask<br />
| Next time <nick> speaks in channel they will be notified they have a message pending and how to receive it.<br />
|}<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>Ysangkokhttps://wiki.haskell.org/index.php?title=IRC_channel&diff=63349IRC channel2020-07-22T06:16:20Z<p>Ysangkok: remove alignment on tables, it would cause tables to appear next to each other and looks terrible. better just keep it simple, have default alignment everywhere</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 1046<br />
concurrent users, making the channel consistently<br />
[https://netsplit.de/channels/details.php?room=%23haskell&net=freenode one of the most popular]<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 />
{| border="0" <br />
|+ '''#haskell visualized'''<br />
|-<br />
| [[Image:Haskell-current.png|thumb|The social graph, Jan 2008]]<br />
| [[Image:Irc-raw.png|thumb|Daily traffic since 2004]]<br />
|-<br />
| [[Image:Nick-activity.png|thumb|Growth]]<br />
| [[Image:Haskell-wordle-irc.png|thumb|Noun map]]<br />
|}<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://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 fact that the community<br />
is quite tight knit &mdash; we know each other &mdash; 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. New Haskell users should feel entirely comfortable asking questions.<br />
<br />
* Helpful answers should be encouraged with <code>name++</code> karma points, in public, as a reward for providing a good answer.<br />
<br />
* Avoid getting frustrated by negative comments and ambiguous questions. Approach them by asking for details (i.e. [http://en.wikipedia.org/wiki/Socratic_method Socratic questioning]), rather than challenging the competence of the writer (ad hominem). As the channel grows, we see a diverse range of people with different programming backgrounds getting accustomed to Haskell. Be patient and take satisfaction from spreading knowledge.<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 />
== Related channels ==<br />
<br />
In addition to the main Haskell channel there are also:<br />
<br />
=== Language/Country specific ===<br />
<br />
The Freenode staff have asked us to consolidate language channels into the "#haskell-" namespace rather than have them continue on in the "#haskell." namespace. Eventually the language channels below listed with "#haskell." will have to move.<br />
<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #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<br />
| French speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.hr<br />
| Croatian speakers<br />
|-<br />
| #haskell-id<br />
| Indonesian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell-it <br />
| Italian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.jp <br />
| Japanese speakers<br />
|-<br />
| #haskell.scandinavian<br />
| Scandinavian speakers<br />
|-<br />
| #haskell-kr<br />
| Korean speakers<br />
|-<br />
| #haskell.no <br />
| Norwegian speakers<br />
|-<br />
| #haskell.pt<br />
| Portuguese speakers<br />
|-<br />
| #haskell-pl<br />
| Polish 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-ro<br />
| Romanian speakers.<br />
|-<br />
| #haskell.se <br />
| Swedish speakers<br />
|-<br />
| #haskell.tw<br />
| Chinese speakers (mainly in Taiwan)<br />
|-<br />
| #haskell.vn<br />
| Vietnamese speakers<br />
|-<br />
| #chicagohaskell<br />
| [http://chicagohaskell.com Chicago Haskell] programmers group<br />
|}<br />
<br />
=== Platform-specific ===<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #haskell-beginners<br />
| Haskell people focused on teaching and learning Haskell, not just beginners.<br />
|-<br />
| #haskell-offtopic<br />
| Haskell people talking about anything except Haskell itself (no TLS required)<br />
|-<br />
| #haskell-blah <br />
| Haskell people talking about anything except Haskell itself (TLS required)<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-apple<br />
| projects that target iOS or OS X using Haskell. <br />
|-<br />
| #haskell-lisp<br />
| [[Haskell Lisp]] - projects that are creating Lisps written in Haskell, or Haskell implementations written in Lisps. <br />
|-<br />
| #haskell-llvm<br />
| For projects using Haskell and LLVM<br />
|-<br />
| #haskell-overflow<br />
| Overflow conversations<br />
|-<br />
| #haskell-web<br />
| Friendly, practical discussion of haskell web app/framework/server development<br />
|-<br />
| #haskell-robotics<br />
| Discussion about the use of Haskell for robotics applications.<br />
|-<br />
| #arch-haskell <br />
| [[Arch Linux]]/ specific Haskell conversations<br />
|-<br />
| #fedora-haskell<br />
| [https://fedoraproject.org/wiki/Haskell Fedora] Haskell SIG<br />
|-<br />
| #gentoo-haskell <br />
| [[Gentoo]]/Linux specific Haskell conversations<br />
|}<br />
<br />
=== Projects using haskell ===<br />
{| border="1" cellspacing="0" cellpadding="5"<br />
! Channel <br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #darcs <br />
| [[Darcs]] revision control system<br />
|-<br />
| #diagrams<br />
| [[Diagrams]] EDSL<br />
|-<br />
| #hackage<br />
| Haskell's software distribution infrastructure<br />
|-<br />
| #haskell-lens<br />
| [[Lens]] discussions<br />
|-<br />
| #haskell-stack<br />
| [https://github.com/commercialhaskell/stack/tree/master/doc Stack] discussions<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 />
| #snowdrift <br />
| [https://snowdrift.coop Snowdrift.coop] Yesod-based web platform for funding free/libre/open works, welcomes Haskell volunteer devs including beginners<br />
|-<br />
| #snapframework<br />
| [http://snapframework.com/ Snap] web framework<br />
|-<br />
| #xmonad<br />
| [http://xmonad.org Xmonad] tiling window manager<br />
|-<br />
| #yesod<br />
| [http://yesodweb.com Yesod] web framework<br />
|-<br />
| #yampa<br />
| [https://wiki.haskell.org/Yampa Yampa] Arrowized FRP<br />
|}<br />
<br />
== Logs ==<br />
<br />
'''Logs''' are kept at http://tunes.org/~nef/logs/haskell/ and can be searched at http://ircbrowse.net/browse/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"<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 />
| @tell <nick> <msg> -- same as @ask<br />
| Next time <nick> speaks in channel they will be notified they have a message pending and how to receive it.<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> Desn't exist as of July 22, 2020.<br />
<br />
To execute any of the commands below, you must prefix you message with an at-sign. For example, try <tt>@list</tt>.<br />
<br />
{| border="1" cellspacing="0" cellpadding="5"<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 />
=== 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>Ysangkokhttps://wiki.haskell.org/index.php?title=IRC_channel&diff=63348IRC channel2020-07-22T06:11:32Z<p>Ysangkok: /* preflex */ explain that an at-sign is needed</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 1046<br />
concurrent users, making the channel consistently<br />
[https://netsplit.de/channels/details.php?room=%23haskell&net=freenode one of the most popular]<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 />
{| border="0" align="right"<br />
|+ '''#haskell visualized'''<br />
|-<br />
| [[Image:Haskell-current.png|thumb|The social graph, Jan 2008]]<br />
| [[Image:Irc-raw.png|thumb|Daily traffic since 2004]]<br />
|-<br />
| [[Image:Nick-activity.png|thumb|Growth]]<br />
| [[Image:Haskell-wordle-irc.png|thumb|Noun map]]<br />
|}<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://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 fact that the community<br />
is quite tight knit &mdash; we know each other &mdash; 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. New Haskell users should feel entirely comfortable asking questions.<br />
<br />
* Helpful answers should be encouraged with <code>name++</code> karma points, in public, as a reward for providing a good answer.<br />
<br />
* Avoid getting frustrated by negative comments and ambiguous questions. Approach them by asking for details (i.e. [http://en.wikipedia.org/wiki/Socratic_method Socratic questioning]), rather than challenging the competence of the writer (ad hominem). As the channel grows, we see a diverse range of people with different programming backgrounds getting accustomed to Haskell. Be patient and take satisfaction from spreading knowledge.<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 />
== Related channels ==<br />
<br />
In addition to the main Haskell channel there are also:<br />
<br />
=== Language/Country specific ===<br />
<br />
The Freenode staff have asked us to consolidate language channels into the "#haskell-" namespace rather than have them continue on in the "#haskell." namespace. Eventually the language channels below listed with "#haskell." will have to move.<br />
<br />
{| border="1" cellspacing="0" cellpadding="5" align="left"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #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<br />
| French speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.hr<br />
| Croatian speakers<br />
|-<br />
| #haskell-id<br />
| Indonesian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell-it <br />
| Italian speakers (note the hyphen! in the channel name)<br />
|-<br />
| #haskell.jp <br />
| Japanese speakers<br />
|-<br />
| #haskell.scandinavian<br />
| Scandinavian speakers<br />
|-<br />
| #haskell-kr<br />
| Korean speakers<br />
|-<br />
| #haskell.no <br />
| Norwegian speakers<br />
|-<br />
| #haskell.pt<br />
| Portuguese speakers<br />
|-<br />
| #haskell-pl<br />
| Polish 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-ro<br />
| Romanian speakers.<br />
|-<br />
| #haskell.se <br />
| Swedish speakers<br />
|-<br />
| #haskell.tw<br />
| Chinese speakers (mainly in Taiwan)<br />
|-<br />
| #haskell.vn<br />
| Vietnamese speakers<br />
|-<br />
| #chicagohaskell<br />
| [http://chicagohaskell.com Chicago Haskell] programmers group<br />
|}<br />
<br />
=== Platform-specific ===<br />
{| border="1" cellspacing="0" cellpadding="5" align="left"<br />
! Channel<br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #haskell-beginners<br />
| Haskell people focused on teaching and learning Haskell, not just beginners.<br />
|-<br />
| #haskell-offtopic<br />
| Haskell people talking about anything except Haskell itself (no TLS required)<br />
|-<br />
| #haskell-blah <br />
| Haskell people talking about anything except Haskell itself (TLS required)<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-apple<br />
| projects that target iOS or OS X using Haskell. <br />
|-<br />
| #haskell-lisp<br />
| [[Haskell Lisp]] - projects that are creating Lisps written in Haskell, or Haskell implementations written in Lisps. <br />
|-<br />
| #haskell-llvm<br />
| For projects using Haskell and LLVM<br />
|-<br />
| #haskell-overflow<br />
| Overflow conversations<br />
|-<br />
| #haskell-web<br />
| Friendly, practical discussion of haskell web app/framework/server development<br />
|-<br />
| #haskell-robotics<br />
| Discussion about the use of Haskell for robotics applications.<br />
|-<br />
| #arch-haskell <br />
| [[Arch Linux]]/ specific Haskell conversations<br />
|-<br />
| #fedora-haskell<br />
| [https://fedoraproject.org/wiki/Haskell Fedora] Haskell SIG<br />
|-<br />
| #gentoo-haskell <br />
| [[Gentoo]]/Linux specific Haskell conversations<br />
|}<br />
<br />
=== Projects using haskell ===<br />
{| border="1" cellspacing="0" cellpadding="5" align="left"<br />
! Channel <br />
! Purpose<br />
|-<br />
| style="width: 20%;" | #darcs <br />
| [[Darcs]] revision control system<br />
|-<br />
| #diagrams<br />
| [[Diagrams]] EDSL<br />
|-<br />
| #hackage<br />
| Haskell's software distribution infrastructure<br />
|-<br />
| #haskell-lens<br />
| [[Lens]] discussions<br />
|-<br />
| #haskell-stack<br />
| [https://github.com/commercialhaskell/stack/tree/master/doc Stack] discussions<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 />
| #snowdrift <br />
| [https://snowdrift.coop Snowdrift.coop] Yesod-based web platform for funding free/libre/open works, welcomes Haskell volunteer devs including beginners<br />
|-<br />
| #snapframework<br />
| [http://snapframework.com/ Snap] web framework<br />
|-<br />
| #xmonad<br />
| [http://xmonad.org Xmonad] tiling window manager<br />
|-<br />
| #yesod<br />
| [http://yesodweb.com Yesod] web framework<br />
|-<br />
| #yampa<br />
| [https://wiki.haskell.org/Yampa Yampa] Arrowized FRP<br />
|}<br />
<br />
== Logs ==<br />
<br />
'''Logs''' are kept at http://tunes.org/~nef/logs/haskell/ and can be searched at http://ircbrowse.net/browse/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 />
| @tell <nick> <msg> -- same as @ask<br />
| Next time <nick> speaks in channel they will be notified they have a message pending and how to receive it.<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> Desn't exist as of July 22, 2020.<br />
<br />
To execute any of the commands below, you must prefix you message with an at-sign. For example, try <tt>@list</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 />
=== 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>Ysangkokhttps://wiki.haskell.org/index.php?title=MonadFail_Proposal&diff=63040MonadFail Proposal2019-09-25T01:17:43Z<p>Ysangkok: /* Adapting old code */ ghc 7.16 is ghc 8.8</p>
<hr />
<div>'''Note:''' this proposal page has been moved to [https://prime.haskell.org/wiki/Libraries/Proposals/MonadFail the Haskell Prime Wiki]; the article below is unmaintained.<br />
<br />
<br />
== <code>MonadFail</code> proposal (MFP) ==<br />
<br />
A couple of years ago, we proposed to make <code>Applicative</code> a superclass of <code>Monad</code> which successfully killed the single most ugly thing in Haskell as of GHC 7.10.<br />
<br />
Now, it's time to tackle the other major issue with <code>Monad</code> <code>fail</code> being a part of it.<br />
<br />
You can contact me as usual via IRC/Freenode as ''quchen'', or by email to ''dluposchainsky at the email service of Google''. This file was posted on the ghc-devs@ and [http://permalink.gmane.org/gmane.comp.lang.haskell.libraries/24910 libraries@ mailing lists], as well as on [http://www.reddit.com/r/haskell/comments/397k1a/monadfail_proposal_mfp_moving_fail_out_of_monad/ Reddit].<br />
<br />
This proposal was first posted on [https://github.com/quchen/articles/blob/master/monad_fail.md quchen's articles Github repo].<br />
<br />
=== Overview ===<br />
<br />
* '''The problem''' - reason for the proposal<br />
* '''MonadFail class''' - the solution<br />
* '''Discussion''' - explaining our design choices<br />
* '''Adapting old code''' - how to prepare current code to transition smoothly<br />
* '''Estimating the breakage''' - how much stuff we will break<br />
* '''Transitional strategy''' - how to break as little as possible while transitioning<br />
* '''Current status'''<br />
<br />
=== The problem ===<br />
<br />
Currently, the <code><-</code> symbol is unconditionally desugared as follows:<br />
<br />
<syntaxhighlight lang="haskell"><br />
do pat <- computation >>> let f pat = more<br />
more >>> f _ = fail "..."<br />
>>> in computation >>= f<br />
</syntaxhighlight><br />
<br />
The problem with this is that <code>fail</code> cannot (!) be sensibly implemented for many monads, for example <code>Either</code>, <code>State</code>, <code>IO</code>, and <code>Reader</code>. In those cases it defaults to <code>error</code> As a consequence, in current Haskell, you can not use <code>Monad</code> polymorphic code safely, because although it claims to work for all <code>Monad</code> , it might just crash on you. This kind of implicit non-totality baked into the class is ''terrible''.<br />
<br />
The goal of this proposal is adding the <code>fail</code> only when necessary and reflecting that in the type signature of the <code>do</code> block, so that it can be used safely, and more importantly, is guaranteed not to be used if the type signature does not say so.<br />
<br />
=== <code>MonadFail</code> class ===<br />
<br />
To fix this, introduce a new typeclass:<br />
<br />
<syntaxhighlight lang="haskell"><br />
class Monad m => MonadFail m where<br />
fail :: String -> m a<br />
</syntaxhighlight><br />
<br />
Desugaring can now be changed to produce this constraint when necessary. For this, we have to decide when a pattern match can not fail; if this is the case, we can omit inserting the <code>fail</code> call.<br />
<br />
The most trivial examples of unfailable patterns are of course those that match anywhere unconditionally,<br />
<br />
<syntaxhighlight lang="haskell"><br />
do x <- action >>> let f x = more<br />
more >>> in action >>= f<br />
</syntaxhighlight><br />
<br />
In particular, the programmer can assert any pattern be unfailable by making it irrefutable using a prefix tilde:<br />
<br />
<syntaxhighlight lang="haskell"><br />
do ~pat <- action >>> let f ~pat = more<br />
more >>> in action >>= f<br />
</syntaxhighlight><br />
<br />
A class of patterns that are conditionally failable are <code>newtype</code> , and single constructor <code>data</code> types, which are unfailable by themselves, but may fail if matching on their fields is done with failable patterns.<br />
<br />
<syntaxhighlight lang="haskell"><br />
data Newtype a = Newtype a<br />
<br />
-- "x" cannot fail<br />
do Newtype x <- action >>> let f (Newtype x) = more<br />
more >>> in action >>= f<br />
<br />
-- "Just x" can fail<br />
do Newtype (Just x) <- action >>> let f (Newtype (Just x)) = more<br />
more >>> f _ = fail "..."<br />
>>> in action >>= f<br />
</syntaxhighlight><br />
<br />
<code>ViewPatterns</code> are as failable as the pattern the view is matched against. Patterns like <code>(Just -> Just x)</code> should generate a <code>MonadFail</code> constraint even when it's "obvious" from the view's implementation that the pattern will always match. From an implementor's perspective, this means that only types (and their constructors) have to be looked at, not arbitrary values (like functions), which is impossible to do statically in general.<br />
<br />
<syntaxhighlight lang="haskell"><br />
do (view -> pat) <- action >>> let f (view -> pat) = more<br />
more >>> f _ = fail "..."<br />
>>> in action >>= f<br />
<br />
do (view -> ~pat) <- action >>> let f (view -> ~pat) = more<br />
more >>> in action >>= f<br />
</syntaxhighlight><br />
<br />
[Edward Kmett: `(view -> pat)` should be unfailing iff pat is unfailing.]<br />
<br />
A similar issue arises for <code>PatternSynonyms</code> which we cannot inspect during compilation sufficiently. A pattern synonym will therefore always be considered failable.<br />
<br />
<syntaxhighlight lang="haskell"><br />
do PatternSynonym x <- action >>> let f PatternSynonym x = more<br />
more >>> f _ = fail "..."<br />
>>> in action >>= f<br />
</syntaxhighlight><br />
<br />
[Edward Kmett: We have the contents of the pattern synonym available to us at the definition site. With some work we should be able to expose it enough that the compiler can see through it:<br />
<br />
<syntaxhighlight lang="haskell"><br />
pattern Foo a b = Bar a 0 b<br />
pattern Baz a b c <- Quux a b c<br />
</syntaxhighlight><br />
<br />
Both of those tell us the "real" desugaring as just another pattern we could recurse into.]<br />
<br />
=== Discussion ===<br />
<br />
* What laws should <code>fail</code> follow?<br />
** '''Left zero''': <code>∀ s f. fail s >>= f ≡ fail s</code>.<br />
** '''Right zero''': <code>∀ v s. v >> fail s ≡ fail s</code>.<br />
* What is the relationship to <code>MonadPlus</code>?<br />
** As the laws above indicate, <code>fail</code> is a close relative of <code>mzero</code>. We could suggest a default definition of <code>fail _ = mzero</code>, which shows the intended usage and effect of the <code>MonadFail</code> class.<br />
** However, we should not remove <code>fail</code> and use only <code>mzero</code> instead. <br />
*** Not all types with <code>Monad</code> instances have <code>MonadPlus</code> instances.<br />
*** Some types do use the <code>String</code> argument to <code>fail</code>. For example, a parser might fail with a message involving positional information. <code>Binary</code> uses <code>fail</code> as their only interface to fail a decoding step.<br />
*** Some types have different definitions for <code>mzero</code> and <code>fail</code>. Although <code>STM</code> is <code>MonadPlus</code> it uses the default <code>fail = error</code>. It should therefore not get a <code>MonadFail</code> instance.<br />
* Rename <code>fail</code>?<br />
** '''No.''' Old code might use <code>fail</code> explicitly and we should avoid breaking it. The Report talks about <code>fail</code> and we have a solid migration strategy that does not require a renaming.<br />
* Remove the <code>String</code> argument?<br />
** '''No.''' The <code>String</code> might help error reporting and debugging. <code>String</code> may be ugly, but it's the de facto standard for simple text in GHC. No high performance string operations are to be expected with <code>fail</code> so this breaking change would in no way be justified. Also note that explicit <code>fail</code> calls would break if we removed the argument.<br />
* How sensitive would existing code be to subtle changes in the strictness behaviour of <code>do</code> notation pattern matching?<br />
** '''It doesn't.''' The implementation does not affect strictness at all, only the desugaring step. Care must be taken when fixing warnings by making patterns irrefutable using <code>~</code> as that ''does'' affect strictness. (Cf. difference between lazy/strict State)<br />
* Do we need a class constraint (e.g. <code>Monad</code>) on <code>MonadFail</code>?<br />
** '''Yes.''' The intended use of <code>fail</code> is for desugaring <code>do</code>-notation, not generally for any <code>String -> m a</code> function. Given that goal, we would rather keep the constraints simple as <code>MonadFail m =></code> rather than the somewhat redundant <code>(Monad m, MonadFail m) =></code>.<br />
* Can we relax the class constraint from <code>Monad</code> to <code>Applicative</code>?<br />
** We don't necessarily have to choose now. Since <code>Applicative</code> is a superclass of <code>Monad</code>, it is possible to change the superclass for <code>MonadFail</code> to <code>Applicative</code> later. This will naturally require a migration period, and the name will, of course, become misleading.<br />
** For the sake of discussion, let's use the following definition:<syntaxhighlight lang="haskell">class Applicative f => ApplicativeFail f where fail :: String -> f a</syntaxhighlight><br />
** '''Pros'''<br />
*** <code>ApplicativeDo</code> is coming, and <code>fail</code> may be useful to combine pattern matching and <code>Applicative</code> code.<br />
*** If the <code>Monad</code> constraint is kept, that would force <code>Applicative</code> code with pattern matching to be <code>Monad</code> code.<br />
** '''Cons'''<br />
*** The constraints for <code>Monad</code> code using <code>fail</code> become <code>(Monad m, ApplicativeFail m) =></code> instead of the simpler <code>MonadFail m =></code>. If we expect the common use of <code>fail</code> to be in <code>Monad</code> — not <code>Applicative</code> — <code>do</code>-notation, this leaves us with more verbose constraints.<br />
** Here are alternative definitions (with names open to debate) that would allow us to keep the constraints simple:<br />
*** <syntaxhighlight lang="haskell">class Applicative f => ApplicativeFail f where failA :: String -> f a</syntaxhighlight><br />
*** <syntaxhighlight lang="haskell">class ApplicativeFail m => MonadFail m where fail :: String -> m a; fail = failA</syntaxhighlight><br />
*** Since we do not have much experience using <code>ApplicativeDo</code>, it is not yet clear that this large of a change is useful.<br />
* Which types with <code>Monad</code> instances will not have <code>MonadFail</code> instances?<br />
** <code>base</code>: <code>Either</code><br />
** <code>transformers</code>:<br />
** <code>stm</code>: <code>STM</code><br />
* What <code>MonadFail</code> instances will be created?<br />
** <code>base</code>: <code>IO</code><br />
** <code>transformers</code>:<br />
*** Proposal for an <code>Either</code> instance using <code>Monad</code> instance in <code>Control.Monad.Trans.Error</code>:<syntaxhighlight lang="haskell">instance MonadFail (Either String) where fail = Left </syntaxhighlight><br />
<br />
=== Adapting old code ===<br />
<br />
<ul><br />
<li>Help! My code is broken because of a missing <code>MonadFail</code> instance! ''Here are your options:''<br />
<ol><li>Write a <code>MonadFail</code> instance (and bring it into scope)<br />
<syntaxhighlight lang="haskell"><br />
#if !MIN_VERSION_base(4,11,0)<br />
-- Control.Monad.Fail import is redundant since GHC 8.8.1<br />
import qualified Control.Monad.Fail as Fail<br />
#endif<br />
import Control.Monad<br />
<br />
instance Monad Foo where<br />
(>>=) = <...bind impl...><br />
-- NB: <code>return</code> defaults to <code>pure</code><br />
#if !MIN_VERSION_base(4,11,0)<br />
-- Monad(fail) was removed in GHC 8.8.1<br />
fail = Fail.fail<br />
#endif<br />
<br />
instance MonadFail Foo where<br />
fail = <...fail implementation...><br />
</syntaxhighlight></li><br />
<li>Change your pattern to be irrefutable</li><br />
<li>Emulate the old behaviour by desugaring the pattern match by hand:<br />
<syntaxhighlight lang="haskell"><br />
do Left e <- foobar<br />
stuff<br />
</syntaxhighlight> becomes <syntaxhighlight lang="haskell"><br />
do x <- foobar<br />
e <- case x of<br />
Left e' -> e'<br />
Right r -> error "Pattern match failed" -- Boooo<br />
stuff<br />
</syntaxhighlight><br />
The point is you'll have to do your dirty laundry yourself now if you have a value that ''you'' know will always match, and if you don't handle the other patterns you'll get incompleteness warnings, and the compiler won't silently eat those for you.</li><br />
</ol></li><br />
<li>Help! My code is broken because you removed <code>fail</code> from <code>Monad</code> but my class defines it! ''Delete that part of the instance definition.''</li></ul><br />
<br />
=== Esimating the breakage ===<br />
<br />
Using our initial implementation, I compiled stackage-nightly, and grepped the logs for the warnings. Assuming my implementation is correct, the number of "missing <code>MonadFail</code> warnings generated is 487. Note that I filtered out <code>[]</code> <code>Maybe</code> and <code>ReadPrec</code> since those can be given a <code>MonadFail</code> instance from within GHC, and no breakage is expected from them.<br />
The build logs can be found [https://www.dropbox.com/s/knz0i979skam4zs/stackage-build.tar.xz?dl=0 here]. Search for "failable pattern" to find your way to the still pretty raw warnings.<br />
<br />
Here are some commands you might find interesting for exploring the logs:<br />
<br />
<syntaxhighlight lang="bash"><br />
# List all packages generating warnings (57 of them)<br />
grep "is used in the context" '' | \<br />
grep -v '(‘\[|Maybe|ReadPrec)' | \<br />
perl -pe 's#^(.'')\.log.''$#\1#' | \<br />
uniq -u<br />
<br />
# Histogram of the breaking contexts (mostly IO and parsers)<br />
grep "is used in the context" '' | \<br />
grep -v '(‘\[|Maybe|ReadPrec)' | \<br />
perl -pe 's#^.''in the context ‘([^ ]+).''$#\1#' | \<br />
sort | \<br />
uniq -c | \<br />
sort -rg<br />
</syntaxhighlight><br />
<br />
=== Transitional strategy ===<br />
<br />
The roadmap is similar to the [https://github.com/quchen/articles/blob/master/applicative_monad.md AMP], the main difference being that since <code>MonadFail</code> does not exist yet, we have to introduce new functionality and then switch to it.<br />
<br />
<ol><br />
<li>GHC 8.0 / base-4.9<br />
<ul><br />
<li>Add module <code>Control.Monad.Fail</code> with new class <code>MonadFail(fail)</code> so people can start writing instances for it. <code>Control.Monad</code> only re-exports the class <code>MonadFail</code> but not its <code>fail</code> method. NB: At this point, <code>Control.Monad.Fail.fail</code> clashes with <code>Prelude.fail</code> and <code>Control.Monad.fail</code>.</li><br />
<li>Add a language extension <code>-XMonadFailDesugaring</code> that changes desugaring to use <code>MonadFail(fail)</code> instead of <code>Monad(fail)</code> This has the effect that typechecking will infer a <code>MonadFail</code> constraint for <code>do</code> blocks with failable patterns, just as it is planned to do when the entire thing is done.</li><br />
<li>Add a warning when a <code>do</code> block that contains a failable pattern is desugared, but there is no <code>MonadFail</code> instance in scope: "Please add the instance or change your pattern matching." Add a flag to control whether this warning appears, but leave it off by default.</li><br />
<li>Add a warning when an instance implements the <code>fail</code> function (or when <code>fail</code> is imported as a method of <code>Monad</code> , as it will be removed from the <code>Monad</code> class in the future. (See also [https://ghc.haskell.org/trac/ghc/ticket/10071 GHC #10071]). Leave it off by default.</li><br />
</ul><br />
</li><br />
<li>GHC 8.4<br />
<ul><br />
<li>Turn on the warning about missing <code>MonadFail</code> instances that we added in 8.0 by default.</li><br />
</ul><br />
</li><br />
<li>GHC 8.6<br />
<ul><br />
<li>Switch <code>-XMonadFailDesugaring</code> on by default.</li><br />
<li>Warnings are still issued if the desugaring extension has been explicitly disabled.</li><br />
<li>Turn on the warning about explicit definition of `fail` in Monad that we added in 8.0 by default.</li><br />
</ul><br />
</li><br />
<li>GHC 8.8<br />
<ul><br />
<li>Remove <code>-XMonadFailDesugaring</code> leaving its effects on at all times.</li><br />
<li>Remove <code>fail</code> from <code>Monad</code></li><br />
<li>Instead, re-export <code>Control.Monad.Fail.fail</code> as <code>Prelude.fail</code> and <code>Control.Monad.fail</code></li><br />
<li><code>Control.Monad.Fail</code> is now a redundant module that can be considered deprecated.</li><br />
</ul><br />
</li><br />
</ol><br />
<br />
=== Current status ===<br />
<br />
* [https://wiki.haskell.org/ZuriHac2015 ZuriHac 2015 (29.5. - 31.5.)]: Franz Thoma (@fmthoma) and me (David Luposchainsky aka @quchen) started implementing the MFP in GHC.<br />
** Desugaring to the new <code>fail</code> can be controlled via a new language extension, <code>MonadFailDesugaring</code><br />
** If the language extension is turned off, a warning will be emitted for code that would break if it was enabled.<br />
** Warnings are emitted for types that ''have'' a ''MonadFail'' instance. This still needs to be fixed.<br />
** The error messages are readable, but should be more so. We're still on this.<br />
* 2015-06-09: Estimated breakage by compiling Stackage. Smaller than expected.<br />
* 2015-06-09 (late): Published. People seem to like the idea, with a couple of pain points remaining.<br />
* 2015-06-16: [https://github.com/quchen/articles/blob/master/monad_fail_update1.md Update 1 posted.]<br />
* 2015-09-18: [https://phabricator.haskell.org/D1248 Patch nearly finished. Some nontrivial tests still fail.]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Es/Librerias_y_Herramientas/Estructuras_de_Datos&diff=63009Es/Librerias y Herramientas/Estructuras de Datos2019-08-15T19:29:06Z<p>Ysangkok: fix gmane links using archive.fo</p>
<hr />
<div>{{unknown copyright}}<br />
{{LibrariesPage}}<br />
{{Es/Traducción en progreso|titulo=Librerias y Herramientas/Estructuras de Datos}}<br />
<br />
== Librerias y herramientas para Estructuras de datos en Haskell ==<br />
<br />
;[http://www.eecs.tufts.edu/~rdocki01/edison.html Edison]<br />
:Esta es la última versión de la librería Edison de estructuras de datos eficientes. También están disponibles [http://www.haskell.org/ghc/docs/edison/ versiones anteriores de Edison] por Chris Okasaki. Esta librería provee secuencias, mapeos finitos, colas de prioridad y conjuntos/multiconjuntos. ([http://www.eecs.usma.edu/Personnel/okasaki/pubs.html#hw00 artículo con un resumen]).<br />
<br />
;[http://homepages.nildram.co.uk/~ahey/HLibs/Data.Tree.AVL/ Data.Tree.AVL]<br />
:Una imlementación de árboles AVL y utilidades relacionadas.<br />
<br />
;[http://homepages.nildram.co.uk/~ahey/HLibs/Data.StringMap/ Data.StringMap]<br />
:Una librería que provee mapeos desde claves de String a valores, basada en Tries.<br />
<br />
;[http://www.cs.vu.nl/Strafunski/ Strafunski]<br />
:A bundle for generic programming. It provides programming support for generic traversal as useful in the implementation of program transformations.<br />
<br />
;[http://www.lochan.org/2005/keith-cl/libs/ Partial v0.1]<br />
:The Partial library provides a partial order class. It also provides routines for generating a Hasse diagram from a set and a partial order. Renderers are provided for the abstract Hasse diagram representation into LaTeX (via Xy-pic) and into dot, the format for AT&amp;T's Graphviz tools. Since no horizontal sorting is done, the Xy-pic output is rather poor at present; dot does a much better job with its layout optimisation algorithm.<br />
<br />
;[http://web.engr.oregonstate.edu/~erwig/diet/ Discrete Interval Encoding Trees]<br />
:The discrete interval encoding tree is a structure for storing subsets of types having a total order and a predecessor and a successor function.<br />
<br />
;[http://sourceforge.net/projects/ranged-sets/ Ranged Sets]<br />
:A ranged set is a list of non-overlapping ranges. The ranges have upper and lower boundaries, and a boundary divides the base type into values above and below. No value can ever sit on a boundary. So you can have the set {2.0 < x <= 3.0, 5.3 < x < 6}<br />
<br />
;[http://www.cwi.nl/~ralf/HList/ HList]<br />
:A heterogeneous collection is a datatype that is capable of storing data of different types, while providing operations for look-up, update, iteration, and others. There are various kinds of heterogeneous collections, differing in representation, invariants, and access operations.<br />
<br />
;[http://www.csee.ogi.edu/~diatchki/monadLib monadLib]<br />
:Iavor Diatchki's library of monad transformers for Haskell. It enables the quick construction of monads --- abstract data types that capture common programming idioms, such as throwing and catching exceptions or continuations. In many programming languages such features are built into the language (if they're provided at all), but in Haskell they are user-programmable.<br />
<br />
;[http://wiki.di.uminho.pt/wiki/bin/view/Alcino/PointlessHaskell Pointless Haskell]<br />
:Pointless Haskell is library for [[pointfree|point-free]] programming with recursion patterns defined as hylomorphisms. It also allows the visualization of the intermediate data structure of the hylomorphisms with GHood. This feature together with the DrHylo tool allows us to easily visualize recursion trees of Haskell functions.<br />
<br />
;[http://www.informatik.uni-freiburg.de/~wehr/haskell/ rhaskell : Reactive Objects]<br />
:Stefan Wehr's reactive objects library. Reactive objects are a convenient abstraction for writing programs which have to interact with a concurrent environment. A reactive object has two characteristics: the abandonment of all blocking operations and the unification of the concepts state and process. The former allows a reactive object to accept input from multiple sources without imposing any ordering on the input events. The latter prevents race conditions because the state of an object is only manipulated from the process belonging to the object.<br />
<br />
;[http://repetae.net/john/recent/out/GenUtil.html GenUtil]<br />
:A collection of random useful utility functions written in pure Haskell 98. In general, it trys to conform to the naming scheme put forth the Haskell prelude and fill in the obvious omissions, as well as provide useful routines in general.<br />
<br />
;[http://www.cs.uu.nl/~afie/pd09122004.zip PersistentDocument] ''The link is dead, somebody please either update it or remove it.''<br />
:The persistent document abstraction takes care of dealing with a document you want to open from and save to disk and that supports undo. This functionality can be used by editors of arbitrary documents and saves you a lot of quite subtle coding.<br />
<br />
;[[Zipper monad]]<br />
:A generic monad for navigating around arbitrary data structures<br />
<br />
=== Graphs ===<br />
<br />
;[http://web.engr.oregonstate.edu/~erwig/fgl/haskell/ FGL - A Functional Graph Library]<br />
:The functional graph library provides a collection of graph operations.<br />
<br />
;[http://wiki.di.uminho.pt/wiki/bin/view/PURe/PUReSoftware Data.Relation]<br />
:Part of the UMinho Haskell libraries, this library provides a representation and operations on relations. A special case of relations are graphs. The operations include graph chopping and slicing, strong connected component analysis, graphs metrics, and more.<br />
<br />
;[http://archive.fo/XdRKm Haskell Graph Automorphism Library]<br />
:Jean-Philippe Bernardy's implementation of Brendan McKay's algorithm for graph canonic labeling and automorphism group (Nauty).<br />
<br />
=== IO ===<br />
<br />
;[http://haskell.org/haskellwiki/Library/Streams Streams]<br />
:Streams is a feature-rich, flexible, extensible, backward-compatible and fast I/O library. It supports various stream types: files and legacy Handle type, string and memory buffers, pipes. There is also common functionality, available for any stream: buffering, Char encoding, locking.<br />
<br />
<br />
=== Mutable data ===<br />
<br />
;[http://www.isi.edu/~hdaume/STPP/ The Haskell STate Preprocessor]<br />
:This is a short preprocessor for stateful Haskell programs. It aleviates the pain of performing single array lookup/write/update functions with some syntax to support it. It also supports hash table operations based on the HashTable implementation available from the author. Finally, it supports monadic if and monadic case constructions. It is lightweight in the sense that it performs no syntactic analysis and is essentially a character transformer.<br />
<br />
;[http://haskell.org/haskellwiki/Library/ArrayRef Arrays & References Library]<br />
:Featuring:<br />
* Unboxed references in IO and ST monads<br />
* Monad-independent interfaces to boxed and unboxed references<br />
* Syntax sugar to make using of mutable objects easier (=:, +=, -=,..)<br />
* Reimplemented Arrays library with the following improvements:<br />
* Unboxed arrays now can be used in polymorphic functions<br />
* The MArray class now supports arrays with dynamic bounds<br />
* Implementation of dynamic (resizable) arrays<br />
<br />
See also [[Modern array libraries]]<br />
<br />
=== Strings ===<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/fps.html Data.ByteString]<br />
:The FPS library provides mmapped and malloc'd packed strings (byte arrays held by a ForeignPtr), along with a list interface to these strings. It lets you do extremely fast I/O in Haskell; in some cases, even faster than typical C implementations, as well as conserving space.<br />
<br />
;[http://quux.org/devel/missingh MissingH]<br />
:MissingH is a library of pure-Haskell utility functions relating to strings, logging, and I/O.<br />
<br />
;[http://repetae.net/john/recent/out/HsLocale.html HsLocale]<br />
:A locale-aware replacement for the standard IO routines, and support for ''wide'' strings<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/code/icfp05/tests/unit-tests/VariableExpansion.hs VariableExpansion]<br />
:A library for variable expansion inside strings<br />
<br />
=== Serialising data ===<br />
<br />
;[http://www.n-heptane.com/nhlab/repos/NewBinary NewBinary]<br />
:A port of Malcolm Wallace's Binary library from NHC, offering facilities for heap compression and binary I/O. The de-facto standard for binary I/O in Haskell<br />
<br />
;[http://www.cs.helsinki.fi/u/ekarttun/SerTH/ SerTH]<br />
:SerTH is a binary serialization library for Haskell. It supports serializing cyclic datatypes in a fast binary format. SerTH uses template haskell for deriving the serializing interface for new datatypes.<br />
<br />
;[http://haskell.org/haskellwiki/Library/AltBinary AltBinary]<br />
: AltBinary is an exhaustive library that support binary I/O and serialization. It's part of [http://haskell.org/haskellwiki/Library/Streams Streams] library, so serialization is possible to any I/O source, from String to memory-mapped file. It's also backward compatible with [http://www.n-heptane.com/nhlab/repos/NewBinary NewBinary] library what makes translation of old code trivial. Very fast, very feature-rich, Hugs/GHC compatible, etc, etc...<br />
<br />
=== Compressing data ===<br />
<br />
;[http://freearc.narod.ru/ Compression-2005]<br />
:Features of the Compression-2005 Library: <br />
* easy and uniform access to most competitive free compression algorithms as of April'05: LZMA, PPMd and GRZip<br />
* all input/output performed via user-supplied functions (callbacks), so you can compress data in memory, files, pipes, sockets and anything else<br />
* all parameters of compression algorithm are defined with a single string, for example "lzma:8mb:fast:hc4:fb32".<br />
Using this library, you can write whole bzip-like utility as one-liner! And it will compress even better than bzip2!<br />
<br />
=== Benchmarking data structures ===<br />
<br />
;[http://www.cs.york.ac.uk/fp/auburn/ Auburn]<br />
:Auburn is Graeme Moss's kit for benchmarking implementations of lazy data structures. Give it several implementations of an ADT (abstract data type) and it will tell you which one is best for your particular application.<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/code/fps/tests/Bench.hs Bench]<br />
:Simple time and space benchmarking for various list-like data structures. Easily adapted to arbitrary structures<br />
<br />
{{traduccion|titulo=Libraries and tools/Data structures}}</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Applications_and_libraries/Data_structures&diff=63008Applications and libraries/Data structures2019-08-15T19:28:09Z<p>Ysangkok: fix gmane links using archive.fo</p>
<hr />
<div>{{unknown copyright}}<br />
{{LibrariesPage}}<br />
<br />
==General libraries and tools for data structures==<br />
<br />
;[http://www.cs.princeton.edu/~rdockins/edison/home/ Edison]<br />
:This is the latest version of the Edison library of efficient data structures. There are also [http://www.haskell.org/ghc/docs/edison/ earlier version of Edison] by Chris Okasaki. It provides sequences, finite maps, priority queues, and sets/bags. ([http://www.eecs.usma.edu/Personnel/okasaki/pubs.html#hw00 overview paper]).<br />
<br />
;[[Library/New collections]]<br />
:This is a package of many useful collections types. Advantages include:<br />
:*It's easy to migrate from standard Lists/Sets/Maps to the new package. The package is an evolution (rather than a revolution) of the collections currently in the base package.<br />
:*Each collection type fits in a consistent framework (thanks to classes)<br />
:*An extensive QuickCheck test suite also serves as detailed specification for the collections.<br />
<br />
:This package includes and supercedes the following libraries:<br />
<br />
:;[http://homepages.nildram.co.uk/~ahey/HLibs/Data.Tree.AVL/ Data.Tree.AVL]<br />
::An implementation of AVL trees and related utilities.<br />
<br />
:;[http://homepages.nildram.co.uk/~ahey/HLibs/Data.StringMap/ Data.StringMap]<br />
::A library providing maps from String keys to values, based on Tries.<br />
<br />
:This package includes the following libraries, but they are maintained separately:<br />
<br />
:;[http://sourceforge.net/projects/ranged-sets/ Ranged Sets]<br />
::A ranged set is a list of non-overlapping ranges. The ranges have upper and lower boundaries, and a boundary divides the base type into values above and below. No value can ever sit on a boundary. So you can have the set {2.0 < x <= 3.0, 5.3 < x < 6}<br />
<br />
;[http://www.cs.vu.nl/Strafunski/ Strafunski]<br />
:A bundle for generic programming. It provides programming support for generic traversal as useful in the implementation of program transformations.<br />
<br />
;[http://www.lochan.org/2005/keith-cl/libs/ Partial v0.1]<br />
:The Partial library provides a partial order class. It also provides routines for generating a Hasse diagram from a set and a partial order. Renderers are provided for the abstract Hasse diagram representation into LaTeX (via Xy-pic) and into dot, the format for AT&amp;T's Graphviz tools. Since no horizontal sorting is done, the Xy-pic output is rather poor at present; dot does a much better job with its layout optimisation algorithm.<br />
<br />
;[http://web.engr.oregonstate.edu/~erwig/diet/ Discrete Interval Encoding Trees]<br />
:The discrete interval encoding tree (DIET) is a structure for storing subsets of types having a total order and a predecessor and a successor function.<br />
<br />
;[http://www.cwi.nl/~ralf/HList/ HList]<br />
:A heterogeneous collection is a datatype that is capable of storing data of different types, while providing operations for look-up, update, iteration, and others. There are various kinds of heterogeneous collections, differing in representation, invariants, and access operations.<br />
<br />
;[http://www.csee.ogi.edu/~diatchki/monadLib monadLib]<br />
:Iavor Diatchki's library of monad transformers for Haskell. It enables the quick construction of monads --- abstract data types that capture common programming idioms, such as throwing and catching exceptions or continuations. In many programming languages such features are built into the language (if they're provided at all), but in Haskell they are user-programmable.<br />
<br />
;[http://wiki.di.uminho.pt/wiki/bin/view/Alcino/PointlessHaskell Pointless Haskell]<br />
:Pointless Haskell is library for [[pointfree|point-free]] programming with recursion patterns defined as hylomorphisms. It also allows the visualization of the intermediate data structure of the hylomorphisms with GHood. This feature together with the DrHylo tool allows us to easily visualize recursion trees of Haskell functions.<br />
<br />
;[http://www.informatik.uni-freiburg.de/~wehr/haskell/ rhaskell : Reactive Objects]<br />
:Stefan Wehr's reactive objects library. Reactive objects are a convenient abstraction for writing programs which have to interact with a concurrent environment. A reactive object has two characteristics: the abandonment of all blocking operations and the unification of the concepts state and process. The former allows a reactive object to accept input from multiple sources without imposing any ordering on the input events. The latter prevents race conditions because the state of an object is only manipulated from the process belonging to the object.<br />
<br />
;[http://repetae.net/john/recent/out/GenUtil.html GenUtil]<br />
:A collection of random useful utility functions written in pure Haskell 98. In general, it tries to conform to the naming scheme put forth in the Haskell prelude and fill in the obvious omissions, as well as providing useful routines in general.<br />
<br />
;[http://www.cs.uu.nl/~afie/pd09122004.zip PersistentDocument] ''The link is dead, somebody please either update it or remove it.''<br />
:The persistent document abstraction takes care of dealing with a document you want to open from and save to disk and that supports undo. This functionality can be used by editors of arbitrary documents and saves you a lot of quite subtle coding.<br />
<br />
;[[Zipper monad]]<br />
:A generic monad for navigating around arbitrary data structures<br />
<br />
==Graphs==<br />
<br />
;[http://web.engr.oregonstate.edu/~erwig/fgl/haskell/ FGL - A Functional Graph Library]<br />
:The functional graph library provides a collection of graph operations.<br />
<br />
;[http://wiki.di.uminho.pt/wiki/bin/view/PURe/PUReSoftware Data.Relation]<br />
:Part of the UMinho Haskell libraries, this library provides a representation and operations on relations. A special case of relations are graphs. The operations include graph chopping and slicing, strong connected component analysis, graphs metrics, and more.<br />
<br />
;[http://archive.fo/XdRKm Haskell Graph Automorphism Library]<br />
:Jean-Philippe Bernardy's implementation of Brendan McKay's algorithm for graph canonical labeling and automorphism group (Nauty).<br />
<br />
==IO==<br />
<br />
;[[Library/Streams | Streams]]<br />
:Streams is a feature-rich, flexible, extensible, backward-compatible and fast I/O library. It supports various stream types: files and legacy Handle type, string and memory buffers, pipes. There is also common functionality available for any stream: buffering, Char encoding, locking.<br />
<br />
;[[Binary IO]]<br />
<br />
==Mutable data==<br />
<br />
;[http://www.isi.edu/~hdaume/STPP/ The Haskell STate Preprocessor]<br />
:This is a short preprocessor for stateful Haskell programs. It aleviates the pain of performing single array lookup/write/update functions with some syntax to support it. It also supports hash table operations based on the HashTable implementation available from the author. Finally, it supports monadic if and monadic case constructions. It is lightweight in the sense that it performs no syntactic analysis and is essentially a character transformer.<br />
<br />
;[[Library/ArrayRef | Arrays & References Library]]<br />
:Featuring:<br />
* Unboxed references in IO and ST monads<br />
* Monad-independent interfaces to boxed and unboxed references<br />
* Syntax sugar to make using of mutable objects easier (=:, +=, -=,..)<br />
* Reimplemented Arrays library with the following improvements:<br />
* Unboxed arrays now can be used in polymorphic functions<br />
* The MArray class now supports arrays with dynamic bounds<br />
* Implementation of dynamic (resizable) arrays<br />
<br />
;[http://code.haskell.org/storablevector/ Data.StorableVector.ST]<br />
:StorableVector also support mutation in ST monad.<br />
<br />
See also [[Modern array libraries]]<br />
<br />
==Lists==<br />
<br />
;[http://code.google.com/p/slist/ SList] ''(broken link)''<br />
:Sized lists for Haskell<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/dlist.html dlist]<br />
:Difference lists (supporting O(1) append and snoc)<br />
<br />
==Strings==<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/fps.html Data.ByteString]<br />
:The FPS library provides mmapped and malloc'd packed strings (byte arrays held by a ForeignPtr), along with a list interface to these strings. It lets you do extremely fast I/O in Haskell; in some cases, even faster than typical C implementations, as well as conserving space.<br />
<br />
;[http://hackage.haskell.org/package/Data-Rope Data.Rope]<br />
:A well-known tree data structure for manipulating strings without (too many) memory copies, contrarily to what Data.ByteString does. Also, contrarily to the functions in Data.ByteString.Lazy, most operations on ropes are in O(log n).<br />
<br />
;[http://code.haskell.org/storablevector/ Data.StorableVector]<br />
:This is very much the same like Data.ByteString extended to any Storable element type. There is a data structure for monolithic blocks and chunky sequences. Mutable access is also possible in ST monad.<br />
<br />
;[http://software.complete.org/missingh/ MissingH]<br />
:MissingH is a library of pure-Haskell utility functions relating to strings, logging, and I/O.<br />
<br />
;[http://repetae.net/john/recent/out/HsLocale.html HsLocale]<br />
:A locale-aware replacement for the standard IO routines, and support for ''wide'' strings<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/code/icfp05/tests/unit-tests/VariableExpansion.hs VariableExpansion]<br />
:A library for variable expansion inside strings<br />
<br />
;[http://haskell-i18n.cvs.sourceforge.net/haskell-i18n/ i18n strings]<br />
:At sourceforge<br />
<br />
==Regular expressions==<br />
<br />
There are many libraries for regular expressions available. By default<br />
GHC comes with:<br />
<br />
;[http://darcs.haskell.org/packages/regex-base/ regex-base]<br />
:This defines the type classes for the new API<br />
<br />
;[http://darcs.haskell.org/packages/regex-compat/ regex-compat]<br />
:This defines the old Text.Regex.Posix API, using regex-posix<br />
<br />
;[http://darcs.haskell.org/packages/regex-posix/ regex-posix]<br />
:This is the interface to the old (and slow) posix backend (C's regex.h)<br />
<br />
All backends provide String and ByteString interfaces.<br />
<br />
Additional backend libraries are available for (hopefully) more efficient regular expression<br />
implementations:<br />
<br />
;[http://darcs.haskell.org/packages/regex-pcre/ regex-pcre]<br />
:PCRE-based regexes. This requires [http://www.pcre.org/ libpcre] (currently works against version 6.6.0 as of January 2007). This Haskell library and libpcre are both BSD. This is very fast but has left branch semantics instead of POSIX leftmost longest semantics.<br />
<br />
;[http://darcs.haskell.org/packages/regex-tre/ regex-tre]<br />
:TRE-based regexes. This requires [http://laurikari.net/tre/ libtre] (currently works against version 0.7.5 as of January 2007). Libtre aims to be POSIX compatible and is a much faster implementation that used by regex-posix. Note that libtre does have an [http://laurikari.net/pipermail/tre-general/2007-January/000083.html outstanding bug] in correctly interpreting some regular expressions. This Haskell package is BSD-3 licensed and libtre is LGPL.<br />
<br />
;[http://darcs.haskell.org/packages/regex-parsec/ regex-parsec]<br />
:Pure Haskell regexes implemented via parsec. The leftmost longest subexpression capture semantics of this library differ from the POSIX standard. This also has an option to prefer the left branch semantics that libpcre uses.<br />
<br />
;[http://darcs.haskell.org/packages/regex-dfa/ regex-dfa]<br />
:Pure Haskell DFA for regexes. This is licensed under LPGL (the above packages are all under BSD-3) due to derived code. This is faster than regex-parsec but does not return captured subexpressions. It also is being updated to handle repeated patterns that can match empty strings (the older version hangs, the new version rewrites the pattern internally).<br />
<br />
;There is a regex-tdfa packages in development (not released) that will be a pure Haskell and BSD-3 licensed implementation inspired by libtre. It aims to be a replacement for regex-posix.<br />
<br />
;Development versions (possible unstable or broken) of the above packages are also available under [http://darcs.haskell.org/packages/regex-unstable/ regex-unstable]. For support, please use the [[Mailing_lists | haskell-cafe]] mailing list.<br />
<br />
==Spatial indices==<br />
There are several libraries containing generic code for maps indexed by 2D, 3D or N-dimensional points that support efficient nearest-neighbour or range operations:<br />
<br />
* 2D:<br />
:;[http://hackage.haskell.org/package/spacepart spacepart]<br />
::Contains quadtree implementation.<br />
<br />
* 3D:<br />
:;[http://hackage.haskell.org/package/Octree octree]<br />
:: Simple unbalanced octrees.<br />
<br />
* Of arbitrary dimensionality:<br />
<br />
:;[http://hackage.haskell.org/package/pktree pktree]<br />
::PK-trees support both radius and rectangular range search.<br />
<br />
:;[http://hackage.haskell.org/package/KdTree k-d tree]<br />
::k-d trees also support efficient range and nearest neighbour search<br />
<br />
==Serialising data==<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/binary/Data-Binary.html Data.Binary] ([http://darcs.haskell.org/binary/ darcs repository])<br />
;A library for serialising binary values to and from lazy ByteStrings.<br />
<br />
;[http://www.n-heptane.com/nhlab/repos/NewBinary NewBinary]<br />
:A port of Malcolm Wallace's Binary library from NHC, offering facilities for heap compression and binary I/O. The de-facto standard for binary I/O in Haskell<br />
<br />
;[http://www.cs.helsinki.fi/u/ekarttun/SerTH/ SerTH]<br />
:SerTH is a binary serialization library for Haskell. It supports serializing cyclic datatypes in a fast binary format. SerTH uses template haskell for deriving the serializing interface for new datatypes.<br />
<br />
;[[Library/AltBinary | AltBinary]]<br />
: AltBinary is an exhaustive library that support binary I/O and serialization. It's part of [http://haskell.org/haskellwiki/Library/Streams Streams] library, so serialization is possible to any I/O source, from String to memory-mapped file. It's also backward compatible with [http://www.n-heptane.com/nhlab/repos/NewBinary NewBinary] library what makes translation of old code trivial. Very fast, very feature-rich, Hugs/GHC compatible, etc, etc...<br />
<br />
;[http://svn.openfoundry.org/pugs/third-party/HsSyck/ HsSyck]<br />
:YAML is a straightforward machine parsable data serialization format designed for human readability and interaction with dynamic languages. It is optimized for data serialization, configuration settings, log files, Internet messaging and filtering. Syck is an extension, written in C, for reading and writing YAML swiftly in popular scripting languages. It is part of core Ruby, and also has bindings for Perl 5, Python, Lua, Cocoa, and Perl 6. HsSyck provides Data.Yaml.Syck as an interface to YAML structures, using Data.ByteString for efficient textual data representation. Additionally, we provide a set of DrIFT rules to dump and load arbitrary Haskell data types in the YAML format.<br />
<br />
;[[GenericSerialize]]<br />
:GenericSerialize is a library which serializes data using the "Scrap Your Boilerplate" infrastructure. This means that while it cannot easily support data-structure-specific serialization, it can support many different data formats cheaply.<br />
<br />
==Compressing data==<br />
<br />
;[[Library/Compression | Compressions-2005]]<br />
:Features of the Compression-2005 Library ([http://freearc.narod.ru/ homepage])<br />
* easy and uniform access to most competitive free compression algorithms as of April'05: LZMA, PPMd and GRZip<br />
* all input/output performed via user-supplied functions (callbacks), so you can compress data in memory, files, pipes, sockets and anything else<br />
* all parameters of compression algorithm are defined with a single string, for example "lzma:8mb:fast:hc4:fb32". <br />
* Using this library, you can write a bzip-like utility in one line, with better compression results than bzip2 itself.<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/zlib Zlib]<br />
:Zlib bindings for ByteStrings. darcs get http://code.haskell.org/zlib/ ([http://hackage.haskell.org/cgi-bin/hackage-scripts/package/zlib docs])<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/bzlib BZip2]<br />
:BZip2 bindings for ByteStrings. darcs get http://code.haskell.org/bzlib/ ([http://hackage.haskell.org/cgi-bin/hackage-scripts/package/bzlib docs])<br />
<br />
==Benchmarking data structures==<br />
<br />
;[http://www.cs.york.ac.uk/fp/auburn/ Auburn]<br />
:Auburn is Graeme Moss's kit for benchmarking implementations of lazy data structures. Give it several implementations of an ADT (abstract data type) and it will tell you which one is best for your particular application.<br />
<br />
;[http://www.cse.unsw.edu.au/~dons/code/fps/tests/Bench.hs Bench]<br />
:Simple time and space benchmarking for various list-like data structures. Easily adapted to arbitrary structures<br />
<br />
==Generic traversals==<br />
<br />
;[http://eecs.oregonstate.edu/~erwig/reclib/ RecLib A Recursion and Traversal Library for Haskell]<br />
:The Recursion Library for Haskell provides a rich set of generic traversal strategies to facilitate the flexible specification of generic term traversals. The underlying mechanism is the Scrap Your Boilerplate (SYB) approach. Most of the strategies that are used to implement recursion operators are taken from Stratego.<br />
<br />
==Typesafe variants of <hask>IntSet</hask> and <hask>IntMap</hask> for enumerations==<br />
<br />
* ChrisKuklewicz wrote a bit of boilerplate to re-use IntSet and IntMap with any Enum type: [[EnumSet EnumMap]]<br />
* an efficient implementation of EnumSet for sets which fit into a machine word can be found in [http://www.eecs.tufts.edu/~rdocki01/docs/edison/Data-Edison-Coll-EnumSet.html Edison] (see above)<br />
<br />
==Hackage==<br />
<br />
* [http://hackage.haskell.org/packages/archive/pkg-list.html#cat:Data%20Structures Data structures on Hackage]<br />
* [http://hackage.haskell.org/packages/archive/pkg-list.html#cat:Data More data structures on Hackage]<br />
* [http://hackage.haskell.org/packages/archive/pkg-list.html#cat:Generics Generics on Hackage]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Applications_and_libraries/Generic_programming&diff=63007Applications and libraries/Generic programming2019-08-15T19:26:18Z<p>Ysangkok: fix gmane links using archive.fo</p>
<hr />
<div>{{unknown copyright}}<br />
<br />
<br />
==Recommended libraries==<br />
See [[Generics]]<br />
<br />
<br />
== Old discussions ==<br />
=== Common library for generic programming ===<br />
<br />
Johan Jeuring and Andres Loeh [http://archive.fo/X72Xq announced] (in 2006) an initiative to design a common library for generic programming, which should work together with most of the Haskell compilers, and for which they hope to guarantee support for generics in Haskell into the future. If you want to get involved (or just want to see the discussion), you can subscribe to [http://www.haskell.org/mailman/listinfo/generics the generics mailing list] (mostly idle since ~2010). Check the [http://haskell.org/haskellwiki/Research_papers/Generics Haskell research wiki] for some background on generics.<br />
<br />
==== Work Plan ====<br />
<br />
We have identified a number of approaches that are potential candidates to a generic programming library:<br />
<br />
<ul><br />
<li><p>[[/Lightweight|A Lightweight Implementation Generics and Dynamics]]</p></li><br />
<li><p>[[/SyB| SYB (and variants)]]</p></li><br />
<li><p>[[/Strafunski| Strafunski]]</p></li><br />
<li><p>Generics for the Masses</p></li><br />
<li><p>Generics as a library</p></li><br />
<li><p>[[/Smash|Smash your Boilerplate]]</p></li><br />
<li><p>RepLib</p></li><br />
<li><p>Extensible superclasses</p></li><br />
<li><p>Almost compositional functions</p></li><br />
</ul><br />
<br />
At the moment we are discussing the advantages and disadvantages of the different approaches. Each approach is roughly two weeks under discussion and the results will be published in this Wiki Page. There is also a darcs repository where you can find some code that we are collecting. For retrieving this code do:<br />
<br />
> darcs get http://code.haskell.org/generics/<br />
<br />
The template that we are using to summarise the different approaches can be found [[/Template|here]].<br />
<br />
===Benchmark suite===<br />
We have developed a benchmark suite that tests the expressiveness of different generic programming libraries. For more information go to: [[GPBench]].</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Applications_and_libraries/Mathematics&diff=63006Applications and libraries/Mathematics2019-08-15T19:24:41Z<p>Ysangkok: fix gmane links using archive.fo</p>
<hr />
<div>== Applications ==<br />
<br />
=== Physics ===<br />
<br />
;[http://ab-initio.mit.edu/meep/ Meep]<br />
:Meep (or MEEP) is a free finite-difference time-domain (FDTD) simulation software package developed at MIT to model electromagnetic systems. Meep used Haskell to generate C++ code, after Meep [http://ab-initio.mit.edu/wiki/index.php/Meep_release_notes 1.0] Haskell generation droped in favor of handwritten C++ code. <br />
<br />
;[[Numeric Quest]]<br />
:Jan Skibinski's [[Numeric Quest]] library provides modules that are useful for Quantum Mechanics, among other things.<br />
<br />
== Libraries ==<br />
<br />
=== Linear algebra ===<br />
<br />
;[http://hackage.haskell.org/package/bed-and-breakfast bed-and-breakfast]<br />
:A library that implements Matrix operations in pure Haskell using mutable arrays and the ST Monad. bed-and-breakfast does not need any additional software to be installed and can perform basic matrix operations like multiplication, finding the inverse, and calculating determinants efficiently.<br />
<br />
;[https://github.com/patperry/hs-linear-algebra hs-linear-algebra]<br />
:Patrick Perry's linear algebra library, built on BLAS. [https://github.com/cartazio/hs-cblas hs-cblas] seems to be a more up-to-date fork.<br />
<br />
;[http://www.cs.utah.edu/~hal/HBlas/index.html Wrapper to CLAPACK]<br />
<br />
;[http://haskelldsp.sourceforge.net/ Digital Signal Processing]<br />
:Modules for matrix manipulation, Fourier transform, interpolation, spectral estimation, and frequency estimation.<br />
<br />
;[http://archive.fo/bfres Index-aware linear algebra]<br />
:Frederik Eaton's library for statically checked matrix manipulation in Haskell<br />
<br />
;[[Numeric Quest]]<br />
:Jan Skibinski's [[Numeric Quest]] library provides several modules that are useful for linear algebra in general, among other things.<br />
<br />
;[[vector-space]]<br />
:The [[vector-space]] package defines classes and generic operations for vector spaces and affine spaces. It also defines a type of infinite towers of generalized derivatives (linear transformations).<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hmatrix HMatrix]<br />
:By Alberto Ruiz. From the project [http://perception.inf.um.es/hmatrix/ website]:<br />
::''A purely functional interface to linear algebra and other numerical algorithms, internally implemented using LAPACK, BLAS, and GSL.<br />
<br />
::''This package includes standard matrix decompositions (eigensystems, singular values, Cholesky, QR, etc.), linear systems, numeric integration, root finding, etc.<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Vec Vec]<br />
:By Scott E. Dillard. Static dimension checking:<br />
::''Vectors are represented by lists with type-encoded lengths. The constructor is :., which acts like a cons both at the value and type levels, with () taking the place of nil. So x:.y:.z:.() is a 3d vector. The library provides a set of common list-like functions (map, fold, etc) for working with vectors. Built up from these functions are a small but useful set of linear algebra operations: matrix multiplication, determinants, solving linear systems, inverting matrices.''<br />
<br />
;[https://github.com/martinra/hlinear HLinear]<br />
:By Alexandru Ghitza, Martin Westerholt-Raum. PDE decomposition of matrices over division rings. See [https://arxiv.org/abs/1605.02532 HLinear: Exact Dense Linear Algebra in Haskell].<br />
::''HLinear is a Haskell implementation of the PLE decomposition of matrices over division rings. It writes an arbitrary matrix as a product of a permutation matrix, a lower unitriangular matrix, and an echelon matrix.''<br />
<br />
== See also ==<br />
<br />
* [[Linear algebra]]<br />
* [[Mathematical prelude discussion]]<br />
<br />
<br />
See also: [[Linear algebra|Design discussions]]<br />
<br />
=== [[Physical units]] ===<br />
<br />
;[[Dimensionalized numbers]]<br />
: Working with physical units like second, meter and so on in a type-safe manner.<br />
<br />
;[http://darcs.haskell.org/numericprelude/src/Number/SI.hs NumericPrelude: Physical units]<br />
: Numeric values with dynamically checked units.<br />
<br />
;[[CalDims]]<br />
:This is not simply a library providing a new type of <hask>Num</hask> class, but stand-alone calculation tool that supports user defined functions and units (basic and derived), so it can provide dimension-safe calculation (not embedded but via shell). Calculations can be modified/saved via shell. It uses rational numbers to avoid rounding errors where possible.<br />
<br />
;[https://github.com/bjornbm/dimensional Dimensional]<br />
: Library providing data types for performing arithmetic with physical quantities and units. Information about the physical dimensions of the quantities/units is embedded in their types and the validity of operations is verified by the type checker at compile time. The boxing and unboxing of numerical values as quantities is done by multiplication and division of units.<br />
<br />
=== Number representations ===<br />
<br />
==== Decimal numbers ====<br />
<br />
;[http://src.seereason.com/decimal/ Decimal arithmetic library]<br />
:An implementation of real decimal arithmetic, for cases where the binary floating point is not acceptable (for example, money).<br />
<br />
==== Real and rational numbers ====<br />
<br />
There are several levels of [[Exact real arithmetic|handling real numbers]] and according libraries.<br />
<br />
===== Arbitrary precision =====<br />
<br />
* Numbers have fixed precision<br />
* Rounding errors accumulate<br />
* Sharing is easy, i.e. in <hask>sqrt pi + sin pi</hask>, <hask>pi</hask> is computed only once<br />
* Fast, because the routines can make use of the fast implementation of <hask>Integer</hask> operations<br />
<br />
;[[Numeric Quest]]<br />
:Jan Skibinski's [[Numeric Quest]] library provides, among other things, a type for arbitrary precision rational numbers with transcendental functions.<br />
<br />
;[http://cvs.haskell.org/darcs/numericprelude/src/Number/FixedPoint.hs FixedPoint.hs]<br />
:part of NumericPrelude project<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/AERN-Basics AERN-Basics] [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/AERN-Real AERN-Real] [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/AERN-Real-Interval AERN-Real-Interval] [http://hackage.haskell.org/cgi-bin/hackage-scripts/package/AERN-Real-Double AERN-Real-Double]<br />
:contains type classes that form a foundation for ''rounded arithmetic'' and ''interval arithmetic'' with explicit control of rounding and the possibility to increase the rounding precision arbitrarily for types that support it. At the moment there are instances for Double floating point numbers where one can control the direction of rounding but cannot increase the rounding precision. In the near future instances for MPFR arbitrary precision numbers will be provided. Intervals can use as endpoints any type that supports directed rounding in the numerical order (such as Double or MPFR) and operations on intervals are rounded either outwards or inwards. Outwards rounding allows to safely approximate exact real arithmetic while a combination of both outwards and inwards rounding allows one to safely approximate exact interval arithmetic. Inverted intervals with Kaucher arithmetic are also supported.<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/AERN-RnToRm AERN-RnToRm]<br />
:contains arithmetic of ''piecewise polynomial function intervals'' that approximate multi-dimensional (almost everywhere) continuous real functions to arbitrary precision<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hmpfr hmpfr]<br />
:hmpfr is a purely functional haskell interface to the [http://www.mpfr.org/ MPFR] library<br />
<br />
;[http://hackage.haskell.org/package/numbers numbers]<br />
:provides an up-to-date, easy-to-use BigFloat implementation that builds with a modern GHC, among other things.<br />
<br />
===== Dynamic precision =====<br />
<br />
* You tell the precision and an expression shall be computed to, and the computer finds out, how precisely to compute the input values<br />
* Rounding errors do not accumulate<br />
* Sharing of temporary results is difficult, that is, in <hask>sqrt pi + sin pi</hask>, <hask>pi</hask> ''will'' be computed twice, each time with the required precision.<br />
* Almost as fast as arbitrary precision computation<br />
<br />
;[http://www.cs.man.ac.uk/arch/dlester/exact.html ERA] is an implementation (in Haskell 1.2) by David Lester.<br />
: It is quite fast, possibly the fastest Haskell implementation. At 220 lines it is also the shortest. Probably the shortest implementation of exact real arithmetic in any language.<br />
: The provided number type <hask>CReal</hask> is instance of the Haskell 98 numeric type classes and thus can be used whereever you used Float or Double before and encountered some numerical difficulties.<br />
:Here is a mirror: http://darcs.augustsson.net/Darcs/CReal/<br />
<br />
;[http://www.doc.ic.ac.uk/~ae/exact-computation/#bm:implementations IC-Reals] is an implementation by Abbas Edalat, Marko Krznar&#263; and Peter J. Potts.<br />
:This implementation uses linear fractional transformations.<br />
<br />
;[http://r6.ca/ Few Digits] by Russell O'Connor.<br />
:This is a prototype of the implementation he intendeds to write in [http://coq.inria.fr/ Coq]. Once the Coq implementation is complete, the Haskell code could be extracted producing an implementation that would be proved correct.<br />
<!--<br />
Example:<br />
*Data.Real.CReal> answer 1000 (exp 1 + sqrt 2)<br />
--><br />
<br />
;COMP is an implementation by Yann Kieffer.<br />
:The work is in beta and relies on new primitive operations on Integers which will be implemented in GHC. The library isn't available yet.<br />
<br />
;[http://www2.arnes.si/~abizja4/hera/ Hera] is an implementation by Aleš Bizjak.<br />
:It uses the [http://www.mpfr.org/ MPFR] library to implement dyadic rationals, on top of which are implemented intervals and real numbers. A real number is represented as a function <hask>Int -> Interval</hask> which represents a sequence of intervals converging to the real.<br />
<br />
===== Dynamic precision by lazy evaluation =====<br />
<br />
The real numbers are represented by an infinite datastructure, which allows you to increase precision successively by evaluating the data structure successively. All of the implementations below use some kind of digit stream as number representation.<br />
Sharing of results is simple.<br />
The implementations are either fast on simple expressions, because they use large blocks/bases, or they are fast on complex expressions, because they consume as little as possible input digits in order to emit the required output digits.<br />
<br />
;[http://medialab.freaknet.org/bignum/ BigFloat] is an implementation by Martin Guy.<br />
:It works with streams of decimal digits (strictly in the range from 0 to 9) and a separate sign. The produced digits are always correct. Output is postponed until the code is certain what the next digit is. This sometimes means that [http://medialab.freaknet.org/bignum/dudeney.html no more data is output].<br />
<br />
;In [http://users.info.unicaen.fr/~karczma/arpap/lazypi.ps.gz "The Most Unreliable Technique in the World to compute pi"] Jerzy Karczmarczuk develops some functions for computing pi lazily.<br />
<br />
;[http://darcs.haskell.org/numericprelude/src/Number/Positional.hs NumericPrelude: positional numbers]<br />
:Represents a real number as pair <hask>(exponent,[digit])</hask>, where the digits are <hask>Int</hask>s in the open range <hask>(-basis,basis)</hask>. There is no need for an extra sign item in the number data structure. The <hask>basis</hask> can range from <hask>10</hask> to <hask>1000</hask>. (Binary representations can be derived from the hexadecimal representation.) Showing the numbers in traditional format (non-negative digits) fails for fractions ending with a run of zeros. However the internal representation with negative digits can always be shown and is probably more useful for further processing. An interface for the numeric type hierarchy of the NumericPrelude project is provided.<br />
:It features<br />
:* basis conversion<br />
:* basic arithmetic: addition, subtraction, multiplication, division<br />
:* algebraic arithmetic: square root, other roots (no general polynomial roots)<br />
:* transcendental arithmetic: pi, exponential, logarithm, trigonometric and inverse trigonometric functions<br />
<br />
=== Type class hierarchies ===<br />
<br />
There are several approaches to improve the [[Mathematical prelude discussion|numeric type class hierarchy]].<br />
<br />
;Dylan Thurston and Henning Thielemann's [[Numeric Prelude]]<br />
:Experimental revised framework for numeric type classes. Needs hiding of Prelude, overriding hidden functions like fromInteger and multi-parameter type classes. Probably restricted to GHC.<br />
<br />
;Jerzy Karczmarczuk's [http://www.haskell.org/pipermail/haskell-cafe/2001-February/001510.html approach]<br />
<br />
;Serge D. Mechveliani's [ftp://ftp.botik.ru/pub/local/Mechveliani/basAlgPropos/ Basic Algebra proposal]<br />
<br />
;Andrew Frank's [http://www.haskell.org/pipermail/haskell-cafe/2006-April/015326.html approach]<br />
:The proposal: ftp://ftp.geoinfo.tuwien.ac.at/frank/numbersPrelude_v1.pdf<br />
<br />
;Haskell Prime: [http://prime.haskell.org/ticket/112 Ongoing efforts for the language revision]<br />
<br />
=== Discrete mathematics ===<br />
<br />
;[http://andrew.bromage.org/darcs/numbertheory/ Number Theory Library]<br />
:Andrew Bromage's Haskell number theory library, providing operations on primes, fibonacci sequences and combinatorics.<br />
<br />
;[http://users.skynet.be/jyp/HGAL/ HGAL]<br />
:An haskell implementation of Brendan McKay's algorithm for graph canonic labeling and automorphism group. (aka Nauty)<br />
<br />
;[http://www.cambridge.org/uk/catalogue/catalogue.asp?isbn=0521849306 Computational Oriented Matroids]<br />
:is a book by [http://wwwopt.mathematik.tu-darmstadt.de/~bokowski/ Jürgen G. Bokowski], where he develops Haskell code for Matroid computations.<br />
<br />
See also [[Libraries and tools/Cryptography]]<br />
<br />
=== Computer Algebra ===<br />
<br />
<!-- Older link: http://haskell.org/docon/ --><br />
; [http://homepages.inf.ed.ac.uk/wadler/realworld/docon2.html DoCon], the Algebraic Domain Constructor<br />
: A library by Sergey D. Mechveliani for Algebra, turns GHCi into a kind of Computer Algebra System<br />
<br />
;[http://www.info.unicaen.fr/~karczma/arpap/ Papers by Jerzy Karczmarczuk]<br />
:Some interesting uses of Haskell in mathematics, including [[functional differentiation]], power series, continued fractions.<br />
<br />
;[http://www.robtougher.com/HCAS/ HCAS] by Rob Tougher.<br />
<br />
=== Statistics ===<br />
;[http://hackage.haskell.org/package/hstats hstats]<br />
: Statistical Computing with Haskell<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hmatrix-gsl-stats hmatrix-gsl-stats]<br />
: A binding to the statistics portion of GSL. Works with hmatrix<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/hstatistics hstatistics]<br />
: A library for doing statistics. Works with hmatrix<br />
<br />
=== Plotting ===<br />
<br />
;[http://hackage.haskell.org/package/easyplot easyplot]<br />
: Simple and easy wrapper to gnuplot.<br />
<br />
;[[Gnuplot]]<br />
: Simple wrapper to gnuplot<br />
<br />
;[http://hackage.haskell.org/packages/archive/hmatrix/latest/doc/html/Graphics-Plot.html hmatrix]<br />
: contains a deprecated gnuplot wrapper<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/Chart Chart]<br />
: A library for generating 2D Charts and Plots, based upon the cairo graphics library.<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/plot plot]<br />
: A library for generating figures, based upon the cairo graphics libary with<br />
a simple, monadic interface.<br />
<br />
;[http://hackage.haskell.org/cgi-bin/hackage-scripts/package/probability probability]<br />
: the module Numeric.Probability.Visualize contains a wrapper to [http://www.r-project.org/ R]<br />
<br />
;[https://github.com/abarbu/matplotlib-haskell matplotlib-haskell]<br />
: Haskell bindings for Python's Matplotlib<br />
<br />
;[https://github.com/ocramz/bokeh-hs bokeh-hs]<br />
: Haskell bindings for Bokeh<br />
<br />
=== Numerical optimization ===<br />
This classification is somewhat arbitrary. Something more systematic like GAMS might be helpful.<br />
<br />
==== bindings ====<br />
;[http://repetae.net/john/recent/out/HsASA.html Adaptive Simulated Annealing]<br />
:A Haskell interface to Lester Ingber's adaptive simulating annealing code.<br />
<br />
;[http://hackage.haskell.org/package/cmaes CMA-ES]<br />
:A wrapper for Covariance Matrix Adaptation Evolution Strategy<br />
<br />
;[https://github.com/ghorn/nlopt-haskell nlopt-haskell]<br />
:A low-level binding to the nlopt library<br />
<br />
;[http://hackage.haskell.org/package/ipopt-hs ipopt-hs]<br />
:A haskell binding to ipopt including automatic differentiation<br />
<br />
;[http://hackage.haskell.org/package/glpk-hs glpk-hs]<br />
:A high-level interface to GLPK's linear programming and mixed integer programming features.<br />
<br />
==== pure haskell ====<br />
;[http://hackage.haskell.org/package/nonlinear-optimization nonlinear-optimization]<br />
:A pure-haskell CG_DESCENT method is implemented<br />
<br />
=== Miscellaneous libraries ===<br />
<br />
;[http://www.robtougher.com/HaskellMath/ HaskellMath]<br />
:The HaskellMath library is a sandbox for experimenting with mathematics algorithms. So far I've implemented a few quantitative finance models (Black Scholes, Binomial Trees, etc) and basic linear algebra functions. Next I might work on either computer algebra or linear programming. All comments welcome!<br />
<br />
;[http://hackage.haskell.org/package/HaskellForMaths HaskellForMaths]<br />
:David Amos' library for combinatorics, group theory, commutative algebra and non-commutative algebra, which is described in an [http://haskellformaths.blogspot.com/ accompanying blog].<br />
<br />
;[http://darcs.haskell.org/htam/ Various math stuff by Henning Thielemann]<br />
:This is some unsorted mathematical stuff including: gnuplot wrapper (now maintained as separate package), portable grey map (PGM) image reader and writer, simplest numerical integration, differentiation, zero finding, interpolation, solution of differential equations, combinatorics, some solutions of math riddles, computation of fractal dimensions of iterated function systems (IFS)<br />
<br />
;[[Numeric Quest]]<br />
:Jan Skibinski wrote a collection of Haskell modules that are useful for Mathematics in general, and Quantum Mechanics in particular.<br />
<br />
:Some of the modules are hosted on [http://darcs.haskell.org/numeric-quest/ haskell.org]. They include modules for:<br />
:* Rational numbers with transcendental functions<br />
:* Roots of polynomials<br />
:* Eigensystems<br />
:* Tensors<br />
:* Dirac quantum mechanics<br />
<br />
:Other modules in Numeric Quest are currently only available via the [http://web.archive.org/web/20010605003250/http://www.numeric-quest.com/haskell/ Internet Archive]. They include, among many other things:<br />
:* [http://web.archive.org/web/*/http://www.numeric-quest.com/haskell/ State vector evolution]<br />
:* [http://web.archive.org/web/*/http://www.numeric-quest.com/haskell/ Short study of fuzzy oscillator]<br />
<br />
:See the [[Numeric Quest]] page for more information.<br />
<br />
;[http://www.dinkla.net/fp/cglib.html Geometric Algorithms]<br />
:A small Haskell library, containing algorithms for two-dimensional convex hulls, triangulations of polygons, Voronoi-diagrams and Delaunay-triangulations, the QEDS data structure, kd-trees and range-trees.<br />
<br />
;[http://home.solcon.nl/mklooster/repos/hmm/ Hmm: Haskell Metamath]<br />
:Hmm is a small Haskell library to parse and verify Metamath databases.<br />
<br />
;[[Probabilistic Functional Programming]]<br />
:The PFP library is a collection of modules for Haskell that facilitates probabilistic functional programming, that is, programming with stochastic values. The probabilistic functional programming approach is based on a data type for representing distributions. A distribution represent the outcome of a probabilistic event as a collection of all possible values, tagged with their likelihood. A nice aspect of this system is that simulations can be specified independently from their method of execution. That is, we can either fully simulate or randomize any simulation without altering the code which defines it.<br />
<br />
;[[Sinc function]]<br />
<br />
;[[Gamma and Beta function]]<br />
<br />
;[http://repetae.net/john/recent/out/Boolean.html Boolean]<br />
:A general boolean algebra class and some instances for Haskell.<br />
<br />
;[http://darcs.haskell.org/~lemmih/hode/ HODE]<br />
:HODE is a binding to the Open Dynamics Engine. ODE is an open source, high performance library for simulating rigid body dynamics.<br />
<br />
;[http://sourceforge.net/projects/ranged-sets Ranged Sets]<br />
:A ranged set is a list of non-overlapping ranges. The ranges have upper and lower boundaries, and a boundary divides the base type into values above and below. No value can ever sit on a boundary. So you can have the set <math>(2.0, 3.0] \cup (5.3, 6)</math>.<br />
<br />
;[http://code.google.com/p/hhydra/ hhydra]<br />
:Hhydra is a tool to compute Goodstein successions and hydra puzzles described by Bernard Hodgson in his article 'Herculean or Sisyphean tasks?' published in No 51 March 2004 of the Newsletter of the European Mathematical Society.<br />
<br />
[[Category:Mathematics|*]]<br />
{{LibrariesPage}}</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Humor&diff=63005Humor2019-08-15T19:23:42Z<p>Ysangkok: fix gmane links using archive.fo</p>
<hr />
<div>Who says functional programmers never have any fun? Here's some of the<br />
hoaxes and other funny stuff from several sources.<br />
<br />
* [http://www.youtube.com/watch?v=Ci48kqp11F8 Ranjit Jhala performs Lambda Style!]<br />
* [http://ro-che.info/ccc/01.html Cartesian Closed Comic]<br />
*[[Let's_Play_Free_Games]]<br />
*[[Music of monads]]<br />
*[http://www.xent.com/pipermail/fork/Week-of-Mon-20070219/044101.html If Haskell were a working girl]<br />
*[[Humor/Microsoft|Microsoft takes over Haskell]]<br />
*[http://www.willamette.edu/~fruehr/haskell/evolution.html The Evolution of a Haskell Programmer] (can you write a factorial function?) <br />
*[[Humor/Haskell saves lives|Haskell saves lives!]]<br />
*[[Humor/Poem|An ode to Haskell]]<br />
*[[Humor/Flakes|Try some Haskell today!]]<br />
*[[Humor/Porn|Functional porn]]<br />
*[http://www.willamette.edu/~fruehr/haskell/seuss.html Dr. Seuss builds a parser]<br />
*[[Humor/Limericks|Limericks]]<br />
*[[Humor/Hugme|The latest Hugs release?]]<br />
*[[Humor/Enron|Haskell fingers Enron]]<br />
*[[Humor/1984|Haskells 1984 parallelisms]]<br />
*[[Humor/irish_joke|How to keep an imperative programmer busy for hours]]<br />
*[[Humor/How quick can you write a ISI paper with Haskell or without it ?]]<br />
*[[Humor/Urgent|URGENT ASSISTANCE NEEDED!]]<br />
*[[Humor/Homework|Need help with your homework?]]<br />
*[[Humor/Y-agra|Need help performing?]]<br />
*[[Humor/Slow|Haskell is slow!]]<br />
*[[Humor/Wanda|Wanda the fish is speaking]]<br />
*[http://www.newadvent.org/cathen/10447b.htm Monads explained by the Catholic Church]<br />
*[http://marc.info/?l=haskell&m=66622004421268 Committee Advocating The Superstitious Use of Parentheses]<br />
*[http://www.cse.unsw.edu.au/~dons/haskell-1990-2000/msg00159.html The Beta Release of Glasgow Haskell] (and [http://www.cse.unsw.edu.au/~dons/haskell-1990-2000/msg00191.html explanation])<br />
*[http://www.dcs.gla.ac.uk/~partain/haskerl/partain-1.html The Haskerl Extension to Haskell]<br />
* HaskellWiki's [http://www.haskell.org/haskellwiki/QuotesPage QuotesPage]. E.g. a quotation from <nowiki><autrijus></nowiki>:<br />
** Perl: "Easy things are easy, hard things are possible"<br />
** Haskell: "Hard things are easy, the impossible just happened"<br />
* [[Lambdabot|Lambdabot's]] [http://www.cse.unsw.edu.au/~dons/code/lambdabot/State/quote quotes archive].<br />
* [[HaskellCosmetics|Haskell cosmetics]], pure and good for you<br />
* [http://archive.fo/seKtU Haskell No Operation]<br />
* [[Almost Haskell]]<br />
* [http://www.haskell.org/pipermail/haskell-cafe/2006-November/019190.html There's a monster in my Haskell!] <br />
* [http://nssdc.gsfc.nasa.gov/image/planetary/jupiter/io.jpg What does IO look like?], or how why threading the real world is tricky.<br />
*[[Humor/Erlkönig|King IO (freely adapted from Goethe)]]<br />
*[http://koweycode.blogspot.com/2007/01/think-of-monad.html Think of a monad ... ]<br />
* [http://www.haskell.org.MonadTransformer.parallelnetz.de/haskellwiki/Category:Monad The warm, fuzzy thing transformer]<br />
* The [[Humor/LearningCurve|Haskell Learning Curve]]<br />
* [http://spl.smugmug.com/gallery/13227630_j2MHcg/#!i=960526161&k=XwKHSBM Lambdacats], inspired by the [http://en.wikipedia.org/wiki/Lolcat lolcat phenomenon].<br />
*[[Humor/Dialogs|The benefits of Haskell, via the Socratic method]]<br />
*[[Humor/Goldilocks|Goldilocks]]<br />
*[[Humor/Hackage Theme Song|Hackage Theme Song]]<br />
*[[Shooting your self in the foot]]<br />
*[[Haiku]]<br />
*[http://blog.plover.com/prog/burritos.html Monads are like burritos]<br />
*More Haskell humor at [http://www.reddit.com/r/ProgrammerHumor/search?q=haskell&restrict_sr=on reddit.com]<br />
<br />
[[Category:Humor|*]]<br />
[[Category:Community]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Type_arithmetic&diff=63004Type arithmetic2019-08-15T19:23:22Z<p>Ysangkok: fix gmane links using archive.fo</p>
<hr />
<div>'''Type arithmetic''' (or type-level computation) are calculations on<br />
the type-level, often implemented in Haskell using functional<br />
dependencies to represent functions.<br />
<br />
A simple example of type-level computation are operations on [[Peano numbers]]:<br />
<br />
<haskell><br />
data Zero<br />
<br />
data Succ a<br />
<br />
class Add a b ab | a b -> ab, a ab -> b<br />
instance Add Zero b b<br />
instance (Add a b ab) => Add (Succ a) b (Succ ab)<br />
</haskell><br />
<br />
Many other representations of numbers are possible, including binary and<br />
balanced base tree. Type-level computation may also include type<br />
representations of boolean values, lists, trees and so on. It is closely<br />
connected to theorem proving, via<br />
[http://en.wikipedia.org/wiki/Curry-Howard the Curry-Howard isomorphism].<br />
<br />
A [http://okmij.org/ftp/Haskell/number-parameterized-types.html decimal representation] was put forward by [http://okmij.org/ftp/ Oleg Kiselyov] in [http://www.haskell.org/haskellwiki/The_Monad.Reader/Issue5/Number_Param_Types "Number-Parameterized Types"] in the [http://www.haskell.org/haskellwiki/The_Monad.Reader/Issue5 fifth issue] of [http://themonadreader.wordpress.com/ The Monad Reader].<br />
There is an implementation in the {{HackagePackage|id=type-level}} package, but unfortunately the arithmetic is really slow, because in fact it simulates Peano arithmetic with decimal numbers.<br />
<br />
== Library support ==<br />
<br />
Robert Dockins has gone as far as to write<br />
a [http://archive.fo/77scn library]<br />
for type level arithmetic, supporting the following operations on type<br />
level naturals: addition, subtraction, multiplication, division,<br />
remainder, GCD, and also contains the following predicates: test for<br />
zero, test for equality and < > <= >=<br />
<br />
This library uses a binary representation and can handle numbers at<br />
the order of 10^15 (at least). It also contains a test suite to help<br />
validate the somewhat unintuitive algorithms.<br />
<br />
More libraries:<br />
<br />
* {{HackagePackage|id=type-level}} Natural numbers in decimal representation using functional dependencies and Template Haskell. However arithmetic is performed in a unary way and thus it is quite slow.<br />
* {{HackagePackage|id=type-level-tf}} Similar to the type-level package (also in speed) but uses type families instead of functional dependencies and uses the same module names as the type-level package. Thus module name clashes are warranted if you have to use both packages.<br />
* {{HackagePackage|id=type-level-natural-number}} and related packages. A collection of packages where the simplest one is even Haskell2010.<br />
* {{HackagePackage|id=tfp}} Decimal representation, Type families, Template Haskell.<br />
* {{HackagePackage|id=typical}} Binary numbers and functional dependencies.<br />
* {{HackagePackage|id=type-unary}} Unary representation and type families.<br />
* {{HackagePackage|id=numtype}}, {{HackagePackage|id=numtype-tf}} Unary representation and functional dependencies and type families, respectively.<br />
<br />
== More type hackery ==<br />
<br />
Not to be outdone, Oleg Kiselyov has <br />
[http://archive.fo/JwMNI written]<br />
on invertible, terminating, 3-place addition, multiplication,<br />
exponentiation relations on type-level Peano numerals, where any two<br />
operands determine the third. He also shows the invertible factorial<br />
relation. Thus providing all common arithmetic operations on Peano<br />
numerals, including n-base discrete logarithm, n-th root, and the<br />
inverse of factorial. The inverting method can work with any<br />
representation of (type-level) numerals, binary or decimal.<br />
<br />
Oleg says, "The implementation of RSA on the type level is left for future work".<br />
<br />
== Djinn ==<br />
<br />
Somewhat related is Lennart Augustsson's tool <br />
[http://archive.fo/4Ztai Djinn], a theorem<br />
prover/coding wizard, that generates Haskell code from a given Haskell<br />
type declaration.<br />
<br />
Djinn interprets a Haskell type as a logic formula using<br />
[http://en.wikipedia.org/wiki/Curry-Howard the Curry-Howard isomorphism]<br />
and then a decision procedure for Intuitionistic Propositional Calculus.<br />
<br />
== An Advanced Example : Type-Level Quicksort ==<br />
<br />
An advanced example: quicksort on the type level.<br />
<br />
Here is a complete example of advanced type level computation, kindly<br />
provided by Roman Leshchinskiy. For further information consult Thomas<br />
Hallgren's 2001 paper <br />
[http://www.cs.chalmers.se/~hallgren/Papers/wm01.html Fun with Functional Dependencies]. <br />
<br />
<haskell><br />
module Sort where<br />
<br />
-- natural numbers<br />
data Zero<br />
data Succ a<br />
<br />
-- booleans<br />
data True<br />
data False<br />
<br />
-- lists<br />
data Nil<br />
data Cons a b<br />
<br />
-- shortcuts<br />
type One = Succ Zero<br />
type Two = Succ One<br />
type Three = Succ Two<br />
type Four = Succ Three<br />
<br />
-- example list<br />
list1 :: Cons Three (Cons Two (Cons Four (Cons One Nil)))<br />
list1 = undefined<br />
<br />
-- utilities<br />
numPred :: Succ a -> a<br />
numPred = const undefined<br />
<br />
class Number a where<br />
numValue :: a -> Int<br />
<br />
instance Number Zero where<br />
numValue = const 0<br />
instance Number x => Number (Succ x) where<br />
numValue x = numValue (numPred x) + 1<br />
<br />
numlHead :: Cons a b -> a<br />
numlHead = const undefined<br />
<br />
numlTail :: Cons a b -> b<br />
numlTail = const undefined<br />
<br />
class NumList l where<br />
listValue :: l -> [Int]<br />
<br />
instance NumList Nil where<br />
listValue = const []<br />
instance (Number x, NumList xs) => NumList (Cons x xs) where<br />
listValue l = numValue (numlHead l) : listValue (numlTail l)<br />
<br />
-- comparisons<br />
data Less<br />
data Equal<br />
data Greater<br />
<br />
class Cmp x y c | x y -> c<br />
<br />
instance Cmp Zero Zero Equal<br />
instance Cmp Zero (Succ x) Less<br />
instance Cmp (Succ x) Zero Greater<br />
instance Cmp x y c => Cmp (Succ x) (Succ y) c<br />
<br />
-- put a value into one of three lists according to a pivot element<br />
class Pick c x ls eqs gs ls' eqs' gs' | c x ls eqs gs -> ls' eqs' gs'<br />
instance Pick Less x ls eqs gs (Cons x ls) eqs gs<br />
instance Pick Equal x ls eqs gs ls (Cons x eqs) gs<br />
instance Pick Greater x ls eqs gs ls eqs (Cons x gs)<br />
<br />
-- split a list into three parts according to a pivot element<br />
class Split n xs ls eqs gs | n xs -> ls eqs gs<br />
instance Split n Nil Nil Nil Nil<br />
instance (Split n xs ls' eqs' gs',<br />
Cmp x n c,<br />
Pick c x ls' eqs' gs' ls eqs gs) =><br />
Split n (Cons x xs) ls eqs gs<br />
<br />
listSplit :: Split n xs ls eqs gs => (n, xs) -> (ls, eqs, gs)<br />
listSplit = const (undefined, undefined, undefined)<br />
<br />
-- zs = xs ++ ys<br />
class App xs ys zs | xs ys -> zs<br />
instance App Nil ys ys<br />
instance App xs ys zs => App (Cons x xs) ys (Cons x zs)<br />
<br />
-- zs = xs ++ [n] ++ ys<br />
-- this is needed because<br />
--<br />
-- class CCons x xs xss | x xs -> xss<br />
-- instance CCons x xs (Cons x xs)<br />
--<br />
-- doesn't work<br />
<br />
class App' xs n ys zs | xs n ys -> zs<br />
instance App' Nil n ys (Cons n ys)<br />
instance (App' xs n ys zs) => App' (Cons x xs) n ys (Cons x zs)<br />
<br />
-- quicksort<br />
class QSort xs ys | xs -> ys<br />
instance QSort Nil Nil<br />
instance (Split x xs ls eqs gs,<br />
QSort ls ls',<br />
QSort gs gs',<br />
App eqs gs' geqs,<br />
App' ls' x geqs ys) =><br />
QSort (Cons x xs) ys<br />
<br />
listQSort :: QSort xs ys => xs -> ys<br />
listQSort = const undefined<br />
</haskell><br />
<br />
And we need to be able to run this somehow, in the typechecker. So fire up ghci:<br />
<br />
<haskell><br />
> :t listQSort list1<br />
Cons<br />
(Succ Zero)<br />
(Cons (Succ One) (Cons (Succ Two) (Cons (Succ Three) Nil)))<br />
</haskell><br />
<br />
== A Really Advanced Example : Type-Level Lambda Calculus ==<br />
<br />
Again, thanks to Roman Leshchinskiy, we present a simple lambda calculus<br />
encoded in the type system (and with non-terminating typechecking fun!)<br />
<br />
Below is an example which encodes a stripped-down version of the lambda<br />
calculus (with only one variable):<br />
<br />
<haskell><br />
{-# OPTIONS -fglasgow-exts #-}<br />
data X<br />
data App t u<br />
data Lam t<br />
<br />
class Subst s t u | s t -> u<br />
instance Subst X u u<br />
instance (Subst s u s', Subst t u t') => Subst (App s t) u (App s' t')<br />
instance Subst (Lam t) u (Lam t)<br />
<br />
class Apply s t u | s t -> u<br />
instance (Subst s t u, Eval u u') => Apply (Lam s) t u'<br />
<br />
class Eval t u | t -> u<br />
instance Eval X X<br />
instance Eval (Lam t) (Lam t)<br />
instance (Eval s s', Apply s' t u) => Eval (App s t) u<br />
</haskell><br />
<br />
Now, lets evaluate some lambda expressions:<br />
<br />
<haskell><br />
> :t undefined :: Eval (App (Lam X) X) u => u<br />
undefined :: Eval (App (Lam X) X) u => u :: X<br />
</haskell><br />
<br />
Ok good, and:<br />
<br />
<haskell><br />
> :t undefined :: Eval (App (Lam (App X X)) (Lam (App X X)) ) u => u<br />
^CInterrupted.<br />
</haskell><br />
<br />
diverges ;)<br />
<br />
== Turing-completeness ==<br />
<br />
It's possible to embed the Turing-complete [[Type_SK|SK combinator calculus]] at the type level.<br />
<br />
== Theory ==<br />
<br />
See also [[dependent type]] theory.<br />
<br />
== Practice ==<br />
<br />
[[Extensible record]]s (which are used e.g. in type safe, declarative [[relational algebra]] approaches to [[Libraries and tools/Database interfaces|database management]])<br />
<br />
[[Category:Idioms]]<br />
[[Category:Mathematics]]<br />
[[Category:Type-level programming]]</div>Ysangkokhttps://wiki.haskell.org/index.php?title=Typeclassopedia&diff=63003Typeclassopedia2019-08-15T19:21:13Z<p>Ysangkok: fix gmane links using archive.fo</p>
<hr />
<div>''By [[User:Byorgey|Brent Yorgey]], byorgey@gmail.com''<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 [{{HackageDocs|base|Prelude}} <code>Prelude</code>], the type system, data types, and type classes.<br />
<br />
The type classes we will be discussing and their interrelationships ([[:File:Dependencies.txt|source code for this graph can be found here]]):<br />
<br />
[[Image:Typeclassopedia-diagram.png]]<br />
<br />
{{note|<code>Apply</code> can be found 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 lines</span> indicate some other sort of relationship.<br />
* <code>Monad</code> and <code>ArrowApply</code> are equivalent.<br />
* <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://www.haskell.org/onlinereport/haskell2010/ Haskell 2010 Language 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 />
[[Instances of List and Maybe]] illustrates these type classes with simple examples using List and Maybe. We now begin with the simplest type class of all: <code>Functor</code>.<br />
<br />
=Functor=<br />
<br />
The <code>Functor</code> class ([{{HackageDocs|base|Prelude}}#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 />
<br />
(<$) :: a -> f b -> f a<br />
(<$) = fmap . const<br />
</haskell><br />
<br />
<code>Functor</code> is exported by the <code>Prelude</code>, so no special imports are needed to use it. Note that the <code>(<$)</code> operator is provided for convenience, with a default implementation in terms of <code>fmap</code>; it is included in the class just to give <code>Functor</code> instances the opportunity to provide a more efficient implementation than the default. To understand <code>Functor</code>, then, we really need to understand <code>fmap</code>.<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 a concrete type like <code>Int</code>; it is a sort of ''type function'' which takes another type as a parameter. More precisely, the ''kind'' of <code>f</code> must be <code>* -> *</code>. For example, <code>Maybe</code> is such a type with kind <code>* -> *</code>: <code>Maybe</code> is not a concrete type by itself (that is, there are no values of type <code>Maybe</code>), 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 />
Finally, we can understand <code>(<$)</code>: instead of applying a function to the values a container/context, it simply replaces them with a given value. This is the same as applying a constant function, so <code>(<$)</code> can be implemented in terms of <code>fmap</code>.<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 :: (a -> b) -> [a] -> [b]<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 :: (a -> b) -> Maybe a -> Maybe b<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 library as well:<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://archive.fo/9sQhq 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 :: (a -> b) -> [a] -> [b]<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://archive.fo/U8xIY 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 />
{{note|Actually, if <code>seq</code>/<code>undefined</code> are considered, it [http://stackoverflow.com/a/8323243/305559 is possible] to have an implementation which satisfies the first law but not the second. The rest of the comments in this section should be considered in a context where <code>seq</code> and <code>undefined</code> are excluded.}}<br />
<br />
A [https://github.com/quchen/articles/blob/master/second_functor_law.md 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.{{noteref}}<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 (excluding <code>undefined</code>), 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 />
==Utility functions==<br />
<br />
There are a few more <code>Functor</code>-related functions which can be imported from the <code>Data.Functor</code> module.<br />
<br />
* <code>(<$>)</code> is defined as a synonym for <code>fmap</code>. This enables a nice infix style that mirrors the <code>($)</code> operator for function application. For example, <code>f $ 3</code> applies the function <code>f</code> to 3, whereas <code>f <$> [1,2,3]</code> applies <code>f</code> to each member of the list.<br />
* <code>($>) :: Functor f => f a -> b -> f b</code> is just <code>flip (<$)</code>, and can occasionally be useful. To keep them straight, you can remember that <code>(<$)</code> and <code>($>)</code> point towards the value that will be kept.<br />
* <code>void :: Functor f => f a -> f ()</code> is a specialization of <code>(<$)</code>, that is, <code>void x = () <$ x</code>. This can be used in cases where a computation computes some value but the value should be ignored.<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 [{{HackageDocs|base|Control-Applicative}} <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> (variously pronounced as "apply", "app", or "splat"). 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 />
infixl 4 <*>, *>, <*<br />
(<*>) :: f (a -> b) -> f a -> f b<br />
<br />
(*>) :: f a -> f b -> f b<br />
a1 *> a2 = (id <$ a1) <*> a2<br />
<br />
(<*) :: f a -> f b -> f a<br />
(<*) = liftA2 const<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 />
<code>(*>)</code> and <code>(<*)</code> are provided for convenience, in case a particular instance of <code>Applicative</code> can provide more efficient implementations, but they are provided with default implementations. For more on these operators, see the section on [[#Utility functions|Utility functions]] below.<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 />
[{{HackageDocs|base|Control-Applicative}} haddock for Applicative] and [http://www.soi.city.ac.uk/~ross/papers/Applicative.html Applicative programming with effects]}}<br />
<br />
Traditionally, there are four laws that <code>Applicative</code> instances should satisfy {{noteref}}. In some sense, they are all concerned with making sure that <code>pure</code> deserves its name:<br />
<br />
* The identity law:<br /><haskell>pure id <*> v = v</haskell><br />
* Homomorphism:<br /><haskell>pure f <*> pure x = pure (f x)</haskell>Intuitively, applying a non-effectful function to a non-effectful argument in an effectful context is the same as just applying the function to the argument and then injecting the result into the context with <code>pure</code>.<br />
* Interchange:<br /><haskell>u <*> pure y = pure ($ y) <*> u</haskell>Intuitively, this says that when evaluating the application of an effectful function to a pure argument, the order in which we evaluate the function and its argument doesn't matter.<br />
* Composition:<br /><haskell>u <*> (v <*> w) = pure (.) <*> u <*> v <*> w </haskell>This one is the trickiest law to gain intuition for. In some sense it is expressing a sort of associativity property of <code>(<*>)</code>. The reader may wish to simply convince themselves that this law is type-correct.<br />
<br />
Considered as left-to-right rewrite rules, the homomorphism, interchange, and composition laws actually constitute an algorithm for transforming any expression using <code>pure</code> and <code>(<*>)</code> into a canonical form with only a single use of <code>pure</code> at the very beginning and only left-nested occurrences of <code>(<*>)</code>. Composition allows reassociating <code>(<*>)</code>; interchange allows moving occurrences of <code>pure</code> leftwards; and homomorphism allows collapsing multiple adjacent occurrences of <code>pure</code> into one.<br />
<br />
There is also a law specifying how <code>Applicative</code> should relate to <code>Functor</code>:<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. Since <code>(<$>)</code> is a synonym for <code>fmap</code>, the above law can also be expressed as:<br />
<br />
<code>g <$> x = pure g <*> x</code>.<br />
<br />
{{Exercises|<br />
# (Tricky) One might imagine a variant of the interchange law that says something about applying a pure function to an effectful argument. Using the above laws, prove that<haskell>pure f <*> x = pure (flip ($)) <*> x <*> pure f</haskell><br />
}}<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 :: a -> ZipList a<br />
pure = undefined -- exercise<br />
<br />
(<*>) :: ZipList (a -> b) -> ZipList a -> ZipList b<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 :: a -> [a]<br />
pure x = [x]<br />
<br />
(<*>) :: [a -> b] -> [a] -> [b]<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 />
x3 :: 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 />
In addition, as of GHC 8, the <code>ApplicativeDo</code> extension enables <code>g <$> x1 <*> x2 <*> ... <*> xn</code> to be written in a different style:<br />
<haskell><br />
do v1 <- x1<br />
v2 <- x2<br />
...<br />
vn <- xn<br />
pure (g v1 v2 ... vn)<br />
</haskell><br />
See the Further Reading section below as well as the discussion of do-notation in the Monad section for more information.<br />
<br />
==Utility functions==<br />
<br />
<code>Control.Applicative</code> provides several utility functions that work generically with any <code>Applicative</code> instance.<br />
<br />
* <code>liftA :: Applicative f => (a -> b) -> f a -> f b</code>. This should be familiar; of course, it is the same as <code>fmap</code> (and hence also the same as <code>(<$>)</code>), but with a more restrictive type. This probably exists to provide a parallel to <code>liftA2</code> and <code>liftA3</code>, but there is no reason you should ever need to use it.<br />
<br />
* <code>liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c</code> lifts a 2-argument function to operate in the context of some <code>Applicative</code>. When <code>liftA2</code> is fully applied, as in <code>liftA2 f arg1 arg2</code>,it is typically better style to instead use <code>f <$> arg1 <*> arg2</code>. However, <code>liftA2</code> can be useful in situations where it is partially applied. For example, one could define a <code>Num</code> instance for <code>Maybe Integer</code> by defining <code>(+) = liftA2 (+)</code> and so on.<br />
<br />
* There is a <code>liftA3</code> but no <code>liftAn</code> for larger <code>n</code>.<br />
<br />
* <code>(*>) :: Applicative f => f a -> f b -> f b</code> sequences the effects of two <code>Applicative</code> computations, but discards the result of the first. For example, if <code>m1, m2 :: Maybe Int</code>, then <code>m1 *> m2</code> is <code>Nothing</code> whenever either <code>m1</code> or <code>m2</code> is <code>Nothing</code>; but if not, it will have the same value as <code>m2</code>.<br />
<br />
* Likewise, <code>(<*) :: Applicative f => f a -> f b -> f a</code> sequences the effects of two computations, but keeps only the result of the first, discarding the result of the second. Just as with <code>(<$)</code> and <code>($>)</code>, to keep <code>(<*)</code> and <code>(*>)</code> straight, remember that they point towards the values that will be kept.<br />
<br />
* <code>(<**>) :: Applicative f => f a -> f (a -> b) -> f b</code> is similar to <code>(<*>)</code>, but where the first computation produces value(s) which are provided as input to the function(s) produced by the second computation. Note this is not the same as <code>flip (<*>)</code>, because the effects are performed in the opposite order. This is possible to observe with any <code>Applicative</code> instance with non-commutative effects, such as the instance for lists: <code>(<**>) [1,2] [(+5),(*10)]</code> produces a different result than <code>(flip (<*>))</code> on the same arguments. <br />
<br />
* <code>when :: Applicative f => Bool -> f () -> f ()</code> conditionally executes a computation, evaluating to its second argument if the test is <code>True</code>, and to <code>pure ()</code> if the test is <code>False</code>.<br />
<br />
* <code>unless :: Applicative f => Bool -> f () -> f ()</code> is like <code>when</code>, but with the test negated.<br />
<br />
* The <code>guard</code> function is for use with instances of <code>Alternative</code> (an extension of <code>Applicative</code> to incorporate the ideas of failure and choice), which is discussed in the [[#Failure_and_choice:_Alternative.2C_MonadPlus.2C_ArrowPlus|section on <code>Alternative</code> and friends]].<br />
<br />
{{Exercises|<br />
# Implement a function <haskell>sequenceAL :: Applicative f => [f a] -> f [a]</haskell>. There is a generalized version of this, <code>sequenceA</code>, which works for any <code>Traversable</code> (see the later section on Traversable), but implementing this version specialized to lists is a good exercise.<br />
}}<br />
<br />
==Alternative formulation==<br />
<br />
An alternative, equivalent formulation of <code>Applicative</code> is given by<br />
<br />
<haskell><br />
class Functor f => Monoidal f where<br />
unit :: f ()<br />
(**) :: f a -> f b -> f (a,b)<br />
</haskell><br />
<br />
{{note|In category-theory speak, we say <code>f</code> is a ''lax'' monoidal functor because there aren't necessarily functions in the other direction, like <code>f (a, b) -> (f a, f b)</code>.}}<br />
Intuitively, this states that a <i>monoidal</i> functor{{noteref}} is one which has some sort of "default shape" and which supports some sort of "combining" operation. <code>pure</code> and <code>(<*>)</code> are equivalent in power to <code>unit</code> and <code>(**)</code> (see the Exercises below). More technically, the idea is that <code>f</code> preserves the "monoidal structure" given by the pairing constructor <code>(,)</code> and unit type <code>()</code>. This can be seen even more clearly if we rewrite the types of <code>unit</code> and <code>(**)</code> as<br />
<haskell><br />
unit' :: () -> f ()<br />
(**') :: (f a, f b) -> f (a, b)<br />
</haskell><br />
<br />
Furthermore, to deserve the name "monoidal" (see the [[#Monoid|section on Monoids]]), instances of <code>Monoidal</code> ought to satisfy the following laws, which seem much more straightforward than the traditional <code>Applicative</code> laws:<br />
<br />
{{note|In this and the following laws, <code>≅</code> refers to <i>isomorphism</i> rather than equality. In particular we consider <code>(x,()) ≅ x ≅ ((),x)</code> and <code>((x,y),z) ≅ (x,(y,z))</code>.}}<br />
* Left identity{{noteref}}: <haskell>unit ** v ≅ v</haskell><br />
* Right identity: <haskell>u ** unit ≅ u</haskell><br />
* Associativity: <haskell>u ** (v ** w) ≅ (u ** v) ** w</haskell><br />
<br />
These turn out to be equivalent to the usual <code>Applicative</code> laws. In a category theory setting, one would also require a naturality law:<br />
<br />
{{note|Here <code>g *** h {{=}} \(x,y) -> (g x, h y)</code>. See [[#Arrow|Arrows]].}}<br />
* Naturality: <haskell>fmap (g *** h) (u ** v) = fmap g u ** fmap h v</haskell><br />
<br />
but in the context of Haskell, this is a free theorem.<br />
<br />
Much of this section was taken from [http://blog.ezyang.com/2012/08/applicative-functors/ a blog post by Edward Z. Yang]; see his actual post for a bit more information.<br />
<br />
{{Exercises|<br />
# Implement <code>pure</code> and <code>(<*>)</code> in terms of <code>unit</code> and <code>(**)</code>, and vice versa.<br />
# Are there any <code>Applicative</code> instances for which there are also functions <code>f () -> ()</code> and <code>f (a,b) -> (f a, f b)</code>, satisfying some "reasonable" laws?<br />
# (Tricky) Prove that given your implementations from the first exercise, the usual <code>Applicative</code> laws and the <code>Monoidal</code> laws stated above are equivalent.<br />
}}<br />
<br />
==Further reading==<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://web.archive.org/web/20090416111947/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 />
Gershom Bazerman's [http://comonad.com/reader/2012/abstracting-with-applicatives/ post] contains many insights into applicatives.<br />
<br />
The <code>ApplicativeDo</code> extension is described in [https://ghc.haskell.org/trac/ghc/wiki/ApplicativeDo this wiki page], and in more detail in [http://doi.org/10.1145/2976002.2976007 this Haskell Symposium paper].<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. (As of GHC 8, <code>do</code>-notation can be used with <code>Applicative</code> as well, but the notation is still fundamentally related to monads.)<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 />
As of GHC 7.10, [{{HackageDocs|base|Prelude}}#t:Monad <code>Monad</code>] is defined as:<br />
<br />
<haskell><br />
class Applicative m => 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 />
(Prior to GHC 7.10, <code>Applicative</code> was not a superclass of <code>Monad</code>, for historical reasons.)<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 [{{HackageDocs|base|Control-Monad}} <code>Control.Monad</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.) For historical reasons, we still have both names, but they should always denote the same value (although this cannot be enforced). Likewise, <code>(>>)</code> should be the same as <code>(*>)</code> from <code>Applicative</code>. It is possible that <code>return</code> and <code>(>>)</code> may eventually be removed from the <code>Monad</code> class: see the [https://ghc.haskell.org/trac/ghc/wiki/Proposal/MonadOfNoReturn Monad of No Return proposal].<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''.<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 :: a -> Maybe a<br />
return = Just<br />
<br />
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b<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, one can recursively construct ''infinite'' grammars, and hence <code>Applicative</code> (together with <code>Alternative</code>) is enough to parse any context-sensitive language with a finite alphabet. See [http://byorgey.wordpress.com/2012/01/05/parsing-context-sensitive-languages-with-applicative/ Parsing context-sensitive languages with Applicative].}}<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 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 canonical definition of monads in category theory is 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 [{{HackageDocs|base|Control-Monad}} <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 />
* <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 a consequence of the fact that the <code>Monad</code> type class did not require a <code>Functor</code> instance until recently, even though mathematically speaking, every monad is a functor. If you are using GHC 7.10 or newer, you should avoid using <code>liftM</code> and just use <code>fmap</code> instead.<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> (see the exercise at the end of the Utility Functions section for Applicative). Note that the actual type of <code>sequence</code> is more general, and works over any <code>Traversable</code> rather than just lists; see the [[#Traversable|section on <code>Traversable</code>]].<br />
<br />
* <code>replicateM :: Monad m => Int -> m a -> m [a]</code> is simply a combination of [{{HackageDocs|base|Prelude}}#v:replicate <code>replicate</code>] and <code>sequence</code>.<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. Again, these functions actually work over any <code>Traversable</code>, not just lists, and they can also be defined in terms of <code>Applicative</code>, not <code>Monad</code>: the analogue of <code>mapM</code> for <code>Applicative</code> is called <code>traverse</code>.<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 />
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 />
</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.<br />
<br />
{{note|I like to pronounce this operator “fish”.}}<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}}.<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 />
{{Exercises|<br />
# Given the definition <code>g >{{=}}> h {{=}} \x -> g x >>{{=}} h</code>, prove the equivalence of the above laws and the usual monad laws.<br />
}}<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> is 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://www.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 />
Sometimes, the full power of <code>Monad</code> is not needed to desugar <code>do</code>-notation. For example,<br />
<br />
<haskell><br />
do x <- foo1<br />
y <- foo2<br />
z <- foo3<br />
return (g x y z)<br />
</haskell><br />
<br />
would normally be desugared to <code>foo1 >>= \x -> foo2 >>= \y -> foo3 >>= \z -> return (g x y z)</code>, but this is equivalent to <code>g <$> foo1 <*> foo2 <*> foo3</code>. With the <code>ApplicativeDo</code> extension enabled (as of GHC 8.0), GHC tries hard to desugar <code>do</code>-blocks using <code>Applicative</code> operations wherever possible. This can sometimes lead to efficiency gains, even for types which also have <code>Monad</code> instances, since in general <code>Applicative</code> computations may be run in parallel, whereas monadic ones may not. For example, consider<br />
<br />
<haskell><br />
g :: Int -> Int -> M Int<br />
<br />
-- These could be expensive<br />
bar, baz :: M Int<br />
<br />
foo :: M Int<br />
foo = do<br />
x <- bar<br />
y <- baz<br />
g x y<br />
</haskell><br />
<br />
<code>foo</code> definitely depends on the <code>Monad</code> instance of <code>M</code>, since the effects generated by the whole computation may depend (via <code>g</code>) on the <code>Int</code> outputs of <code>bar</code> and <code>baz</code>. Nonetheless, with <code>ApplicativeDo</code> enabled, <code>foo</code> can be desugared as<br />
<haskell><br />
join (g <$> bar <*> baz)<br />
</haskell><br />
which may allow <code>bar</code> and <code>baz</code> to be computed in parallel, since they at least do not depend on each other.<br />
<br />
The <code>ApplicativeDo</code> extension is described in [https://ghc.haskell.org/trac/ghc/wiki/ApplicativeDo this wiki page], and in more detail in [http://doi.org/10.1145/2976002.2976007 this Haskell Symposium paper].<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://www.haskell.org/haskellwiki/Monads_as_Containers Monads as containers],<br />
[http://en.wikibooks.org/w/index.php?title=Haskell/Understanding_monads 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://www.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://www.haskell.org/haskellwiki/Monads_as_Containers Monads as containers] and [http://www.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], Tim Newsham’s [http://www.thenewsh.com/~newsham/haskell/monad.html What’s a Monad?], and Chris Smith's excellent article [http://cdsmith.wordpress.com/2012/04/18/why-do-monads-matter/ Why Do Monads Matter?]. 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 />
For help constructing monads from scratch, and for obtaining a "deep embedding" of monad operations suitable for use in, say, compiling a domain-specific language, see [http://projects.haskell.org/operational Apfelmus's operational package].<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 [https://bentnib.org/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’ 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>. Jonathan Hill and Keith Clarke have [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.53.6497 an early paper explaining the connection between monads as they arise in category theory and as used in functional programming]. There is also a [http://okmij.org/ftp/Computation/IO-monad-history.html web page by Oleg Kiselyov] explaining the history of the IO monad.<br />
<br />
Links to many more research papers related to monads can be found under [[Research papers/Monads and arrows]].<br />
<br />
=MonadFail=<br />
<br />
Some monads support a notion of ''failure'', without necessarily supporting the notion of ''recovery'' suggested by <code>MonadPlus</code>, and possibly including a primitive error reporting mechanism. This notion is expressed by the relatively unprincipled <code>MonadFail</code>. When the <code>MonadFailDesugaring</code> language extension is enabled, the <code>fail</code> method from <code>MonadFail</code> is used for pattern match failure in <code>do</code> bindings rather than the traditional <code>fail</code> method of the <code>Monad</code> class. This language change is being implemented because there are many monads, such as <code>Reader</code>, <code>State</code>, <code>Writer</code>, <code>RWST</code>, and <code>Cont</code> that simply do not support a legitimate <code>fail</code> method.<br />
<br />
See the [https://prime.haskell.org/wiki/Libraries/Proposals/MonadFail MonadFail proposal] for more information.<br />
<br />
==Definition==<br />
<br />
<haskell><br />
class Monad m => MonadFail m where<br />
fail :: String -> m a<br />
</haskell><br />
<br />
==Law==<br />
<br />
<haskell><br />
fail s >>= m = fail s<br />
</haskell><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, when you do not actually want any extra capabilities.<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 m