Document the fact that Template Haskell type splices work
[ghc-hetmet.git] / docs / users_guide / glasgow_exts.xml
1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <para>
3 <indexterm><primary>language, GHC</primary></indexterm>
4 <indexterm><primary>extensions, GHC</primary></indexterm>
5 As with all known Haskell systems, GHC implements some extensions to
6 the language.  They are all enabled by options; by default GHC
7 understands only plain Haskell 98.
8 </para>
9
10 <para>
11 Some of the Glasgow extensions serve to give you access to the
12 underlying facilities with which we implement Haskell.  Thus, you can
13 get at the Raw Iron, if you are willing to write some non-portable
14 code at a more primitive level.  You need not be &ldquo;stuck&rdquo;
15 on performance because of the implementation costs of Haskell's
16 &ldquo;high-level&rdquo; features&mdash;you can always code
17 &ldquo;under&rdquo; them.  In an extreme case, you can write all your
18 time-critical code in C, and then just glue it together with Haskell!
19 </para>
20
21 <para>
22 Before you get too carried away working at the lowest level (e.g.,
23 sloshing <literal>MutableByteArray&num;</literal>s around your
24 program), you may wish to check if there are libraries that provide a
25 &ldquo;Haskellised veneer&rdquo; over the features you want.  The
26 separate <ulink url="../libraries/index.html">libraries
27 documentation</ulink> describes all the libraries that come with GHC.
28 </para>
29
30 <!-- LANGUAGE OPTIONS -->
31   <sect1 id="options-language">
32     <title>Language options</title>
33
34     <indexterm><primary>language</primary><secondary>option</secondary>
35     </indexterm>
36     <indexterm><primary>options</primary><secondary>language</secondary>
37     </indexterm>
38     <indexterm><primary>extensions</primary><secondary>options controlling</secondary>
39     </indexterm>
40
41     <para>The language option flags control what variation of the language are
42     permitted.  Leaving out all of them gives you standard Haskell
43     98.</para>
44
45     <para>Language options can be controlled in two ways:
46     <itemizedlist>
47       <listitem><para>Every language option can switched on by a command-line flag "<option>-X...</option>" 
48         (e.g. <option>-XTemplateHaskell</option>), and switched off by the flag "<option>-XNo...</option>"; 
49         (e.g. <option>-XNoTemplateHaskell</option>).</para></listitem>
50       <listitem><para>
51           Language options recognised by Cabal can also be enabled using the <literal>LANGUAGE</literal> pragma,
52           thus <literal>{-# LANGUAGE TemplateHaskell #-}</literal> (see <xref linkend="language-pragma"/>). </para>
53           </listitem>
54       </itemizedlist></para>
55
56     <para>The flag <option>-fglasgow-exts</option>
57           <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
58           is equivalent to enabling the following extensions: 
59           <option>-XPrintExplicitForalls</option>,
60           <option>-XForeignFunctionInterface</option>,
61           <option>-XUnliftedFFITypes</option>,
62           <option>-XGADTs</option>,
63           <option>-XImplicitParams</option>,
64           <option>-XScopedTypeVariables</option>,
65           <option>-XUnboxedTuples</option>,
66           <option>-XTypeSynonymInstances</option>,
67           <option>-XStandaloneDeriving</option>,
68           <option>-XDeriveDataTypeable</option>,
69           <option>-XFlexibleContexts</option>,
70           <option>-XFlexibleInstances</option>,
71           <option>-XConstrainedClassMethods</option>,
72           <option>-XMultiParamTypeClasses</option>,
73           <option>-XFunctionalDependencies</option>,
74           <option>-XMagicHash</option>,
75           <option>-XPolymorphicComponents</option>,
76           <option>-XExistentialQuantification</option>,
77           <option>-XUnicodeSyntax</option>,
78           <option>-XPostfixOperators</option>,
79           <option>-XPatternGuards</option>,
80           <option>-XLiberalTypeSynonyms</option>,
81           <option>-XRankNTypes</option>,
82           <option>-XImpredicativeTypes</option>,
83           <option>-XTypeOperators</option>,
84           <option>-XRecursiveDo</option>,
85           <option>-XParallelListComp</option>,
86           <option>-XEmptyDataDecls</option>,
87           <option>-XKindSignatures</option>,
88           <option>-XGeneralizedNewtypeDeriving</option>,
89           <option>-XTypeFamilies</option>.
90             Enabling these options is the <emphasis>only</emphasis> 
91             effect of <option>-fglasgow-exts</option>.
92           We are trying to move away from this portmanteau flag, 
93           and towards enabling features individually.</para>
94
95   </sect1>
96
97 <!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS -->
98 <sect1 id="primitives">
99   <title>Unboxed types and primitive operations</title>
100
101 <para>GHC is built on a raft of primitive data types and operations;
102 "primitive" in the sense that they cannot be defined in Haskell itself.
103 While you really can use this stuff to write fast code,
104   we generally find it a lot less painful, and more satisfying in the
105   long run, to use higher-level language features and libraries.  With
106   any luck, the code you write will be optimised to the efficient
107   unboxed version in any case.  And if it isn't, we'd like to know
108   about it.</para>
109
110 <para>All these primitive data types and operations are exported by the 
111 library <literal>GHC.Prim</literal>, for which there is 
112 <ulink url="../libraries/base/GHC.Prim.html">detailed online documentation</ulink>.
113 (This documentation is generated from the file <filename>compiler/prelude/primops.txt.pp</filename>.)
114 </para>
115 <para>
116 If you want to mention any of the primitive data types or operations in your
117 program, you must first import <literal>GHC.Prim</literal> to bring them
118 into scope.  Many of them have names ending in "&num;", and to mention such
119 names you need the <option>-XMagicHash</option> extension (<xref linkend="magic-hash"/>).
120 </para>
121
122 <para>The primops make extensive use of <link linkend="glasgow-unboxed">unboxed types</link> 
123 and <link linkend="unboxed-tuples">unboxed tuples</link>, which
124 we briefly summarise here. </para>
125   
126 <sect2 id="glasgow-unboxed">
127 <title>Unboxed types
128 </title>
129
130 <para>
131 <indexterm><primary>Unboxed types (Glasgow extension)</primary></indexterm>
132 </para>
133
134 <para>Most types in GHC are <firstterm>boxed</firstterm>, which means
135 that values of that type are represented by a pointer to a heap
136 object.  The representation of a Haskell <literal>Int</literal>, for
137 example, is a two-word heap object.  An <firstterm>unboxed</firstterm>
138 type, however, is represented by the value itself, no pointers or heap
139 allocation are involved.
140 </para>
141
142 <para>
143 Unboxed types correspond to the &ldquo;raw machine&rdquo; types you
144 would use in C: <literal>Int&num;</literal> (long int),
145 <literal>Double&num;</literal> (double), <literal>Addr&num;</literal>
146 (void *), etc.  The <emphasis>primitive operations</emphasis>
147 (PrimOps) on these types are what you might expect; e.g.,
148 <literal>(+&num;)</literal> is addition on
149 <literal>Int&num;</literal>s, and is the machine-addition that we all
150 know and love&mdash;usually one instruction.
151 </para>
152
153 <para>
154 Primitive (unboxed) types cannot be defined in Haskell, and are
155 therefore built into the language and compiler.  Primitive types are
156 always unlifted; that is, a value of a primitive type cannot be
157 bottom.  We use the convention (but it is only a convention) 
158 that primitive types, values, and
159 operations have a <literal>&num;</literal> suffix (see <xref linkend="magic-hash"/>).
160 For some primitive types we have special syntax for literals, also
161 described in the <link linkend="magic-hash">same section</link>.
162 </para>
163
164 <para>
165 Primitive values are often represented by a simple bit-pattern, such
166 as <literal>Int&num;</literal>, <literal>Float&num;</literal>,
167 <literal>Double&num;</literal>.  But this is not necessarily the case:
168 a primitive value might be represented by a pointer to a
169 heap-allocated object.  Examples include
170 <literal>Array&num;</literal>, the type of primitive arrays.  A
171 primitive array is heap-allocated because it is too big a value to fit
172 in a register, and would be too expensive to copy around; in a sense,
173 it is accidental that it is represented by a pointer.  If a pointer
174 represents a primitive value, then it really does point to that value:
175 no unevaluated thunks, no indirections&hellip;nothing can be at the
176 other end of the pointer than the primitive value.
177 A numerically-intensive program using unboxed types can
178 go a <emphasis>lot</emphasis> faster than its &ldquo;standard&rdquo;
179 counterpart&mdash;we saw a threefold speedup on one example.
180 </para>
181
182 <para>
183 There are some restrictions on the use of primitive types:
184 <itemizedlist>
185 <listitem><para>The main restriction
186 is that you can't pass a primitive value to a polymorphic
187 function or store one in a polymorphic data type.  This rules out
188 things like <literal>[Int&num;]</literal> (i.e. lists of primitive
189 integers).  The reason for this restriction is that polymorphic
190 arguments and constructor fields are assumed to be pointers: if an
191 unboxed integer is stored in one of these, the garbage collector would
192 attempt to follow it, leading to unpredictable space leaks.  Or a
193 <function>seq</function> operation on the polymorphic component may
194 attempt to dereference the pointer, with disastrous results.  Even
195 worse, the unboxed value might be larger than a pointer
196 (<literal>Double&num;</literal> for instance).
197 </para>
198 </listitem>
199 <listitem><para> You cannot define a newtype whose representation type
200 (the argument type of the data constructor) is an unboxed type.  Thus,
201 this is illegal:
202 <programlisting>
203   newtype A = MkA Int#
204 </programlisting>
205 </para></listitem>
206 <listitem><para> You cannot bind a variable with an unboxed type
207 in a <emphasis>top-level</emphasis> binding.
208 </para></listitem>
209 <listitem><para> You cannot bind a variable with an unboxed type
210 in a <emphasis>recursive</emphasis> binding.
211 </para></listitem>
212 <listitem><para> You may bind unboxed variables in a (non-recursive,
213 non-top-level) pattern binding, but any such variable causes the entire
214 pattern-match
215 to become strict.  For example:
216 <programlisting>
217   data Foo = Foo Int Int#
218
219   f x = let (Foo a b, w) = ..rhs.. in ..body..
220 </programlisting>
221 Since <literal>b</literal> has type <literal>Int#</literal>, the entire pattern
222 match
223 is strict, and the program behaves as if you had written
224 <programlisting>
225   data Foo = Foo Int Int#
226
227   f x = case ..rhs.. of { (Foo a b, w) -> ..body.. }
228 </programlisting>
229 </para>
230 </listitem>
231 </itemizedlist>
232 </para>
233
234 </sect2>
235
236 <sect2 id="unboxed-tuples">
237 <title>Unboxed Tuples
238 </title>
239
240 <para>
241 Unboxed tuples aren't really exported by <literal>GHC.Exts</literal>,
242 they're available by default with <option>-fglasgow-exts</option>.  An
243 unboxed tuple looks like this:
244 </para>
245
246 <para>
247
248 <programlisting>
249 (# e_1, ..., e_n #)
250 </programlisting>
251
252 </para>
253
254 <para>
255 where <literal>e&lowbar;1..e&lowbar;n</literal> are expressions of any
256 type (primitive or non-primitive).  The type of an unboxed tuple looks
257 the same.
258 </para>
259
260 <para>
261 Unboxed tuples are used for functions that need to return multiple
262 values, but they avoid the heap allocation normally associated with
263 using fully-fledged tuples.  When an unboxed tuple is returned, the
264 components are put directly into registers or on the stack; the
265 unboxed tuple itself does not have a composite representation.  Many
266 of the primitive operations listed in <literal>primops.txt.pp</literal> return unboxed
267 tuples.
268 In particular, the <literal>IO</literal> and <literal>ST</literal> monads use unboxed
269 tuples to avoid unnecessary allocation during sequences of operations.
270 </para>
271
272 <para>
273 There are some pretty stringent restrictions on the use of unboxed tuples:
274 <itemizedlist>
275 <listitem>
276
277 <para>
278 Values of unboxed tuple types are subject to the same restrictions as
279 other unboxed types; i.e. they may not be stored in polymorphic data
280 structures or passed to polymorphic functions.
281
282 </para>
283 </listitem>
284 <listitem>
285
286 <para>
287 No variable can have an unboxed tuple type, nor may a constructor or function
288 argument have an unboxed tuple type.  The following are all illegal:
289
290
291 <programlisting>
292   data Foo = Foo (# Int, Int #)
293
294   f :: (# Int, Int #) -&#62; (# Int, Int #)
295   f x = x
296
297   g :: (# Int, Int #) -&#62; Int
298   g (# a,b #) = a
299
300   h x = let y = (# x,x #) in ...
301 </programlisting>
302 </para>
303 </listitem>
304 </itemizedlist>
305 </para>
306 <para>
307 The typical use of unboxed tuples is simply to return multiple values,
308 binding those multiple results with a <literal>case</literal> expression, thus:
309 <programlisting>
310   f x y = (# x+1, y-1 #)
311   g x = case f x x of { (# a, b #) -&#62; a + b }
312 </programlisting>
313 You can have an unboxed tuple in a pattern binding, thus
314 <programlisting>
315   f x = let (# p,q #) = h x in ..body..
316 </programlisting>
317 If the types of <literal>p</literal> and <literal>q</literal> are not unboxed,
318 the resulting binding is lazy like any other Haskell pattern binding.  The 
319 above example desugars like this:
320 <programlisting>
321   f x = let t = case h x o f{ (# p,q #) -> (p,q)
322             p = fst t
323             q = snd t
324         in ..body..
325 </programlisting>
326 Indeed, the bindings can even be recursive.
327 </para>
328
329 </sect2>
330 </sect1>
331
332
333 <!-- ====================== SYNTACTIC EXTENSIONS =======================  -->
334
335 <sect1 id="syntax-extns">
336 <title>Syntactic extensions</title>
337  
338     <sect2 id="unicode-syntax">
339       <title>Unicode syntax</title>
340       <para>The language
341       extension <option>-XUnicodeSyntax</option><indexterm><primary><option>-XUnicodeSyntax</option></primary></indexterm>
342       enables Unicode characters to be used to stand for certain ASCII
343       character sequences.  The following alternatives are provided:</para>
344
345       <informaltable>
346         <tgroup cols="2" align="left" colsep="1" rowsep="1">
347           <thead>
348             <row>
349               <entry>ASCII</entry>
350               <entry>Unicode alternative</entry>
351               <entry>Code point</entry>
352               <entry>Name</entry>
353             </row>
354           </thead>
355           <tbody>
356             <row>
357               <entry><literal>::</literal></entry>
358               <entry>::</entry> <!-- no special char, apparently -->
359               <entry>0x2237</entry>
360               <entry>PROPORTION</entry>
361             </row>
362           </tbody>
363           <tbody>
364             <row>
365               <entry><literal>=&gt;</literal></entry>
366               <entry>&rArr;</entry>
367               <entry>0x21D2</entry>
368               <entry>RIGHTWARDS DOUBLE ARROW</entry>
369             </row>
370           </tbody>
371           <tbody>
372             <row>
373               <entry><literal>forall</literal></entry>
374               <entry>&forall;</entry>
375               <entry>0x2200</entry>
376               <entry>FOR ALL</entry>
377             </row>
378           </tbody>
379           <tbody>
380             <row>
381               <entry><literal>-&gt;</literal></entry>
382               <entry>&rarr;</entry>
383               <entry>0x2192</entry>
384               <entry>RIGHTWARDS ARROW</entry>
385             </row>
386           </tbody>
387           <tbody>
388             <row>
389               <entry><literal>&lt;-</literal></entry>
390               <entry>&larr;</entry>
391               <entry>0x2190</entry>
392               <entry>LEFTWARDS ARROW</entry>
393             </row>
394           </tbody>
395           <tbody>
396             <row>
397               <entry>..</entry>
398               <entry>&hellip;</entry>
399               <entry>0x22EF</entry>
400               <entry>MIDLINE HORIZONTAL ELLIPSIS</entry>
401             </row>
402           </tbody>
403         </tgroup>
404       </informaltable>
405     </sect2>
406
407     <sect2 id="magic-hash">
408       <title>The magic hash</title>
409       <para>The language extension <option>-XMagicHash</option> allows "&num;" as a
410         postfix modifier to identifiers.  Thus, "x&num;" is a valid variable, and "T&num;" is
411         a valid type constructor or data constructor.</para>
412
413       <para>The hash sign does not change sematics at all.  We tend to use variable
414         names ending in "&num;" for unboxed values or types (e.g. <literal>Int&num;</literal>), 
415         but there is no requirement to do so; they are just plain ordinary variables.
416         Nor does the <option>-XMagicHash</option> extension bring anything into scope.
417         For example, to bring <literal>Int&num;</literal> into scope you must 
418         import <literal>GHC.Prim</literal> (see <xref linkend="primitives"/>); 
419         the <option>-XMagicHash</option> extension
420         then allows you to <emphasis>refer</emphasis> to the <literal>Int&num;</literal>
421         that is now in scope.</para>
422       <para> The <option>-XMagicHash</option> also enables some new forms of literals (see <xref linkend="glasgow-unboxed"/>):
423         <itemizedlist> 
424           <listitem><para> <literal>'x'&num;</literal> has type <literal>Char&num;</literal></para> </listitem>
425           <listitem><para> <literal>&quot;foo&quot;&num;</literal> has type <literal>Addr&num;</literal></para> </listitem>
426           <listitem><para> <literal>3&num;</literal> has type <literal>Int&num;</literal>. In general,
427           any Haskell 98 integer lexeme followed by a <literal>&num;</literal> is an <literal>Int&num;</literal> literal, e.g.
428             <literal>-0x3A&num;</literal> as well as <literal>32&num;</literal></para>.</listitem>
429           <listitem><para> <literal>3&num;&num;</literal> has type <literal>Word&num;</literal>. In general,
430           any non-negative Haskell 98 integer lexeme followed by <literal>&num;&num;</literal> 
431               is a <literal>Word&num;</literal>. </para> </listitem>
432           <listitem><para> <literal>3.2&num;</literal> has type <literal>Float&num;</literal>.</para> </listitem>
433           <listitem><para> <literal>3.2&num;&num;</literal> has type <literal>Double&num;</literal></para> </listitem>
434           </itemizedlist>
435       </para>
436    </sect2>
437
438     <sect2 id="new-qualified-operators">
439       <title>New qualified operator syntax</title>
440
441       <para>A new syntax for referencing qualified operators is
442         planned to be introduced by Haskell', and is enabled in GHC
443         with
444         the <option>-XNewQualifiedOperators</option><indexterm><primary><option>-XNewQualifiedOperators</option></primary></indexterm>
445         option.  In the new syntax, the prefix form of a qualified
446         operator is
447         written <literal><replaceable>module</replaceable>.(<replaceable>symbol</replaceable>)</literal>
448         (in Haskell 98 this would
449         be <literal>(<replaceable>module</replaceable>.<replaceable>symbol</replaceable>)</literal>),
450         and the infix form is
451         written <literal>`<replaceable>module</replaceable>.(<replaceable>symbol</replaceable>)`</literal>
452         (in Haskell 98 this would
453         be <literal>`<replaceable>module</replaceable>.<replaceable>symbol</replaceable>`</literal>.
454         For example:
455 <programlisting>
456   add x y = Prelude.(+) x y
457   subtract y = (`Prelude.(-)` y)
458 </programlisting>
459         The new form of qualified operators is intended to regularise
460         the syntax by eliminating odd cases
461         like <literal>Prelude..</literal>.  For example,
462         when <literal>NewQualifiedOperators</literal> is on, it is possible to
463         write the enumerated sequence <literal>[Monday..]</literal>
464         without spaces, whereas in Haskell 98 this would be a
465         reference to the operator &lsquo;<literal>.</literal>&lsquo;
466         from module <literal>Monday</literal>.</para>
467
468       <para>When <option>-XNewQualifiedOperators</option> is on, the old Haskell
469         98 syntax for qualified operators is not accepted, so this
470         option may cause existing Haskell 98 code to break.</para>
471
472     </sect2>
473         
474
475     <!-- ====================== HIERARCHICAL MODULES =======================  -->
476
477
478     <sect2 id="hierarchical-modules">
479       <title>Hierarchical Modules</title>
480
481       <para>GHC supports a small extension to the syntax of module
482       names: a module name is allowed to contain a dot
483       <literal>&lsquo;.&rsquo;</literal>.  This is also known as the
484       &ldquo;hierarchical module namespace&rdquo; extension, because
485       it extends the normally flat Haskell module namespace into a
486       more flexible hierarchy of modules.</para>
487
488       <para>This extension has very little impact on the language
489       itself; modules names are <emphasis>always</emphasis> fully
490       qualified, so you can just think of the fully qualified module
491       name as <quote>the module name</quote>.  In particular, this
492       means that the full module name must be given after the
493       <literal>module</literal> keyword at the beginning of the
494       module; for example, the module <literal>A.B.C</literal> must
495       begin</para>
496
497 <programlisting>module A.B.C</programlisting>
498
499
500       <para>It is a common strategy to use the <literal>as</literal>
501       keyword to save some typing when using qualified names with
502       hierarchical modules.  For example:</para>
503
504 <programlisting>
505 import qualified Control.Monad.ST.Strict as ST
506 </programlisting>
507
508       <para>For details on how GHC searches for source and interface
509       files in the presence of hierarchical modules, see <xref
510       linkend="search-path"/>.</para>
511
512       <para>GHC comes with a large collection of libraries arranged
513       hierarchically; see the accompanying <ulink
514       url="../libraries/index.html">library
515       documentation</ulink>.  More libraries to install are available
516       from <ulink
517       url="http://hackage.haskell.org/packages/hackage.html">HackageDB</ulink>.</para>
518     </sect2>
519
520     <!-- ====================== PATTERN GUARDS =======================  -->
521
522 <sect2 id="pattern-guards">
523 <title>Pattern guards</title>
524
525 <para>
526 <indexterm><primary>Pattern guards (Glasgow extension)</primary></indexterm>
527 The discussion that follows is an abbreviated version of Simon Peyton Jones's original <ulink url="http://research.microsoft.com/~simonpj/Haskell/guards.html">proposal</ulink>. (Note that the proposal was written before pattern guards were implemented, so refers to them as unimplemented.)
528 </para>
529
530 <para>
531 Suppose we have an abstract data type of finite maps, with a
532 lookup operation:
533
534 <programlisting>
535 lookup :: FiniteMap -> Int -> Maybe Int
536 </programlisting>
537
538 The lookup returns <function>Nothing</function> if the supplied key is not in the domain of the mapping, and <function>(Just v)</function> otherwise,
539 where <varname>v</varname> is the value that the key maps to.  Now consider the following definition:
540 </para>
541
542 <programlisting>
543 clunky env var1 var2 | ok1 &amp;&amp; ok2 = val1 + val2
544 | otherwise  = var1 + var2
545 where
546   m1 = lookup env var1
547   m2 = lookup env var2
548   ok1 = maybeToBool m1
549   ok2 = maybeToBool m2
550   val1 = expectJust m1
551   val2 = expectJust m2
552 </programlisting>
553
554 <para>
555 The auxiliary functions are 
556 </para>
557
558 <programlisting>
559 maybeToBool :: Maybe a -&gt; Bool
560 maybeToBool (Just x) = True
561 maybeToBool Nothing  = False
562
563 expectJust :: Maybe a -&gt; a
564 expectJust (Just x) = x
565 expectJust Nothing  = error "Unexpected Nothing"
566 </programlisting>
567
568 <para>
569 What is <function>clunky</function> doing? The guard <literal>ok1 &amp;&amp;
570 ok2</literal> checks that both lookups succeed, using
571 <function>maybeToBool</function> to convert the <function>Maybe</function>
572 types to booleans. The (lazily evaluated) <function>expectJust</function>
573 calls extract the values from the results of the lookups, and binds the
574 returned values to <varname>val1</varname> and <varname>val2</varname>
575 respectively.  If either lookup fails, then clunky takes the
576 <literal>otherwise</literal> case and returns the sum of its arguments.
577 </para>
578
579 <para>
580 This is certainly legal Haskell, but it is a tremendously verbose and
581 un-obvious way to achieve the desired effect.  Arguably, a more direct way
582 to write clunky would be to use case expressions:
583 </para>
584
585 <programlisting>
586 clunky env var1 var2 = case lookup env var1 of
587   Nothing -&gt; fail
588   Just val1 -&gt; case lookup env var2 of
589     Nothing -&gt; fail
590     Just val2 -&gt; val1 + val2
591 where
592   fail = var1 + var2
593 </programlisting>
594
595 <para>
596 This is a bit shorter, but hardly better.  Of course, we can rewrite any set
597 of pattern-matching, guarded equations as case expressions; that is
598 precisely what the compiler does when compiling equations! The reason that
599 Haskell provides guarded equations is because they allow us to write down
600 the cases we want to consider, one at a time, independently of each other. 
601 This structure is hidden in the case version.  Two of the right-hand sides
602 are really the same (<function>fail</function>), and the whole expression
603 tends to become more and more indented. 
604 </para>
605
606 <para>
607 Here is how I would write clunky:
608 </para>
609
610 <programlisting>
611 clunky env var1 var2
612   | Just val1 &lt;- lookup env var1
613   , Just val2 &lt;- lookup env var2
614   = val1 + val2
615 ...other equations for clunky...
616 </programlisting>
617
618 <para>
619 The semantics should be clear enough.  The qualifiers are matched in order. 
620 For a <literal>&lt;-</literal> qualifier, which I call a pattern guard, the
621 right hand side is evaluated and matched against the pattern on the left. 
622 If the match fails then the whole guard fails and the next equation is
623 tried.  If it succeeds, then the appropriate binding takes place, and the
624 next qualifier is matched, in the augmented environment.  Unlike list
625 comprehensions, however, the type of the expression to the right of the
626 <literal>&lt;-</literal> is the same as the type of the pattern to its
627 left.  The bindings introduced by pattern guards scope over all the
628 remaining guard qualifiers, and over the right hand side of the equation.
629 </para>
630
631 <para>
632 Just as with list comprehensions, boolean expressions can be freely mixed
633 with among the pattern guards.  For example:
634 </para>
635
636 <programlisting>
637 f x | [y] &lt;- x
638     , y > 3
639     , Just z &lt;- h y
640     = ...
641 </programlisting>
642
643 <para>
644 Haskell's current guards therefore emerge as a special case, in which the
645 qualifier list has just one element, a boolean expression.
646 </para>
647 </sect2>
648
649     <!-- ===================== View patterns ===================  -->
650
651 <sect2 id="view-patterns">
652 <title>View patterns
653 </title>
654
655 <para>
656 View patterns are enabled by the flag <literal>-XViewPatterns</literal>.
657 More information and examples of view patterns can be found on the
658 <ulink url="http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns">Wiki
659 page</ulink>.
660 </para>
661
662 <para>
663 View patterns are somewhat like pattern guards that can be nested inside
664 of other patterns.  They are a convenient way of pattern-matching
665 against values of abstract types. For example, in a programming language
666 implementation, we might represent the syntax of the types of the
667 language as follows:
668
669 <programlisting>
670 type Typ
671  
672 data TypView = Unit
673              | Arrow Typ Typ
674
675 view :: Type -> TypeView
676
677 -- additional operations for constructing Typ's ...
678 </programlisting>
679
680 The representation of Typ is held abstract, permitting implementations
681 to use a fancy representation (e.g., hash-consing to manage sharing).
682
683 Without view patterns, using this signature a little inconvenient: 
684 <programlisting>
685 size :: Typ -> Integer
686 size t = case view t of
687   Unit -> 1
688   Arrow t1 t2 -> size t1 + size t2
689 </programlisting>
690
691 It is necessary to iterate the case, rather than using an equational
692 function definition. And the situation is even worse when the matching
693 against <literal>t</literal> is buried deep inside another pattern.
694 </para>
695
696 <para>
697 View patterns permit calling the view function inside the pattern and
698 matching against the result: 
699 <programlisting>
700 size (view -> Unit) = 1
701 size (view -> Arrow t1 t2) = size t1 + size t2
702 </programlisting>
703
704 That is, we add a new form of pattern, written
705 <replaceable>expression</replaceable> <literal>-></literal>
706 <replaceable>pattern</replaceable> that means "apply the expression to
707 whatever we're trying to match against, and then match the result of
708 that application against the pattern". The expression can be any Haskell
709 expression of function type, and view patterns can be used wherever
710 patterns are used.
711 </para>
712
713 <para>
714 The semantics of a pattern <literal>(</literal>
715 <replaceable>exp</replaceable> <literal>-></literal>
716 <replaceable>pat</replaceable> <literal>)</literal> are as follows:
717
718 <itemizedlist>
719
720 <listitem> Scoping:
721
722 <para>The variables bound by the view pattern are the variables bound by
723 <replaceable>pat</replaceable>.
724 </para>
725
726 <para>
727 Any variables in <replaceable>exp</replaceable> are bound occurrences,
728 but variables bound "to the left" in a pattern are in scope.  This
729 feature permits, for example, one argument to a function to be used in
730 the view of another argument.  For example, the function
731 <literal>clunky</literal> from <xref linkend="pattern-guards" /> can be
732 written using view patterns as follows:
733
734 <programlisting>
735 clunky env (lookup env -> Just val1) (lookup env -> Just val2) = val1 + val2
736 ...other equations for clunky...
737 </programlisting>
738 </para>
739
740 <para>
741 More precisely, the scoping rules are: 
742 <itemizedlist>
743 <listitem>
744 <para>
745 In a single pattern, variables bound by patterns to the left of a view
746 pattern expression are in scope. For example:
747 <programlisting>
748 example :: Maybe ((String -> Integer,Integer), String) -> Bool
749 example Just ((f,_), f -> 4) = True
750 </programlisting>
751
752 Additionally, in function definitions, variables bound by matching earlier curried
753 arguments may be used in view pattern expressions in later arguments:
754 <programlisting>
755 example :: (String -> Integer) -> String -> Bool
756 example f (f -> 4) = True
757 </programlisting>
758 That is, the scoping is the same as it would be if the curried arguments
759 were collected into a tuple.  
760 </para>
761 </listitem>
762
763 <listitem>
764 <para>
765 In mutually recursive bindings, such as <literal>let</literal>,
766 <literal>where</literal>, or the top level, view patterns in one
767 declaration may not mention variables bound by other declarations.  That
768 is, each declaration must be self-contained.  For example, the following
769 program is not allowed:
770 <programlisting>
771 let {(x -> y) = e1 ;
772      (y -> x) = e2 } in x
773 </programlisting>
774
775 (We may lift this
776 restriction in the future; the only cost is that type checking patterns
777 would get a little more complicated.)  
778
779
780 </para>
781 </listitem>
782 </itemizedlist>
783
784 </para>
785 </listitem>
786
787 <listitem><para> Typing: If <replaceable>exp</replaceable> has type
788 <replaceable>T1</replaceable> <literal>-></literal>
789 <replaceable>T2</replaceable> and <replaceable>pat</replaceable> matches
790 a <replaceable>T2</replaceable>, then the whole view pattern matches a
791 <replaceable>T1</replaceable>.
792 </para></listitem>
793
794 <listitem><para> Matching: To the equations in Section 3.17.3 of the
795 <ulink url="http://www.haskell.org/onlinereport/">Haskell 98
796 Report</ulink>, add the following:
797 <programlisting>
798 case v of { (e -> p) -> e1 ; _ -> e2 } 
799  = 
800 case (e v) of { p -> e1 ; _ -> e2 }
801 </programlisting>
802 That is, to match a variable <replaceable>v</replaceable> against a pattern
803 <literal>(</literal> <replaceable>exp</replaceable>
804 <literal>-></literal> <replaceable>pat</replaceable>
805 <literal>)</literal>, evaluate <literal>(</literal>
806 <replaceable>exp</replaceable> <replaceable> v</replaceable>
807 <literal>)</literal> and match the result against
808 <replaceable>pat</replaceable>.  
809 </para></listitem>
810
811 <listitem><para> Efficiency: When the same view function is applied in
812 multiple branches of a function definition or a case expression (e.g.,
813 in <literal>size</literal> above), GHC makes an attempt to collect these
814 applications into a single nested case expression, so that the view
815 function is only applied once.  Pattern compilation in GHC follows the
816 matrix algorithm described in Chapter 4 of <ulink
817 url="http://research.microsoft.com/~simonpj/Papers/slpj-book-1987/">The
818 Implementation of Functional Programming Languages</ulink>.  When the
819 top rows of the first column of a matrix are all view patterns with the
820 "same" expression, these patterns are transformed into a single nested
821 case.  This includes, for example, adjacent view patterns that line up
822 in a tuple, as in
823 <programlisting>
824 f ((view -> A, p1), p2) = e1
825 f ((view -> B, p3), p4) = e2
826 </programlisting>
827 </para>
828
829 <para> The current notion of when two view pattern expressions are "the
830 same" is very restricted: it is not even full syntactic equality.
831 However, it does include variables, literals, applications, and tuples;
832 e.g., two instances of <literal>view ("hi", "there")</literal> will be
833 collected.  However, the current implementation does not compare up to
834 alpha-equivalence, so two instances of <literal>(x, view x ->
835 y)</literal> will not be coalesced.
836 </para>
837
838 </listitem>
839
840 </itemizedlist>
841 </para>
842
843 </sect2>
844
845     <!-- ===================== Recursive do-notation ===================  -->
846
847 <sect2 id="mdo-notation">
848 <title>The recursive do-notation
849 </title>
850
851 <para> The recursive do-notation (also known as mdo-notation) is implemented as described in
852 <ulink url="http://citeseer.ist.psu.edu/erk02recursive.html">A recursive do for Haskell</ulink>,
853 by Levent Erkok, John Launchbury,
854 Haskell Workshop 2002, pages: 29-37. Pittsburgh, Pennsylvania. 
855 This paper is essential reading for anyone making non-trivial use of mdo-notation,
856 and we do not repeat it here.
857 </para>
858 <para>
859 The do-notation of Haskell does not allow <emphasis>recursive bindings</emphasis>,
860 that is, the variables bound in a do-expression are visible only in the textually following 
861 code block. Compare this to a let-expression, where bound variables are visible in the entire binding
862 group. It turns out that several applications can benefit from recursive bindings in
863 the do-notation, and this extension provides the necessary syntactic support.
864 </para>
865 <para>
866 Here is a simple (yet contrived) example:
867 </para>
868 <programlisting>
869 import Control.Monad.Fix
870
871 justOnes = mdo xs &lt;- Just (1:xs)
872                return xs
873 </programlisting>
874 <para>
875 As you can guess <literal>justOnes</literal> will evaluate to <literal>Just [1,1,1,...</literal>.
876 </para>
877
878 <para>
879 The Control.Monad.Fix library introduces the <literal>MonadFix</literal> class. It's definition is:
880 </para>
881 <programlisting>
882 class Monad m => MonadFix m where
883    mfix :: (a -> m a) -> m a
884 </programlisting>
885 <para>
886 The function <literal>mfix</literal>
887 dictates how the required recursion operation should be performed.  For example, 
888 <literal>justOnes</literal> desugars as follows:
889 <programlisting>
890 justOnes = mfix (\xs' -&gt; do { xs &lt;- Just (1:xs'); return xs }
891 </programlisting>
892 For full details of the way in which mdo is typechecked and desugared, see 
893 the paper <ulink url="http://citeseer.ist.psu.edu/erk02recursive.html">A recursive do for Haskell</ulink>.
894 In particular, GHC implements the segmentation technique described in Section 3.2 of the paper.
895 </para>
896 <para>
897 If recursive bindings are required for a monad,
898 then that monad must be declared an instance of the <literal>MonadFix</literal> class.
899 The following instances of <literal>MonadFix</literal> are automatically provided: List, Maybe, IO. 
900 Furthermore, the Control.Monad.ST and Control.Monad.ST.Lazy modules provide the instances of the MonadFix class 
901 for Haskell's internal state monad (strict and lazy, respectively).
902 </para>
903 <para>
904 Here are some important points in using the recursive-do notation:
905 <itemizedlist>
906 <listitem><para>
907 The recursive version of the do-notation uses the keyword <literal>mdo</literal> (rather
908 than <literal>do</literal>).
909 </para></listitem>
910
911 <listitem><para>
912 It is enabled with the flag <literal>-XRecursiveDo</literal>, which is in turn implied by
913 <literal>-fglasgow-exts</literal>.
914 </para></listitem>
915
916 <listitem><para>
917 Unlike ordinary do-notation, but like <literal>let</literal> and <literal>where</literal> bindings,
918 name shadowing is not allowed; that is, all the names bound in a single <literal>mdo</literal> must
919 be distinct (Section 3.3 of the paper).
920 </para></listitem>
921
922 <listitem><para>
923 Variables bound by a <literal>let</literal> statement in an <literal>mdo</literal>
924 are monomorphic in the <literal>mdo</literal> (Section 3.1 of the paper).  However
925 GHC breaks the <literal>mdo</literal> into segments to enhance polymorphism,
926 and improve termination (Section 3.2 of the paper).
927 </para></listitem>
928 </itemizedlist>
929 </para>
930
931 <para>
932 Historical note: The old implementation of the mdo-notation (and most
933 of the existing documents) used the name
934 <literal>MonadRec</literal> for the class and the corresponding library.
935 This name is not supported by GHC.
936 </para>
937
938 </sect2>
939
940
941    <!-- ===================== PARALLEL LIST COMPREHENSIONS ===================  -->
942
943   <sect2 id="parallel-list-comprehensions">
944     <title>Parallel List Comprehensions</title>
945     <indexterm><primary>list comprehensions</primary><secondary>parallel</secondary>
946     </indexterm>
947     <indexterm><primary>parallel list comprehensions</primary>
948     </indexterm>
949
950     <para>Parallel list comprehensions are a natural extension to list
951     comprehensions.  List comprehensions can be thought of as a nice
952     syntax for writing maps and filters.  Parallel comprehensions
953     extend this to include the zipWith family.</para>
954
955     <para>A parallel list comprehension has multiple independent
956     branches of qualifier lists, each separated by a `|' symbol.  For
957     example, the following zips together two lists:</para>
958
959 <programlisting>
960    [ (x, y) | x &lt;- xs | y &lt;- ys ] 
961 </programlisting>
962
963     <para>The behavior of parallel list comprehensions follows that of
964     zip, in that the resulting list will have the same length as the
965     shortest branch.</para>
966
967     <para>We can define parallel list comprehensions by translation to
968     regular comprehensions.  Here's the basic idea:</para>
969
970     <para>Given a parallel comprehension of the form: </para>
971
972 <programlisting>
973    [ e | p1 &lt;- e11, p2 &lt;- e12, ... 
974        | q1 &lt;- e21, q2 &lt;- e22, ... 
975        ... 
976    ] 
977 </programlisting>
978
979     <para>This will be translated to: </para>
980
981 <programlisting>
982    [ e | ((p1,p2), (q1,q2), ...) &lt;- zipN [(p1,p2) | p1 &lt;- e11, p2 &lt;- e12, ...] 
983                                          [(q1,q2) | q1 &lt;- e21, q2 &lt;- e22, ...] 
984                                          ... 
985    ] 
986 </programlisting>
987
988     <para>where `zipN' is the appropriate zip for the given number of
989     branches.</para>
990
991   </sect2>
992   
993   <!-- ===================== TRANSFORM LIST COMPREHENSIONS ===================  -->
994
995   <sect2 id="generalised-list-comprehensions">
996     <title>Generalised (SQL-Like) List Comprehensions</title>
997     <indexterm><primary>list comprehensions</primary><secondary>generalised</secondary>
998     </indexterm>
999     <indexterm><primary>extended list comprehensions</primary>
1000     </indexterm>
1001     <indexterm><primary>group</primary></indexterm>
1002     <indexterm><primary>sql</primary></indexterm>
1003
1004
1005     <para>Generalised list comprehensions are a further enhancement to the
1006     list comprehension syntatic sugar to allow operations such as sorting
1007     and grouping which are familiar from SQL.   They are fully described in the
1008         paper <ulink url="http://research.microsoft.com/~simonpj/papers/list-comp">
1009           Comprehensive comprehensions: comprehensions with "order by" and "group by"</ulink>,
1010     except that the syntax we use differs slightly from the paper.</para>
1011 <para>Here is an example: 
1012 <programlisting>
1013 employees = [ ("Simon", "MS", 80)
1014 , ("Erik", "MS", 100)
1015 , ("Phil", "Ed", 40)
1016 , ("Gordon", "Ed", 45)
1017 , ("Paul", "Yale", 60)]
1018
1019 output = [ (the dept, sum salary)
1020 | (name, dept, salary) &lt;- employees
1021 , then group by dept
1022 , then sortWith by (sum salary)
1023 , then take 5 ]
1024 </programlisting>
1025 In this example, the list <literal>output</literal> would take on 
1026     the value:
1027     
1028 <programlisting>
1029 [("Yale", 60), ("Ed", 85), ("MS", 180)]
1030 </programlisting>
1031 </para>
1032 <para>There are three new keywords: <literal>group</literal>, <literal>by</literal>, and <literal>using</literal>.
1033 (The function <literal>sortWith</literal> is not a keyword; it is an ordinary
1034 function that is exported by <literal>GHC.Exts</literal>.)</para>
1035
1036 <para>There are five new forms of comprehension qualifier,
1037 all introduced by the (existing) keyword <literal>then</literal>:
1038     <itemizedlist>
1039     <listitem>
1040     
1041 <programlisting>
1042 then f
1043 </programlisting>
1044
1045     This statement requires that <literal>f</literal> have the type <literal>
1046     forall a. [a] -> [a]</literal>. You can see an example of it's use in the
1047     motivating example, as this form is used to apply <literal>take 5</literal>.
1048     
1049     </listitem>
1050     
1051     
1052     <listitem>
1053 <para>
1054 <programlisting>
1055 then f by e
1056 </programlisting>
1057
1058     This form is similar to the previous one, but allows you to create a function
1059     which will be passed as the first argument to f. As a consequence f must have 
1060     the type <literal>forall a. (a -> t) -> [a] -> [a]</literal>. As you can see
1061     from the type, this function lets f &quot;project out&quot; some information 
1062     from the elements of the list it is transforming.</para>
1063
1064     <para>An example is shown in the opening example, where <literal>sortWith</literal> 
1065     is supplied with a function that lets it find out the <literal>sum salary</literal> 
1066     for any item in the list comprehension it transforms.</para>
1067
1068     </listitem>
1069
1070
1071     <listitem>
1072
1073 <programlisting>
1074 then group by e using f
1075 </programlisting>
1076
1077     <para>This is the most general of the grouping-type statements. In this form,
1078     f is required to have type <literal>forall a. (a -> t) -> [a] -> [[a]]</literal>.
1079     As with the <literal>then f by e</literal> case above, the first argument
1080     is a function supplied to f by the compiler which lets it compute e on every
1081     element of the list being transformed. However, unlike the non-grouping case,
1082     f additionally partitions the list into a number of sublists: this means that
1083     at every point after this statement, binders occurring before it in the comprehension
1084     refer to <emphasis>lists</emphasis> of possible values, not single values. To help understand
1085     this, let's look at an example:</para>
1086     
1087 <programlisting>
1088 -- This works similarly to groupWith in GHC.Exts, but doesn't sort its input first
1089 groupRuns :: Eq b => (a -> b) -> [a] -> [[a]]
1090 groupRuns f = groupBy (\x y -> f x == f y)
1091
1092 output = [ (the x, y)
1093 | x &lt;- ([1..3] ++ [1..2])
1094 , y &lt;- [4..6]
1095 , then group by x using groupRuns ]
1096 </programlisting>
1097
1098     <para>This results in the variable <literal>output</literal> taking on the value below:</para>
1099
1100 <programlisting>
1101 [(1, [4, 5, 6]), (2, [4, 5, 6]), (3, [4, 5, 6]), (1, [4, 5, 6]), (2, [4, 5, 6])]
1102 </programlisting>
1103
1104     <para>Note that we have used the <literal>the</literal> function to change the type 
1105     of x from a list to its original numeric type. The variable y, in contrast, is left 
1106     unchanged from the list form introduced by the grouping.</para>
1107
1108     </listitem>
1109
1110     <listitem>
1111
1112 <programlisting>
1113 then group by e
1114 </programlisting>
1115
1116     <para>This form of grouping is essentially the same as the one described above. However,
1117     since no function to use for the grouping has been supplied it will fall back on the
1118     <literal>groupWith</literal> function defined in 
1119     <ulink url="../libraries/base/GHC-Exts.html"><literal>GHC.Exts</literal></ulink>. This
1120     is the form of the group statement that we made use of in the opening example.</para>
1121
1122     </listitem>
1123     
1124     
1125     <listitem>
1126
1127 <programlisting>
1128 then group using f
1129 </programlisting>
1130
1131     <para>With this form of the group statement, f is required to simply have the type
1132     <literal>forall a. [a] -> [[a]]</literal>, which will be used to group up the
1133     comprehension so far directly. An example of this form is as follows:</para>
1134     
1135 <programlisting>
1136 output = [ x
1137 | y &lt;- [1..5]
1138 , x &lt;- "hello"
1139 , then group using inits]
1140 </programlisting>
1141
1142     <para>This will yield a list containing every prefix of the word "hello" written out 5 times:</para>
1143
1144 <programlisting>
1145 ["","h","he","hel","hell","hello","helloh","hellohe","hellohel","hellohell","hellohello","hellohelloh",...]
1146 </programlisting>
1147
1148     </listitem>
1149 </itemizedlist>
1150 </para>
1151   </sect2>
1152
1153    <!-- ===================== REBINDABLE SYNTAX ===================  -->
1154
1155 <sect2 id="rebindable-syntax">
1156 <title>Rebindable syntax and the implicit Prelude import</title>
1157
1158  <para><indexterm><primary>-XNoImplicitPrelude
1159  option</primary></indexterm> GHC normally imports
1160  <filename>Prelude.hi</filename> files for you.  If you'd
1161  rather it didn't, then give it a
1162  <option>-XNoImplicitPrelude</option> option.  The idea is
1163  that you can then import a Prelude of your own.  (But don't
1164  call it <literal>Prelude</literal>; the Haskell module
1165  namespace is flat, and you must not conflict with any
1166  Prelude module.)</para>
1167
1168             <para>Suppose you are importing a Prelude of your own
1169               in order to define your own numeric class
1170             hierarchy.  It completely defeats that purpose if the
1171             literal "1" means "<literal>Prelude.fromInteger
1172             1</literal>", which is what the Haskell Report specifies.
1173             So the <option>-XNoImplicitPrelude</option> 
1174               flag <emphasis>also</emphasis> causes
1175             the following pieces of built-in syntax to refer to
1176             <emphasis>whatever is in scope</emphasis>, not the Prelude
1177             versions:
1178             <itemizedlist>
1179               <listitem>
1180                 <para>An integer literal <literal>368</literal> means
1181                 "<literal>fromInteger (368::Integer)</literal>", rather than
1182                 "<literal>Prelude.fromInteger (368::Integer)</literal>".
1183 </para> </listitem>         
1184
1185       <listitem><para>Fractional literals are handed in just the same way,
1186           except that the translation is 
1187               <literal>fromRational (3.68::Rational)</literal>.
1188 </para> </listitem>         
1189
1190           <listitem><para>The equality test in an overloaded numeric pattern
1191               uses whatever <literal>(==)</literal> is in scope.
1192 </para> </listitem>         
1193
1194           <listitem><para>The subtraction operation, and the
1195           greater-than-or-equal test, in <literal>n+k</literal> patterns
1196               use whatever <literal>(-)</literal> and <literal>(>=)</literal> are in scope.
1197               </para></listitem>
1198
1199               <listitem>
1200                 <para>Negation (e.g. "<literal>- (f x)</literal>")
1201                 means "<literal>negate (f x)</literal>", both in numeric
1202                 patterns, and expressions.
1203               </para></listitem>
1204
1205               <listitem>
1206           <para>"Do" notation is translated using whatever
1207               functions <literal>(>>=)</literal>,
1208               <literal>(>>)</literal>, and <literal>fail</literal>,
1209               are in scope (not the Prelude
1210               versions).  List comprehensions, mdo (<xref linkend="mdo-notation"/>), and parallel array
1211               comprehensions, are unaffected.  </para></listitem>
1212
1213               <listitem>
1214                 <para>Arrow
1215                 notation (see <xref linkend="arrow-notation"/>)
1216                 uses whatever <literal>arr</literal>,
1217                 <literal>(>>>)</literal>, <literal>first</literal>,
1218                 <literal>app</literal>, <literal>(|||)</literal> and
1219                 <literal>loop</literal> functions are in scope. But unlike the
1220                 other constructs, the types of these functions must match the
1221                 Prelude types very closely.  Details are in flux; if you want
1222                 to use this, ask!
1223               </para></listitem>
1224             </itemizedlist>
1225 In all cases (apart from arrow notation), the static semantics should be that of the desugared form,
1226 even if that is a little unexpected. For example, the 
1227 static semantics of the literal <literal>368</literal>
1228 is exactly that of <literal>fromInteger (368::Integer)</literal>; it's fine for
1229 <literal>fromInteger</literal> to have any of the types:
1230 <programlisting>
1231 fromInteger :: Integer -> Integer
1232 fromInteger :: forall a. Foo a => Integer -> a
1233 fromInteger :: Num a => a -> Integer
1234 fromInteger :: Integer -> Bool -> Bool
1235 </programlisting>
1236 </para>
1237                 
1238              <para>Be warned: this is an experimental facility, with
1239              fewer checks than usual.  Use <literal>-dcore-lint</literal>
1240              to typecheck the desugared program.  If Core Lint is happy
1241              you should be all right.</para>
1242
1243 </sect2>
1244
1245 <sect2 id="postfix-operators">
1246 <title>Postfix operators</title>
1247
1248 <para>
1249   The <option>-XPostfixOperators</option> flag enables a small
1250 extension to the syntax of left operator sections, which allows you to
1251 define postfix operators.  The extension is this: the left section
1252 <programlisting>
1253   (e !)
1254 </programlisting>
1255 is equivalent (from the point of view of both type checking and execution) to the expression
1256 <programlisting>
1257   ((!) e)
1258 </programlisting>
1259 (for any expression <literal>e</literal> and operator <literal>(!)</literal>.
1260 The strict Haskell 98 interpretation is that the section is equivalent to
1261 <programlisting>
1262   (\y -> (!) e y)
1263 </programlisting>
1264 That is, the operator must be a function of two arguments.  GHC allows it to
1265 take only one argument, and that in turn allows you to write the function
1266 postfix.
1267 </para>
1268 <para>The extension does not extend to the left-hand side of function
1269 definitions; you must define such a function in prefix form.</para>
1270
1271 </sect2>
1272
1273 <sect2 id="disambiguate-fields">
1274 <title>Record field disambiguation</title>
1275 <para>
1276 In record construction and record pattern matching
1277 it is entirely unambiguous which field is referred to, even if there are two different
1278 data types in scope with a common field name.  For example:
1279 <programlisting>
1280 module M where
1281   data S = MkS { x :: Int, y :: Bool }
1282
1283 module Foo where
1284   import M
1285
1286   data T = MkT { x :: Int }
1287   
1288   ok1 (MkS { x = n }) = n+1   -- Unambiguous
1289
1290   ok2 n = MkT { x = n+1 }     -- Unambiguous
1291
1292   bad1 k = k { x = 3 }  -- Ambiguous
1293   bad2 k = x k          -- Ambiguous
1294 </programlisting>
1295 Even though there are two <literal>x</literal>'s in scope,
1296 it is clear that the <literal>x</literal> in the pattern in the
1297 definition of <literal>ok1</literal> can only mean the field
1298 <literal>x</literal> from type <literal>S</literal>. Similarly for
1299 the function <literal>ok2</literal>.  However, in the record update
1300 in <literal>bad1</literal> and the record selection in <literal>bad2</literal>
1301 it is not clear which of the two types is intended.
1302 </para>
1303 <para>
1304 Haskell 98 regards all four as ambiguous, but with the
1305 <option>-XDisambiguateRecordFields</option> flag, GHC will accept
1306 the former two.  The rules are precisely the same as those for instance
1307 declarations in Haskell 98, where the method names on the left-hand side 
1308 of the method bindings in an instance declaration refer unambiguously
1309 to the method of that class (provided they are in scope at all), even
1310 if there are other variables in scope with the same name.
1311 This reduces the clutter of qualified names when you import two
1312 records from different modules that use the same field name.
1313 </para>
1314 </sect2>
1315
1316     <!-- ===================== Record puns ===================  -->
1317
1318 <sect2 id="record-puns">
1319 <title>Record puns
1320 </title>
1321
1322 <para>
1323 Record puns are enabled by the flag <literal>-XNamedFieldPuns</literal>.
1324 </para>
1325
1326 <para>
1327 When using records, it is common to write a pattern that binds a
1328 variable with the same name as a record field, such as:
1329
1330 <programlisting>
1331 data C = C {a :: Int}
1332 f (C {a = a}) = a
1333 </programlisting>
1334 </para>
1335
1336 <para>
1337 Record punning permits the variable name to be elided, so one can simply
1338 write
1339
1340 <programlisting>
1341 f (C {a}) = a
1342 </programlisting>
1343
1344 to mean the same pattern as above.  That is, in a record pattern, the
1345 pattern <literal>a</literal> expands into the pattern <literal>a =
1346 a</literal> for the same name <literal>a</literal>.  
1347 </para>
1348
1349 <para>
1350 Note that puns and other patterns can be mixed in the same record:
1351 <programlisting>
1352 data C = C {a :: Int, b :: Int}
1353 f (C {a, b = 4}) = a
1354 </programlisting>
1355 and that puns can be used wherever record patterns occur (e.g. in
1356 <literal>let</literal> bindings or at the top-level).  
1357 </para>
1358
1359 <para>
1360 Record punning can also be used in an expression, writing, for example,
1361 <programlisting>
1362 let a = 1 in C {a}
1363 </programlisting>
1364 instead of 
1365 <programlisting>
1366 let a = 1 in C {a = a}
1367 </programlisting>
1368
1369 Note that this expansion is purely syntactic, so the record pun
1370 expression refers to the nearest enclosing variable that is spelled the
1371 same as the field name.
1372 </para>
1373
1374 </sect2>
1375
1376     <!-- ===================== Record wildcards ===================  -->
1377
1378 <sect2 id="record-wildcards">
1379 <title>Record wildcards
1380 </title>
1381
1382 <para>
1383 Record wildcards are enabled by the flag <literal>-XRecordWildCards</literal>.
1384 </para>
1385
1386 <para>
1387 For records with many fields, it can be tiresome to write out each field
1388 individually in a record pattern, as in
1389 <programlisting>
1390 data C = C {a :: Int, b :: Int, c :: Int, d :: Int}
1391 f (C {a = 1, b = b, c = c, d = d}) = b + c + d
1392 </programlisting>
1393 </para>
1394
1395 <para>
1396 Record wildcard syntax permits a (<literal>..</literal>) in a record
1397 pattern, where each elided field <literal>f</literal> is replaced by the
1398 pattern <literal>f = f</literal>.  For example, the above pattern can be
1399 written as
1400 <programlisting>
1401 f (C {a = 1, ..}) = b + c + d
1402 </programlisting>
1403 </para>
1404
1405 <para>
1406 Note that wildcards can be mixed with other patterns, including puns
1407 (<xref linkend="record-puns"/>); for example, in a pattern <literal>C {a
1408 = 1, b, ..})</literal>.  Additionally, record wildcards can be used
1409 wherever record patterns occur, including in <literal>let</literal>
1410 bindings and at the top-level.  For example, the top-level binding
1411 <programlisting>
1412 C {a = 1, ..} = e
1413 </programlisting>
1414 defines <literal>b</literal>, <literal>c</literal>, and
1415 <literal>d</literal>.
1416 </para>
1417
1418 <para>
1419 Record wildcards can also be used in expressions, writing, for example,
1420
1421 <programlisting>
1422 let {a = 1; b = 2; c = 3; d = 4} in C {..}
1423 </programlisting>
1424
1425 in place of
1426
1427 <programlisting>
1428 let {a = 1; b = 2; c = 3; d = 4} in C {a=a, b=b, c=c, d=d}
1429 </programlisting>
1430
1431 Note that this expansion is purely syntactic, so the record wildcard
1432 expression refers to the nearest enclosing variables that are spelled
1433 the same as the omitted field names.
1434 </para>
1435
1436 </sect2>
1437
1438     <!-- ===================== Local fixity declarations ===================  -->
1439
1440 <sect2 id="local-fixity-declarations">
1441 <title>Local Fixity Declarations
1442 </title>
1443
1444 <para>A careful reading of the Haskell 98 Report reveals that fixity
1445 declarations (<literal>infix</literal>, <literal>infixl</literal>, and
1446 <literal>infixr</literal>) are permitted to appear inside local bindings
1447 such those introduced by <literal>let</literal> and
1448 <literal>where</literal>.  However, the Haskell Report does not specify
1449 the semantics of such bindings very precisely.
1450 </para>
1451
1452 <para>In GHC, a fixity declaration may accompany a local binding:
1453 <programlisting>
1454 let f = ...
1455     infixr 3 `f`
1456 in 
1457     ...
1458 </programlisting>
1459 and the fixity declaration applies wherever the binding is in scope.
1460 For example, in a <literal>let</literal>, it applies in the right-hand
1461 sides of other <literal>let</literal>-bindings and the body of the
1462 <literal>let</literal>C. Or, in recursive <literal>do</literal>
1463 expressions (<xref linkend="mdo-notation"/>), the local fixity
1464 declarations of a <literal>let</literal> statement scope over other
1465 statements in the group, just as the bound name does.
1466 </para>
1467
1468 <para>
1469 Moreover, a local fixity declaration *must* accompany a local binding of
1470 that name: it is not possible to revise the fixity of name bound
1471 elsewhere, as in
1472 <programlisting>
1473 let infixr 9 $ in ...
1474 </programlisting>
1475
1476 Because local fixity declarations are technically Haskell 98, no flag is
1477 necessary to enable them.
1478 </para>
1479 </sect2>
1480
1481 <sect2 id="package-imports">
1482   <title>Package-qualified imports</title>
1483
1484   <para>With the <option>-XPackageImports</option> flag, GHC allows
1485   import declarations to be qualified by the package name that the
1486     module is intended to be imported from.  For example:</para>
1487
1488 <programlisting>
1489 import "network" Network.Socket
1490 </programlisting>
1491   
1492   <para>would import the module <literal>Network.Socket</literal> from
1493     the package <literal>network</literal> (any version).  This may
1494     be used to disambiguate an import when the same module is
1495     available from multiple packages, or is present in both the
1496     current package being built and an external package.</para>
1497
1498   <para>Note: you probably don't need to use this feature, it was
1499     added mainly so that we can build backwards-compatible versions of
1500     packages when APIs change.  It can lead to fragile dependencies in
1501     the common case: modules occasionally move from one package to
1502     another, rendering any package-qualified imports broken.</para>
1503 </sect2>
1504
1505 <sect2 id="syntax-stolen">
1506 <title>Summary of stolen syntax</title>
1507
1508     <para>Turning on an option that enables special syntax
1509     <emphasis>might</emphasis> cause working Haskell 98 code to fail
1510     to compile, perhaps because it uses a variable name which has
1511     become a reserved word.  This section lists the syntax that is
1512     "stolen" by language extensions.
1513      We use
1514     notation and nonterminal names from the Haskell 98 lexical syntax
1515     (see the Haskell 98 Report).  
1516     We only list syntax changes here that might affect
1517     existing working programs (i.e. "stolen" syntax).  Many of these
1518     extensions will also enable new context-free syntax, but in all
1519     cases programs written to use the new syntax would not be
1520     compilable without the option enabled.</para>
1521
1522 <para>There are two classes of special
1523     syntax:
1524
1525     <itemizedlist>
1526       <listitem>
1527         <para>New reserved words and symbols: character sequences
1528         which are no longer available for use as identifiers in the
1529         program.</para>
1530       </listitem>
1531       <listitem>
1532         <para>Other special syntax: sequences of characters that have
1533         a different meaning when this particular option is turned
1534         on.</para>
1535       </listitem>
1536     </itemizedlist>
1537     
1538 The following syntax is stolen:
1539
1540     <variablelist>
1541       <varlistentry>
1542         <term>
1543           <literal>forall</literal>
1544           <indexterm><primary><literal>forall</literal></primary></indexterm>
1545         </term>
1546         <listitem><para>
1547         Stolen (in types) by: <option>-XScopedTypeVariables</option>,
1548             <option>-XLiberalTypeSynonyms</option>,
1549             <option>-XRank2Types</option>,
1550             <option>-XRankNTypes</option>,
1551             <option>-XPolymorphicComponents</option>,
1552             <option>-XExistentialQuantification</option>
1553           </para></listitem>
1554       </varlistentry>
1555
1556       <varlistentry>
1557         <term>
1558           <literal>mdo</literal>
1559           <indexterm><primary><literal>mdo</literal></primary></indexterm>
1560         </term>
1561         <listitem><para>
1562         Stolen by: <option>-XRecursiveDo</option>,
1563           </para></listitem>
1564       </varlistentry>
1565
1566       <varlistentry>
1567         <term>
1568           <literal>foreign</literal>
1569           <indexterm><primary><literal>foreign</literal></primary></indexterm>
1570         </term>
1571         <listitem><para>
1572         Stolen by: <option>-XForeignFunctionInterface</option>,
1573           </para></listitem>
1574       </varlistentry>
1575
1576       <varlistentry>
1577         <term>
1578           <literal>rec</literal>,
1579           <literal>proc</literal>, <literal>-&lt;</literal>,
1580           <literal>&gt;-</literal>, <literal>-&lt;&lt;</literal>,
1581           <literal>&gt;&gt;-</literal>, and <literal>(|</literal>,
1582           <literal>|)</literal> brackets
1583           <indexterm><primary><literal>proc</literal></primary></indexterm>
1584         </term>
1585         <listitem><para>
1586         Stolen by: <option>-XArrows</option>,
1587           </para></listitem>
1588       </varlistentry>
1589
1590       <varlistentry>
1591         <term>
1592           <literal>?<replaceable>varid</replaceable></literal>,
1593           <literal>%<replaceable>varid</replaceable></literal>
1594           <indexterm><primary>implicit parameters</primary></indexterm>
1595         </term>
1596         <listitem><para>
1597         Stolen by: <option>-XImplicitParams</option>,
1598           </para></listitem>
1599       </varlistentry>
1600
1601       <varlistentry>
1602         <term>
1603           <literal>[|</literal>,
1604           <literal>[e|</literal>, <literal>[p|</literal>,
1605           <literal>[d|</literal>, <literal>[t|</literal>,
1606           <literal>$(</literal>,
1607           <literal>$<replaceable>varid</replaceable></literal>
1608           <indexterm><primary>Template Haskell</primary></indexterm>
1609         </term>
1610         <listitem><para>
1611         Stolen by: <option>-XTemplateHaskell</option>,
1612           </para></listitem>
1613       </varlistentry>
1614
1615       <varlistentry>
1616         <term>
1617           <literal>[:<replaceable>varid</replaceable>|</literal>
1618           <indexterm><primary>quasi-quotation</primary></indexterm>
1619         </term>
1620         <listitem><para>
1621         Stolen by: <option>-XQuasiQuotes</option>,
1622           </para></listitem>
1623       </varlistentry>
1624
1625       <varlistentry>
1626         <term>
1627               <replaceable>varid</replaceable>{<literal>&num;</literal>},
1628               <replaceable>char</replaceable><literal>&num;</literal>,      
1629               <replaceable>string</replaceable><literal>&num;</literal>,    
1630               <replaceable>integer</replaceable><literal>&num;</literal>,    
1631               <replaceable>float</replaceable><literal>&num;</literal>,    
1632               <replaceable>float</replaceable><literal>&num;&num;</literal>,    
1633               <literal>(&num;</literal>, <literal>&num;)</literal>,         
1634         </term>
1635         <listitem><para>
1636         Stolen by: <option>-XMagicHash</option>,
1637           </para></listitem>
1638       </varlistentry>
1639     </variablelist>
1640 </para>
1641 </sect2>
1642 </sect1>
1643
1644
1645 <!-- TYPE SYSTEM EXTENSIONS -->
1646 <sect1 id="data-type-extensions">
1647 <title>Extensions to data types and type synonyms</title>
1648
1649 <sect2 id="nullary-types">
1650 <title>Data types with no constructors</title>
1651
1652 <para>With the <option>-fglasgow-exts</option> flag, GHC lets you declare
1653 a data type with no constructors.  For example:</para>
1654
1655 <programlisting>
1656   data S      -- S :: *
1657   data T a    -- T :: * -> *
1658 </programlisting>
1659
1660 <para>Syntactically, the declaration lacks the "= constrs" part.  The 
1661 type can be parameterised over types of any kind, but if the kind is
1662 not <literal>*</literal> then an explicit kind annotation must be used
1663 (see <xref linkend="kinding"/>).</para>
1664
1665 <para>Such data types have only one value, namely bottom.
1666 Nevertheless, they can be useful when defining "phantom types".</para>
1667 </sect2>
1668
1669 <sect2 id="infix-tycons">
1670 <title>Infix type constructors, classes, and type variables</title>
1671
1672 <para>
1673 GHC allows type constructors, classes, and type variables to be operators, and
1674 to be written infix, very much like expressions.  More specifically:
1675 <itemizedlist>
1676 <listitem><para>
1677   A type constructor or class can be an operator, beginning with a colon; e.g. <literal>:*:</literal>.
1678   The lexical syntax is the same as that for data constructors.
1679   </para></listitem>
1680 <listitem><para>
1681   Data type and type-synonym declarations can be written infix, parenthesised
1682   if you want further arguments.  E.g.
1683 <screen>
1684   data a :*: b = Foo a b
1685   type a :+: b = Either a b
1686   class a :=: b where ...
1687
1688   data (a :**: b) x = Baz a b x
1689   type (a :++: b) y = Either (a,b) y
1690 </screen>
1691   </para></listitem>
1692 <listitem><para>
1693   Types, and class constraints, can be written infix.  For example
1694   <screen>
1695         x :: Int :*: Bool
1696         f :: (a :=: b) => a -> b
1697   </screen>
1698   </para></listitem>
1699 <listitem><para>
1700   A type variable can be an (unqualified) operator e.g. <literal>+</literal>.
1701   The lexical syntax is the same as that for variable operators, excluding "(.)",
1702   "(!)", and "(*)".  In a binding position, the operator must be
1703   parenthesised.  For example:
1704 <programlisting>
1705    type T (+) = Int + Int
1706    f :: T Either
1707    f = Left 3
1708  
1709    liftA2 :: Arrow (~>)
1710           => (a -> b -> c) -> (e ~> a) -> (e ~> b) -> (e ~> c)
1711    liftA2 = ...
1712 </programlisting>
1713   </para></listitem>
1714 <listitem><para>
1715   Back-quotes work
1716   as for expressions, both for type constructors and type variables;  e.g. <literal>Int `Either` Bool</literal>, or
1717   <literal>Int `a` Bool</literal>.  Similarly, parentheses work the same; e.g.  <literal>(:*:) Int Bool</literal>.
1718   </para></listitem>
1719 <listitem><para>
1720   Fixities may be declared for type constructors, or classes, just as for data constructors.  However,
1721   one cannot distinguish between the two in a fixity declaration; a fixity declaration
1722   sets the fixity for a data constructor and the corresponding type constructor.  For example:
1723 <screen>
1724   infixl 7 T, :*:
1725 </screen>
1726   sets the fixity for both type constructor <literal>T</literal> and data constructor <literal>T</literal>,
1727   and similarly for <literal>:*:</literal>.
1728   <literal>Int `a` Bool</literal>.
1729   </para></listitem>
1730 <listitem><para>
1731   Function arrow is <literal>infixr</literal> with fixity 0.  (This might change; I'm not sure what it should be.)
1732   </para></listitem>
1733
1734 </itemizedlist>
1735 </para>
1736 </sect2>
1737
1738 <sect2 id="type-synonyms">
1739 <title>Liberalised type synonyms</title>
1740
1741 <para>
1742 Type synonyms are like macros at the type level, but Haskell 98 imposes many rules
1743 on individual synonym declarations.
1744 With the <option>-XLiberalTypeSynonyms</option> extension,
1745 GHC does validity checking on types <emphasis>only after expanding type synonyms</emphasis>.
1746 That means that GHC can be very much more liberal about type synonyms than Haskell 98. 
1747
1748 <itemizedlist>
1749 <listitem> <para>You can write a <literal>forall</literal> (including overloading)
1750 in a type synonym, thus:
1751 <programlisting>
1752   type Discard a = forall b. Show b => a -> b -> (a, String)
1753
1754   f :: Discard a
1755   f x y = (x, show y)
1756
1757   g :: Discard Int -> (Int,String)    -- A rank-2 type
1758   g f = f 3 True
1759 </programlisting>
1760 </para>
1761 </listitem>
1762
1763 <listitem><para>
1764 If you also use <option>-XUnboxedTuples</option>, 
1765 you can write an unboxed tuple in a type synonym:
1766 <programlisting>
1767   type Pr = (# Int, Int #)
1768
1769   h :: Int -> Pr
1770   h x = (# x, x #)
1771 </programlisting>
1772 </para></listitem>
1773
1774 <listitem><para>
1775 You can apply a type synonym to a forall type:
1776 <programlisting>
1777   type Foo a = a -> a -> Bool
1778  
1779   f :: Foo (forall b. b->b)
1780 </programlisting>
1781 After expanding the synonym, <literal>f</literal> has the legal (in GHC) type:
1782 <programlisting>
1783   f :: (forall b. b->b) -> (forall b. b->b) -> Bool
1784 </programlisting>
1785 </para></listitem>
1786
1787 <listitem><para>
1788 You can apply a type synonym to a partially applied type synonym:
1789 <programlisting>
1790   type Generic i o = forall x. i x -> o x
1791   type Id x = x
1792   
1793   foo :: Generic Id []
1794 </programlisting>
1795 After expanding the synonym, <literal>foo</literal> has the legal (in GHC) type:
1796 <programlisting>
1797   foo :: forall x. x -> [x]
1798 </programlisting>
1799 </para></listitem>
1800
1801 </itemizedlist>
1802 </para>
1803
1804 <para>
1805 GHC currently does kind checking before expanding synonyms (though even that
1806 could be changed.)
1807 </para>
1808 <para>
1809 After expanding type synonyms, GHC does validity checking on types, looking for
1810 the following mal-formedness which isn't detected simply by kind checking:
1811 <itemizedlist>
1812 <listitem><para>
1813 Type constructor applied to a type involving for-alls.
1814 </para></listitem>
1815 <listitem><para>
1816 Unboxed tuple on left of an arrow.
1817 </para></listitem>
1818 <listitem><para>
1819 Partially-applied type synonym.
1820 </para></listitem>
1821 </itemizedlist>
1822 So, for example,
1823 this will be rejected:
1824 <programlisting>
1825   type Pr = (# Int, Int #)
1826
1827   h :: Pr -> Int
1828   h x = ...
1829 </programlisting>
1830 because GHC does not allow  unboxed tuples on the left of a function arrow.
1831 </para>
1832 </sect2>
1833
1834
1835 <sect2 id="existential-quantification">
1836 <title>Existentially quantified data constructors
1837 </title>
1838
1839 <para>
1840 The idea of using existential quantification in data type declarations
1841 was suggested by Perry, and implemented in Hope+ (Nigel Perry, <emphasis>The Implementation
1842 of Practical Functional Programming Languages</emphasis>, PhD Thesis, University of
1843 London, 1991). It was later formalised by Laufer and Odersky
1844 (<emphasis>Polymorphic type inference and abstract data types</emphasis>,
1845 TOPLAS, 16(5), pp1411-1430, 1994).
1846 It's been in Lennart
1847 Augustsson's <command>hbc</command> Haskell compiler for several years, and
1848 proved very useful.  Here's the idea.  Consider the declaration:
1849 </para>
1850
1851 <para>
1852
1853 <programlisting>
1854   data Foo = forall a. MkFoo a (a -> Bool)
1855            | Nil
1856 </programlisting>
1857
1858 </para>
1859
1860 <para>
1861 The data type <literal>Foo</literal> has two constructors with types:
1862 </para>
1863
1864 <para>
1865
1866 <programlisting>
1867   MkFoo :: forall a. a -> (a -> Bool) -> Foo
1868   Nil   :: Foo
1869 </programlisting>
1870
1871 </para>
1872
1873 <para>
1874 Notice that the type variable <literal>a</literal> in the type of <function>MkFoo</function>
1875 does not appear in the data type itself, which is plain <literal>Foo</literal>.
1876 For example, the following expression is fine:
1877 </para>
1878
1879 <para>
1880
1881 <programlisting>
1882   [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
1883 </programlisting>
1884
1885 </para>
1886
1887 <para>
1888 Here, <literal>(MkFoo 3 even)</literal> packages an integer with a function
1889 <function>even</function> that maps an integer to <literal>Bool</literal>; and <function>MkFoo 'c'
1890 isUpper</function> packages a character with a compatible function.  These
1891 two things are each of type <literal>Foo</literal> and can be put in a list.
1892 </para>
1893
1894 <para>
1895 What can we do with a value of type <literal>Foo</literal>?.  In particular,
1896 what happens when we pattern-match on <function>MkFoo</function>?
1897 </para>
1898
1899 <para>
1900
1901 <programlisting>
1902   f (MkFoo val fn) = ???
1903 </programlisting>
1904
1905 </para>
1906
1907 <para>
1908 Since all we know about <literal>val</literal> and <function>fn</function> is that they
1909 are compatible, the only (useful) thing we can do with them is to
1910 apply <function>fn</function> to <literal>val</literal> to get a boolean.  For example:
1911 </para>
1912
1913 <para>
1914
1915 <programlisting>
1916   f :: Foo -> Bool
1917   f (MkFoo val fn) = fn val
1918 </programlisting>
1919
1920 </para>
1921
1922 <para>
1923 What this allows us to do is to package heterogeneous values
1924 together with a bunch of functions that manipulate them, and then treat
1925 that collection of packages in a uniform manner.  You can express
1926 quite a bit of object-oriented-like programming this way.
1927 </para>
1928
1929 <sect3 id="existential">
1930 <title>Why existential?
1931 </title>
1932
1933 <para>
1934 What has this to do with <emphasis>existential</emphasis> quantification?
1935 Simply that <function>MkFoo</function> has the (nearly) isomorphic type
1936 </para>
1937
1938 <para>
1939
1940 <programlisting>
1941   MkFoo :: (exists a . (a, a -> Bool)) -> Foo
1942 </programlisting>
1943
1944 </para>
1945
1946 <para>
1947 But Haskell programmers can safely think of the ordinary
1948 <emphasis>universally</emphasis> quantified type given above, thereby avoiding
1949 adding a new existential quantification construct.
1950 </para>
1951
1952 </sect3>
1953
1954 <sect3 id="existential-with-context">
1955 <title>Existentials and type classes</title>
1956
1957 <para>
1958 An easy extension is to allow
1959 arbitrary contexts before the constructor.  For example:
1960 </para>
1961
1962 <para>
1963
1964 <programlisting>
1965 data Baz = forall a. Eq a => Baz1 a a
1966          | forall b. Show b => Baz2 b (b -> b)
1967 </programlisting>
1968
1969 </para>
1970
1971 <para>
1972 The two constructors have the types you'd expect:
1973 </para>
1974
1975 <para>
1976
1977 <programlisting>
1978 Baz1 :: forall a. Eq a => a -> a -> Baz
1979 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
1980 </programlisting>
1981
1982 </para>
1983
1984 <para>
1985 But when pattern matching on <function>Baz1</function> the matched values can be compared
1986 for equality, and when pattern matching on <function>Baz2</function> the first matched
1987 value can be converted to a string (as well as applying the function to it).
1988 So this program is legal:
1989 </para>
1990
1991 <para>
1992
1993 <programlisting>
1994   f :: Baz -> String
1995   f (Baz1 p q) | p == q    = "Yes"
1996                | otherwise = "No"
1997   f (Baz2 v fn)            = show (fn v)
1998 </programlisting>
1999
2000 </para>
2001
2002 <para>
2003 Operationally, in a dictionary-passing implementation, the
2004 constructors <function>Baz1</function> and <function>Baz2</function> must store the
2005 dictionaries for <literal>Eq</literal> and <literal>Show</literal> respectively, and
2006 extract it on pattern matching.
2007 </para>
2008
2009 </sect3>
2010
2011 <sect3 id="existential-records">
2012 <title>Record Constructors</title>
2013
2014 <para>
2015 GHC allows existentials to be used with records syntax as well.  For example:
2016
2017 <programlisting>
2018 data Counter a = forall self. NewCounter
2019     { _this    :: self
2020     , _inc     :: self -> self
2021     , _display :: self -> IO ()
2022     , tag      :: a
2023     }
2024 </programlisting>
2025 Here <literal>tag</literal> is a public field, with a well-typed selector
2026 function <literal>tag :: Counter a -> a</literal>.  The <literal>self</literal>
2027 type is hidden from the outside; any attempt to apply <literal>_this</literal>,
2028 <literal>_inc</literal> or <literal>_display</literal> as functions will raise a
2029 compile-time error.  In other words, <emphasis>GHC defines a record selector function
2030 only for fields whose type does not mention the existentially-quantified variables</emphasis>.
2031 (This example used an underscore in the fields for which record selectors
2032 will not be defined, but that is only programming style; GHC ignores them.)
2033 </para>
2034
2035 <para>
2036 To make use of these hidden fields, we need to create some helper functions:
2037
2038 <programlisting>
2039 inc :: Counter a -> Counter a
2040 inc (NewCounter x i d t) = NewCounter
2041     { _this = i x, _inc = i, _display = d, tag = t } 
2042
2043 display :: Counter a -> IO ()
2044 display NewCounter{ _this = x, _display = d } = d x
2045 </programlisting>
2046
2047 Now we can define counters with different underlying implementations:
2048
2049 <programlisting>
2050 counterA :: Counter String 
2051 counterA = NewCounter
2052     { _this = 0, _inc = (1+), _display = print, tag = "A" }
2053
2054 counterB :: Counter String 
2055 counterB = NewCounter
2056     { _this = "", _inc = ('#':), _display = putStrLn, tag = "B" }
2057
2058 main = do
2059     display (inc counterA)         -- prints "1"
2060     display (inc (inc counterB))   -- prints "##"
2061 </programlisting>
2062
2063 Record update syntax is supported for existentials (and GADTs):
2064 <programlisting>
2065 setTag :: Counter a -> a -> Counter a
2066 setTag obj t = obj{ tag = t }
2067 </programlisting>
2068 The rule for record update is this: <emphasis>
2069 the types of the updated fields may
2070 mention only the universally-quantified type variables
2071 of the data constructor.  For GADTs, the field may mention only types
2072 that appear as a simple type-variable argument in the constructor's result
2073 type</emphasis>.  For example:
2074 <programlisting>
2075 data T a b where { T1 { f1::a, f2::b, f3::(b,c) } :: T a b } -- c is existential
2076 upd1 t x = t { f1=x }   -- OK:   upd1 :: T a b -> a' -> T a' b
2077 upd2 t x = t { f3=x }   -- BAD   (f3's type mentions c, which is
2078                         --        existentially quantified)
2079
2080 data G a b where { G1 { g1::a, g2::c } :: G a [c] }
2081 upd3 g x = g { g1=x }   -- OK:   upd3 :: G a b -> c -> G c b
2082 upd4 g x = g { g2=x }   -- BAD (f2's type mentions c, which is not a simple
2083                         --      type-variable argument in G1's result type)
2084 </programlisting>
2085 </para>
2086
2087 </sect3>
2088
2089
2090 <sect3>
2091 <title>Restrictions</title>
2092
2093 <para>
2094 There are several restrictions on the ways in which existentially-quantified
2095 constructors can be use.
2096 </para>
2097
2098 <para>
2099
2100 <itemizedlist>
2101 <listitem>
2102
2103 <para>
2104  When pattern matching, each pattern match introduces a new,
2105 distinct, type for each existential type variable.  These types cannot
2106 be unified with any other type, nor can they escape from the scope of
2107 the pattern match.  For example, these fragments are incorrect:
2108
2109
2110 <programlisting>
2111 f1 (MkFoo a f) = a
2112 </programlisting>
2113
2114
2115 Here, the type bound by <function>MkFoo</function> "escapes", because <literal>a</literal>
2116 is the result of <function>f1</function>.  One way to see why this is wrong is to
2117 ask what type <function>f1</function> has:
2118
2119
2120 <programlisting>
2121   f1 :: Foo -> a             -- Weird!
2122 </programlisting>
2123
2124
2125 What is this "<literal>a</literal>" in the result type? Clearly we don't mean
2126 this:
2127
2128
2129 <programlisting>
2130   f1 :: forall a. Foo -> a   -- Wrong!
2131 </programlisting>
2132
2133
2134 The original program is just plain wrong.  Here's another sort of error
2135
2136
2137 <programlisting>
2138   f2 (Baz1 a b) (Baz1 p q) = a==q
2139 </programlisting>
2140
2141
2142 It's ok to say <literal>a==b</literal> or <literal>p==q</literal>, but
2143 <literal>a==q</literal> is wrong because it equates the two distinct types arising
2144 from the two <function>Baz1</function> constructors.
2145
2146
2147 </para>
2148 </listitem>
2149 <listitem>
2150
2151 <para>
2152 You can't pattern-match on an existentially quantified
2153 constructor in a <literal>let</literal> or <literal>where</literal> group of
2154 bindings. So this is illegal:
2155
2156
2157 <programlisting>
2158   f3 x = a==b where { Baz1 a b = x }
2159 </programlisting>
2160
2161 Instead, use a <literal>case</literal> expression:
2162
2163 <programlisting>
2164   f3 x = case x of Baz1 a b -> a==b
2165 </programlisting>
2166
2167 In general, you can only pattern-match
2168 on an existentially-quantified constructor in a <literal>case</literal> expression or
2169 in the patterns of a function definition.
2170
2171 The reason for this restriction is really an implementation one.
2172 Type-checking binding groups is already a nightmare without
2173 existentials complicating the picture.  Also an existential pattern
2174 binding at the top level of a module doesn't make sense, because it's
2175 not clear how to prevent the existentially-quantified type "escaping".
2176 So for now, there's a simple-to-state restriction.  We'll see how
2177 annoying it is.
2178
2179 </para>
2180 </listitem>
2181 <listitem>
2182
2183 <para>
2184 You can't use existential quantification for <literal>newtype</literal>
2185 declarations.  So this is illegal:
2186
2187
2188 <programlisting>
2189   newtype T = forall a. Ord a => MkT a
2190 </programlisting>
2191
2192
2193 Reason: a value of type <literal>T</literal> must be represented as a
2194 pair of a dictionary for <literal>Ord t</literal> and a value of type
2195 <literal>t</literal>.  That contradicts the idea that
2196 <literal>newtype</literal> should have no concrete representation.
2197 You can get just the same efficiency and effect by using
2198 <literal>data</literal> instead of <literal>newtype</literal>.  If
2199 there is no overloading involved, then there is more of a case for
2200 allowing an existentially-quantified <literal>newtype</literal>,
2201 because the <literal>data</literal> version does carry an
2202 implementation cost, but single-field existentially quantified
2203 constructors aren't much use.  So the simple restriction (no
2204 existential stuff on <literal>newtype</literal>) stands, unless there
2205 are convincing reasons to change it.
2206
2207
2208 </para>
2209 </listitem>
2210 <listitem>
2211
2212 <para>
2213  You can't use <literal>deriving</literal> to define instances of a
2214 data type with existentially quantified data constructors.
2215
2216 Reason: in most cases it would not make sense. For example:;
2217
2218 <programlisting>
2219 data T = forall a. MkT [a] deriving( Eq )
2220 </programlisting>
2221
2222 To derive <literal>Eq</literal> in the standard way we would need to have equality
2223 between the single component of two <function>MkT</function> constructors:
2224
2225 <programlisting>
2226 instance Eq T where
2227   (MkT a) == (MkT b) = ???
2228 </programlisting>
2229
2230 But <varname>a</varname> and <varname>b</varname> have distinct types, and so can't be compared.
2231 It's just about possible to imagine examples in which the derived instance
2232 would make sense, but it seems altogether simpler simply to prohibit such
2233 declarations.  Define your own instances!
2234 </para>
2235 </listitem>
2236
2237 </itemizedlist>
2238
2239 </para>
2240
2241 </sect3>
2242 </sect2>
2243
2244 <!-- ====================== Generalised algebraic data types =======================  -->
2245
2246 <sect2 id="gadt-style">
2247 <title>Declaring data types with explicit constructor signatures</title>
2248
2249 <para>GHC allows you to declare an algebraic data type by 
2250 giving the type signatures of constructors explicitly.  For example:
2251 <programlisting>
2252   data Maybe a where
2253       Nothing :: Maybe a
2254       Just    :: a -> Maybe a
2255 </programlisting>
2256 The form is called a "GADT-style declaration"
2257 because Generalised Algebraic Data Types, described in <xref linkend="gadt"/>, 
2258 can only be declared using this form.</para>
2259 <para>Notice that GADT-style syntax generalises existential types (<xref linkend="existential-quantification"/>).  
2260 For example, these two declarations are equivalent:
2261 <programlisting>
2262   data Foo = forall a. MkFoo a (a -> Bool)
2263   data Foo' where { MKFoo :: a -> (a->Bool) -> Foo' }
2264 </programlisting>
2265 </para>
2266 <para>Any data type that can be declared in standard Haskell-98 syntax 
2267 can also be declared using GADT-style syntax.
2268 The choice is largely stylistic, but GADT-style declarations differ in one important respect:
2269 they treat class constraints on the data constructors differently.
2270 Specifically, if the constructor is given a type-class context, that
2271 context is made available by pattern matching.  For example:
2272 <programlisting>
2273   data Set a where
2274     MkSet :: Eq a => [a] -> Set a
2275
2276   makeSet :: Eq a => [a] -> Set a
2277   makeSet xs = MkSet (nub xs)
2278
2279   insert :: a -> Set a -> Set a
2280   insert a (MkSet as) | a `elem` as = MkSet as
2281                       | otherwise   = MkSet (a:as)
2282 </programlisting>
2283 A use of <literal>MkSet</literal> as a constructor (e.g. in the definition of <literal>makeSet</literal>) 
2284 gives rise to a <literal>(Eq a)</literal>
2285 constraint, as you would expect.  The new feature is that pattern-matching on <literal>MkSet</literal>
2286 (as in the definition of <literal>insert</literal>) makes <emphasis>available</emphasis> an <literal>(Eq a)</literal>
2287 context.  In implementation terms, the <literal>MkSet</literal> constructor has a hidden field that stores
2288 the <literal>(Eq a)</literal> dictionary that is passed to <literal>MkSet</literal>; so
2289 when pattern-matching that dictionary becomes available for the right-hand side of the match.
2290 In the example, the equality dictionary is used to satisfy the equality constraint 
2291 generated by the call to <literal>elem</literal>, so that the type of
2292 <literal>insert</literal> itself has no <literal>Eq</literal> constraint.
2293 </para>
2294 <para>
2295 For example, one possible application is to reify dictionaries:
2296 <programlisting>
2297    data NumInst a where
2298      MkNumInst :: Num a => NumInst a
2299
2300    intInst :: NumInst Int
2301    intInst = MkNumInst
2302
2303    plus :: NumInst a -> a -> a -> a
2304    plus MkNumInst p q = p + q
2305 </programlisting>
2306 Here, a value of type <literal>NumInst a</literal> is equivalent 
2307 to an explicit <literal>(Num a)</literal> dictionary.
2308 </para>
2309 <para>
2310 All this applies to constructors declared using the syntax of <xref linkend="existential-with-context"/>.
2311 For example, the <literal>NumInst</literal> data type above could equivalently be declared 
2312 like this:
2313 <programlisting>
2314    data NumInst a 
2315       = Num a => MkNumInst (NumInst a)
2316 </programlisting>
2317 Notice that, unlike the situation when declaring an existential, there is 
2318 no <literal>forall</literal>, because the <literal>Num</literal> constrains the
2319 data type's universally quantified type variable <literal>a</literal>.  
2320 A constructor may have both universal and existential type variables: for example,
2321 the following two declarations are equivalent:
2322 <programlisting>
2323    data T1 a 
2324         = forall b. (Num a, Eq b) => MkT1 a b
2325    data T2 a where
2326         MkT2 :: (Num a, Eq b) => a -> b -> T2 a
2327 </programlisting>
2328 </para>
2329 <para>All this behaviour contrasts with Haskell 98's peculiar treatment of 
2330 contexts on a data type declaration (Section 4.2.1 of the Haskell 98 Report).
2331 In Haskell 98 the definition
2332 <programlisting>
2333   data Eq a => Set' a = MkSet' [a]
2334 </programlisting>
2335 gives <literal>MkSet'</literal> the same type as <literal>MkSet</literal> above.  But instead of 
2336 <emphasis>making available</emphasis> an <literal>(Eq a)</literal> constraint, pattern-matching
2337 on <literal>MkSet'</literal> <emphasis>requires</emphasis> an <literal>(Eq a)</literal> constraint!
2338 GHC faithfully implements this behaviour, odd though it is.  But for GADT-style declarations,
2339 GHC's behaviour is much more useful, as well as much more intuitive.
2340 </para>
2341
2342 <para>
2343 The rest of this section gives further details about GADT-style data
2344 type declarations.
2345
2346 <itemizedlist>
2347 <listitem><para>
2348 The result type of each data constructor must begin with the type constructor being defined.
2349 If the result type of all constructors 
2350 has the form <literal>T a1 ... an</literal>, where <literal>a1 ... an</literal>
2351 are distinct type variables, then the data type is <emphasis>ordinary</emphasis>;
2352 otherwise is a <emphasis>generalised</emphasis> data type (<xref linkend="gadt"/>).
2353 </para></listitem>
2354
2355 <listitem><para>
2356 As with other type signatures, you can give a single signature for several data constructors.
2357 In this example we give a single signature for <literal>T1</literal> and <literal>T2</literal>:
2358 <programlisting>
2359   data T a where
2360     T1,T2 :: a -> T a
2361     T3 :: T a
2362 </programlisting>
2363 </para></listitem>
2364
2365 <listitem><para>
2366 The type signature of
2367 each constructor is independent, and is implicitly universally quantified as usual. 
2368 Different constructors may have different universally-quantified type variables
2369 and different type-class constraints.  
2370 For example, this is fine:
2371 <programlisting>
2372   data T a where
2373     T1 :: Eq b => b -> T b
2374     T2 :: (Show c, Ix c) => c -> [c] -> T c
2375 </programlisting>
2376 </para></listitem>
2377
2378 <listitem><para>
2379 Unlike a Haskell-98-style 
2380 data type declaration, the type variable(s) in the "<literal>data Set a where</literal>" header 
2381 have no scope.  Indeed, one can write a kind signature instead:
2382 <programlisting>
2383   data Set :: * -> * where ...
2384 </programlisting>
2385 or even a mixture of the two:
2386 <programlisting>
2387   data Foo a :: (* -> *) -> * where ...
2388 </programlisting>
2389 The type variables (if given) may be explicitly kinded, so we could also write the header for <literal>Foo</literal>
2390 like this:
2391 <programlisting>
2392   data Foo a (b :: * -> *) where ...
2393 </programlisting>
2394 </para></listitem>
2395
2396
2397 <listitem><para>
2398 You can use strictness annotations, in the obvious places
2399 in the constructor type:
2400 <programlisting>
2401   data Term a where
2402       Lit    :: !Int -> Term Int
2403       If     :: Term Bool -> !(Term a) -> !(Term a) -> Term a
2404       Pair   :: Term a -> Term b -> Term (a,b)
2405 </programlisting>
2406 </para></listitem>
2407
2408 <listitem><para>
2409 You can use a <literal>deriving</literal> clause on a GADT-style data type
2410 declaration.   For example, these two declarations are equivalent
2411 <programlisting>
2412   data Maybe1 a where {
2413       Nothing1 :: Maybe1 a ;
2414       Just1    :: a -> Maybe1 a
2415     } deriving( Eq, Ord )
2416
2417   data Maybe2 a = Nothing2 | Just2 a 
2418        deriving( Eq, Ord )
2419 </programlisting>
2420 </para></listitem>
2421
2422 <listitem><para>
2423 You can use record syntax on a GADT-style data type declaration:
2424
2425 <programlisting>
2426   data Person where
2427       Adult { name :: String, children :: [Person] } :: Person
2428       Child { name :: String } :: Person
2429 </programlisting>
2430 As usual, for every constructor that has a field <literal>f</literal>, the type of
2431 field <literal>f</literal> must be the same (modulo alpha conversion).
2432 </para>
2433 <para>
2434 At the moment, record updates are not yet possible with GADT-style declarations, 
2435 so support is limited to record construction, selection and pattern matching.
2436 For example
2437 <programlisting>
2438   aPerson = Adult { name = "Fred", children = [] }
2439
2440   shortName :: Person -> Bool
2441   hasChildren (Adult { children = kids }) = not (null kids)
2442   hasChildren (Child {})                  = False
2443 </programlisting>
2444 </para></listitem>
2445
2446 <listitem><para> 
2447 As in the case of existentials declared using the Haskell-98-like record syntax 
2448 (<xref linkend="existential-records"/>),
2449 record-selector functions are generated only for those fields that have well-typed
2450 selectors.  
2451 Here is the example of that section, in GADT-style syntax:
2452 <programlisting>
2453 data Counter a where
2454     NewCounter { _this    :: self
2455                , _inc     :: self -> self
2456                , _display :: self -> IO ()
2457                , tag      :: a
2458                }
2459         :: Counter a
2460 </programlisting>
2461 As before, only one selector function is generated here, that for <literal>tag</literal>.
2462 Nevertheless, you can still use all the field names in pattern matching and record construction.
2463 </para></listitem>
2464 </itemizedlist></para>
2465 </sect2>
2466
2467 <sect2 id="gadt">
2468 <title>Generalised Algebraic Data Types (GADTs)</title>
2469
2470 <para>Generalised Algebraic Data Types generalise ordinary algebraic data types 
2471 by allowing constructors to have richer return types.  Here is an example:
2472 <programlisting>
2473   data Term a where
2474       Lit    :: Int -> Term Int
2475       Succ   :: Term Int -> Term Int
2476       IsZero :: Term Int -> Term Bool   
2477       If     :: Term Bool -> Term a -> Term a -> Term a
2478       Pair   :: Term a -> Term b -> Term (a,b)
2479 </programlisting>
2480 Notice that the return type of the constructors is not always <literal>Term a</literal>, as is the
2481 case with ordinary data types.  This generality allows us to 
2482 write a well-typed <literal>eval</literal> function
2483 for these <literal>Terms</literal>:
2484 <programlisting>
2485   eval :: Term a -> a
2486   eval (Lit i)      = i
2487   eval (Succ t)     = 1 + eval t
2488   eval (IsZero t)   = eval t == 0
2489   eval (If b e1 e2) = if eval b then eval e1 else eval e2
2490   eval (Pair e1 e2) = (eval e1, eval e2)
2491 </programlisting>
2492 The key point about GADTs is that <emphasis>pattern matching causes type refinement</emphasis>.  
2493 For example, in the right hand side of the equation
2494 <programlisting>
2495   eval :: Term a -> a
2496   eval (Lit i) =  ...
2497 </programlisting>
2498 the type <literal>a</literal> is refined to <literal>Int</literal>.  That's the whole point!
2499 A precise specification of the type rules is beyond what this user manual aspires to, 
2500 but the design closely follows that described in
2501 the paper <ulink
2502 url="http://research.microsoft.com/%7Esimonpj/papers/gadt/">Simple
2503 unification-based type inference for GADTs</ulink>,
2504 (ICFP 2006).
2505 The general principle is this: <emphasis>type refinement is only carried out 
2506 based on user-supplied type annotations</emphasis>.
2507 So if no type signature is supplied for <literal>eval</literal>, no type refinement happens, 
2508 and lots of obscure error messages will
2509 occur.  However, the refinement is quite general.  For example, if we had:
2510 <programlisting>
2511   eval :: Term a -> a -> a
2512   eval (Lit i) j =  i+j
2513 </programlisting>
2514 the pattern match causes the type <literal>a</literal> to be refined to <literal>Int</literal> (because of the type
2515 of the constructor <literal>Lit</literal>), and that refinement also applies to the type of <literal>j</literal>, and
2516 the result type of the <literal>case</literal> expression.  Hence the addition <literal>i+j</literal> is legal.
2517 </para>
2518 <para>
2519 These and many other examples are given in papers by Hongwei Xi, and
2520 Tim Sheard. There is a longer introduction
2521 <ulink url="http://www.haskell.org/haskellwiki/GADT">on the wiki</ulink>,
2522 and Ralf Hinze's
2523 <ulink url="http://www.informatik.uni-bonn.de/~ralf/publications/With.pdf">Fun with phantom types</ulink> also has a number of examples. Note that papers
2524 may use different notation to that implemented in GHC.
2525 </para>
2526 <para>
2527 The rest of this section outlines the extensions to GHC that support GADTs.   The extension is enabled with 
2528 <option>-XGADTs</option>.  The <option>-XGADTs</option> flag also sets <option>-XRelaxedPolyRec</option>.
2529 <itemizedlist>
2530 <listitem><para>
2531 A GADT can only be declared using GADT-style syntax (<xref linkend="gadt-style"/>); 
2532 the old Haskell-98 syntax for data declarations always declares an ordinary data type.
2533 The result type of each constructor must begin with the type constructor being defined,
2534 but for a GADT the arguments to the type constructor can be arbitrary monotypes.  
2535 For example, in the <literal>Term</literal> data
2536 type above, the type of each constructor must end with <literal>Term ty</literal>, but
2537 the <literal>ty</literal> need not be a type variable (e.g. the <literal>Lit</literal>
2538 constructor).
2539 </para></listitem>
2540
2541 <listitem><para>
2542 It's is permitted to declare an ordinary algebraic data type using GADT-style syntax.
2543 What makes a GADT into a GADT is not the syntax, but rather the presence of data constructors
2544 whose result type is not just <literal>T a b</literal>.
2545 </para></listitem>
2546
2547 <listitem><para>
2548 You cannot use a <literal>deriving</literal> clause for a GADT; only for
2549 an ordinary data type.
2550 </para></listitem>
2551
2552 <listitem><para>
2553 As mentioned in <xref linkend="gadt-style"/>, record syntax is supported.
2554 For example:
2555 <programlisting>
2556   data Term a where
2557       Lit    { val  :: Int }      :: Term Int
2558       Succ   { num  :: Term Int } :: Term Int
2559       Pred   { num  :: Term Int } :: Term Int
2560       IsZero { arg  :: Term Int } :: Term Bool  
2561       Pair   { arg1 :: Term a
2562              , arg2 :: Term b
2563              }                    :: Term (a,b)
2564       If     { cnd  :: Term Bool
2565              , tru  :: Term a
2566              , fls  :: Term a
2567              }                    :: Term a
2568 </programlisting>
2569 However, for GADTs there is the following additional constraint: 
2570 every constructor that has a field <literal>f</literal> must have
2571 the same result type (modulo alpha conversion)
2572 Hence, in the above example, we cannot merge the <literal>num</literal> 
2573 and <literal>arg</literal> fields above into a 
2574 single name.  Although their field types are both <literal>Term Int</literal>,
2575 their selector functions actually have different types:
2576
2577 <programlisting>
2578   num :: Term Int -> Term Int
2579   arg :: Term Bool -> Term Int
2580 </programlisting>
2581 </para></listitem>
2582
2583 <listitem><para>
2584 When pattern-matching against data constructors drawn from a GADT, 
2585 for example in a <literal>case</literal> expression, the following rules apply:
2586 <itemizedlist>
2587 <listitem><para>The type of the scrutinee must be rigid.</para></listitem>
2588 <listitem><para>The type of the entire <literal>case</literal> expression must be rigid.</para></listitem>
2589 <listitem><para>The type of any free variable mentioned in any of
2590 the <literal>case</literal> alternatives must be rigid.</para></listitem>
2591 </itemizedlist>
2592 A type is "rigid" if it is completely known to the compiler at its binding site.  The easiest
2593 way to ensure that a variable a rigid type is to give it a type signature.
2594 For more precise details see <ulink url="http://research.microsoft.com/%7Esimonpj/papers/gadt">
2595 Simple unification-based type inference for GADTs
2596 </ulink>. The criteria implemented by GHC are given in the Appendix.
2597
2598 </para></listitem>
2599
2600 </itemizedlist>
2601 </para>
2602
2603 </sect2>
2604 </sect1>
2605
2606 <!-- ====================== End of Generalised algebraic data types =======================  -->
2607
2608 <sect1 id="deriving">
2609 <title>Extensions to the "deriving" mechanism</title>
2610
2611 <sect2 id="deriving-inferred">
2612 <title>Inferred context for deriving clauses</title>
2613
2614 <para>
2615 The Haskell Report is vague about exactly when a <literal>deriving</literal> clause is
2616 legal.  For example:
2617 <programlisting>
2618   data T0 f a = MkT0 a         deriving( Eq )
2619   data T1 f a = MkT1 (f a)     deriving( Eq )
2620   data T2 f a = MkT2 (f (f a)) deriving( Eq )
2621 </programlisting>
2622 The natural generated <literal>Eq</literal> code would result in these instance declarations:
2623 <programlisting>
2624   instance Eq a         => Eq (T0 f a) where ...
2625   instance Eq (f a)     => Eq (T1 f a) where ...
2626   instance Eq (f (f a)) => Eq (T2 f a) where ...
2627 </programlisting>
2628 The first of these is obviously fine. The second is still fine, although less obviously. 
2629 The third is not Haskell 98, and risks losing termination of instances.
2630 </para>
2631 <para>
2632 GHC takes a conservative position: it accepts the first two, but not the third.  The  rule is this:
2633 each constraint in the inferred instance context must consist only of type variables, 
2634 with no repetitions.
2635 </para>
2636 <para>
2637 This rule is applied regardless of flags.  If you want a more exotic context, you can write
2638 it yourself, using the <link linkend="stand-alone-deriving">standalone deriving mechanism</link>.
2639 </para>
2640 </sect2>
2641
2642 <sect2 id="stand-alone-deriving">
2643 <title>Stand-alone deriving declarations</title>
2644
2645 <para>
2646 GHC now allows stand-alone <literal>deriving</literal> declarations, enabled by <literal>-XStandaloneDeriving</literal>:
2647 <programlisting>
2648   data Foo a = Bar a | Baz String
2649
2650   deriving instance Eq a => Eq (Foo a)
2651 </programlisting>
2652 The syntax is identical to that of an ordinary instance declaration apart from (a) the keyword
2653 <literal>deriving</literal>, and (b) the absence of the <literal>where</literal> part.
2654 You must supply a context (in the example the context is <literal>(Eq a)</literal>), 
2655 exactly as you would in an ordinary instance declaration.
2656 (In contrast the context is inferred in a <literal>deriving</literal> clause 
2657 attached to a data type declaration.) 
2658
2659 A <literal>deriving instance</literal> declaration
2660 must obey the same rules concerning form and termination as ordinary instance declarations,
2661 controlled by the same flags; see <xref linkend="instance-decls"/>.
2662 </para>
2663 <para>
2664 Unlike a <literal>deriving</literal>
2665 declaration attached to a <literal>data</literal> declaration, the instance can be more specific
2666 than the data type (assuming you also use 
2667 <literal>-XFlexibleInstances</literal>, <xref linkend="instance-rules"/>).  Consider
2668 for example
2669 <programlisting>
2670   data Foo a = Bar a | Baz String
2671
2672   deriving instance Eq a => Eq (Foo [a])
2673   deriving instance Eq a => Eq (Foo (Maybe a))
2674 </programlisting>
2675 This will generate a derived instance for <literal>(Foo [a])</literal> and <literal>(Foo (Maybe a))</literal>,
2676 but other types such as <literal>(Foo (Int,Bool))</literal> will not be an instance of <literal>Eq</literal>.
2677 </para>
2678
2679 <para>The stand-alone syntax is generalised for newtypes in exactly the same
2680 way that ordinary <literal>deriving</literal> clauses are generalised (<xref linkend="newtype-deriving"/>).
2681 For example:
2682 <programlisting>
2683   newtype Foo a = MkFoo (State Int a)
2684
2685   deriving instance MonadState Int Foo
2686 </programlisting>
2687 GHC always treats the <emphasis>last</emphasis> parameter of the instance
2688 (<literal>Foo</literal> in this example) as the type whose instance is being derived.
2689 </para>
2690
2691 </sect2>
2692
2693
2694 <sect2 id="deriving-typeable">
2695 <title>Deriving clause for extra classes (<literal>Typeable</literal>, <literal>Data</literal>, etc)</title>
2696
2697 <para>
2698 Haskell 98 allows the programmer to add "<literal>deriving( Eq, Ord )</literal>" to a data type 
2699 declaration, to generate a standard instance declaration for classes specified in the <literal>deriving</literal> clause.  
2700 In Haskell 98, the only classes that may appear in the <literal>deriving</literal> clause are the standard
2701 classes <literal>Eq</literal>, <literal>Ord</literal>, 
2702 <literal>Enum</literal>, <literal>Ix</literal>, <literal>Bounded</literal>, <literal>Read</literal>, and <literal>Show</literal>.
2703 </para>
2704 <para>
2705 GHC extends this list with several more classes that may be automatically derived:
2706 <itemizedlist>
2707 <listitem><para> With <option>-XDeriveDataTypeable</option>, you can derive instances of the classes
2708 <literal>Typeable</literal>, and <literal>Data</literal>, defined in the library
2709 modules <literal>Data.Typeable</literal> and <literal>Data.Generics</literal> respectively.
2710 </para>
2711 <para>An instance of <literal>Typeable</literal> can only be derived if the
2712 data type has seven or fewer type parameters, all of kind <literal>*</literal>.
2713 The reason for this is that the <literal>Typeable</literal> class is derived using the scheme
2714 described in
2715 <ulink url="http://research.microsoft.com/%7Esimonpj/papers/hmap/gmap2.ps">
2716 Scrap More Boilerplate: Reflection, Zips, and Generalised Casts
2717 </ulink>.
2718 (Section 7.4 of the paper describes the multiple <literal>Typeable</literal> classes that
2719 are used, and only <literal>Typeable1</literal> up to
2720 <literal>Typeable7</literal> are provided in the library.)
2721 In other cases, there is nothing to stop the programmer writing a <literal>TypableX</literal>
2722 class, whose kind suits that of the data type constructor, and
2723 then writing the data type instance by hand.
2724 </para>
2725 </listitem>
2726
2727 <listitem><para> With <option>-XDeriveFunctor</option>, you can derive instances of 
2728 the class <literal>Functor</literal>,
2729 defined in <literal>GHC.Base</literal>.
2730 </para></listitem>
2731
2732 <listitem><para> With <option>-XDeriveFoldable</option>, you can derive instances of 
2733 the class <literal>Foldable</literal>,
2734 defined in <literal>Data.Foldable</literal>.
2735 </para></listitem>
2736
2737 <listitem><para> With <option>-XDeriveTraversable</option>, you can derive instances of 
2738 the class <literal>Traversable</literal>,
2739 defined in <literal>Data.Traversable</literal>.
2740 </para></listitem>
2741 </itemizedlist>
2742 In each case the appropriate class must be in scope before it 
2743 can be mentioned in the <literal>deriving</literal> clause.
2744 </para>
2745 </sect2>
2746
2747 <sect2 id="newtype-deriving">
2748 <title>Generalised derived instances for newtypes</title>
2749
2750 <para>
2751 When you define an abstract type using <literal>newtype</literal>, you may want
2752 the new type to inherit some instances from its representation. In
2753 Haskell 98, you can inherit instances of <literal>Eq</literal>, <literal>Ord</literal>,
2754 <literal>Enum</literal> and <literal>Bounded</literal> by deriving them, but for any
2755 other classes you have to write an explicit instance declaration. For
2756 example, if you define
2757
2758 <programlisting>
2759   newtype Dollars = Dollars Int 
2760 </programlisting>
2761
2762 and you want to use arithmetic on <literal>Dollars</literal>, you have to
2763 explicitly define an instance of <literal>Num</literal>:
2764
2765 <programlisting>
2766   instance Num Dollars where
2767     Dollars a + Dollars b = Dollars (a+b)
2768     ...
2769 </programlisting>
2770 All the instance does is apply and remove the <literal>newtype</literal>
2771 constructor. It is particularly galling that, since the constructor
2772 doesn't appear at run-time, this instance declaration defines a
2773 dictionary which is <emphasis>wholly equivalent</emphasis> to the <literal>Int</literal>
2774 dictionary, only slower!
2775 </para>
2776
2777
2778 <sect3> <title> Generalising the deriving clause </title>
2779 <para>
2780 GHC now permits such instances to be derived instead, 
2781 using the flag <option>-XGeneralizedNewtypeDeriving</option>,
2782 so one can write 
2783 <programlisting>
2784   newtype Dollars = Dollars Int deriving (Eq,Show,Num)
2785 </programlisting>
2786
2787 and the implementation uses the <emphasis>same</emphasis> <literal>Num</literal> dictionary
2788 for <literal>Dollars</literal> as for <literal>Int</literal>. Notionally, the compiler
2789 derives an instance declaration of the form
2790
2791 <programlisting>
2792   instance Num Int => Num Dollars
2793 </programlisting>
2794
2795 which just adds or removes the <literal>newtype</literal> constructor according to the type.
2796 </para>
2797 <para>
2798
2799 We can also derive instances of constructor classes in a similar
2800 way. For example, suppose we have implemented state and failure monad
2801 transformers, such that
2802
2803 <programlisting>
2804   instance Monad m => Monad (State s m) 
2805   instance Monad m => Monad (Failure m)
2806 </programlisting>
2807 In Haskell 98, we can define a parsing monad by 
2808 <programlisting>
2809   type Parser tok m a = State [tok] (Failure m) a
2810 </programlisting>
2811
2812 which is automatically a monad thanks to the instance declarations
2813 above. With the extension, we can make the parser type abstract,
2814 without needing to write an instance of class <literal>Monad</literal>, via
2815
2816 <programlisting>
2817   newtype Parser tok m a = Parser (State [tok] (Failure m) a)
2818                          deriving Monad
2819 </programlisting>
2820 In this case the derived instance declaration is of the form 
2821 <programlisting>
2822   instance Monad (State [tok] (Failure m)) => Monad (Parser tok m) 
2823 </programlisting>
2824
2825 Notice that, since <literal>Monad</literal> is a constructor class, the
2826 instance is a <emphasis>partial application</emphasis> of the new type, not the
2827 entire left hand side. We can imagine that the type declaration is
2828 "eta-converted" to generate the context of the instance
2829 declaration.
2830 </para>
2831 <para>
2832
2833 We can even derive instances of multi-parameter classes, provided the
2834 newtype is the last class parameter. In this case, a ``partial
2835 application'' of the class appears in the <literal>deriving</literal>
2836 clause. For example, given the class
2837
2838 <programlisting>
2839   class StateMonad s m | m -> s where ... 
2840   instance Monad m => StateMonad s (State s m) where ... 
2841 </programlisting>
2842 then we can derive an instance of <literal>StateMonad</literal> for <literal>Parser</literal>s by 
2843 <programlisting>
2844   newtype Parser tok m a = Parser (State [tok] (Failure m) a)
2845                          deriving (Monad, StateMonad [tok])
2846 </programlisting>
2847
2848 The derived instance is obtained by completing the application of the
2849 class to the new type:
2850
2851 <programlisting>
2852   instance StateMonad [tok] (State [tok] (Failure m)) =>
2853            StateMonad [tok] (Parser tok m)
2854 </programlisting>
2855 </para>
2856 <para>
2857
2858 As a result of this extension, all derived instances in newtype
2859  declarations are treated uniformly (and implemented just by reusing
2860 the dictionary for the representation type), <emphasis>except</emphasis>
2861 <literal>Show</literal> and <literal>Read</literal>, which really behave differently for
2862 the newtype and its representation.
2863 </para>
2864 </sect3>
2865
2866 <sect3> <title> A more precise specification </title>
2867 <para>
2868 Derived instance declarations are constructed as follows. Consider the
2869 declaration (after expansion of any type synonyms)
2870
2871 <programlisting>
2872   newtype T v1...vn = T' (t vk+1...vn) deriving (c1...cm) 
2873 </programlisting>
2874
2875 where 
2876  <itemizedlist>
2877 <listitem><para>
2878   The <literal>ci</literal> are partial applications of
2879   classes of the form <literal>C t1'...tj'</literal>, where the arity of <literal>C</literal>
2880   is exactly <literal>j+1</literal>.  That is, <literal>C</literal> lacks exactly one type argument.
2881 </para></listitem>
2882 <listitem><para>
2883   The <literal>k</literal> is chosen so that <literal>ci (T v1...vk)</literal> is well-kinded.
2884 </para></listitem>
2885 <listitem><para>
2886   The type <literal>t</literal> is an arbitrary type.
2887 </para></listitem>
2888 <listitem><para>
2889   The type variables <literal>vk+1...vn</literal> do not occur in <literal>t</literal>, 
2890   nor in the <literal>ci</literal>, and
2891 </para></listitem>
2892 <listitem><para>
2893   None of the <literal>ci</literal> is <literal>Read</literal>, <literal>Show</literal>, 
2894                 <literal>Typeable</literal>, or <literal>Data</literal>.  These classes
2895                 should not "look through" the type or its constructor.  You can still
2896                 derive these classes for a newtype, but it happens in the usual way, not 
2897                 via this new mechanism.  
2898 </para></listitem>
2899 </itemizedlist>
2900 Then, for each <literal>ci</literal>, the derived instance
2901 declaration is:
2902 <programlisting>
2903   instance ci t => ci (T v1...vk)
2904 </programlisting>
2905 As an example which does <emphasis>not</emphasis> work, consider 
2906 <programlisting>
2907   newtype NonMonad m s = NonMonad (State s m s) deriving Monad 
2908 </programlisting>
2909 Here we cannot derive the instance 
2910 <programlisting>
2911   instance Monad (State s m) => Monad (NonMonad m) 
2912 </programlisting>
2913
2914 because the type variable <literal>s</literal> occurs in <literal>State s m</literal>,
2915 and so cannot be "eta-converted" away. It is a good thing that this
2916 <literal>deriving</literal> clause is rejected, because <literal>NonMonad m</literal> is
2917 not, in fact, a monad --- for the same reason. Try defining
2918 <literal>>>=</literal> with the correct type: you won't be able to.
2919 </para>
2920 <para>
2921
2922 Notice also that the <emphasis>order</emphasis> of class parameters becomes
2923 important, since we can only derive instances for the last one. If the
2924 <literal>StateMonad</literal> class above were instead defined as
2925
2926 <programlisting>
2927   class StateMonad m s | m -> s where ... 
2928 </programlisting>
2929
2930 then we would not have been able to derive an instance for the
2931 <literal>Parser</literal> type above. We hypothesise that multi-parameter
2932 classes usually have one "main" parameter for which deriving new
2933 instances is most interesting.
2934 </para>
2935 <para>Lastly, all of this applies only for classes other than
2936 <literal>Read</literal>, <literal>Show</literal>, <literal>Typeable</literal>, 
2937 and <literal>Data</literal>, for which the built-in derivation applies (section
2938 4.3.3. of the Haskell Report).
2939 (For the standard classes <literal>Eq</literal>, <literal>Ord</literal>,
2940 <literal>Ix</literal>, and <literal>Bounded</literal> it is immaterial whether
2941 the standard method is used or the one described here.)
2942 </para>
2943 </sect3>
2944 </sect2>
2945 </sect1>
2946
2947
2948 <!-- TYPE SYSTEM EXTENSIONS -->
2949 <sect1 id="type-class-extensions">
2950 <title>Class and instances declarations</title>
2951
2952 <sect2 id="multi-param-type-classes">
2953 <title>Class declarations</title>
2954
2955 <para>
2956 This section, and the next one, documents GHC's type-class extensions.
2957 There's lots of background in the paper <ulink
2958 url="http://research.microsoft.com/~simonpj/Papers/type-class-design-space/">Type
2959 classes: exploring the design space</ulink> (Simon Peyton Jones, Mark
2960 Jones, Erik Meijer).
2961 </para>
2962 <para>
2963 All the extensions are enabled by the <option>-fglasgow-exts</option> flag.
2964 </para>
2965
2966 <sect3>
2967 <title>Multi-parameter type classes</title>
2968 <para>
2969 Multi-parameter type classes are permitted. For example:
2970
2971
2972 <programlisting>
2973   class Collection c a where
2974     union :: c a -> c a -> c a
2975     ...etc.
2976 </programlisting>
2977
2978 </para>
2979 </sect3>
2980
2981 <sect3>
2982 <title>The superclasses of a class declaration</title>
2983
2984 <para>
2985 There are no restrictions on the context in a class declaration
2986 (which introduces superclasses), except that the class hierarchy must
2987 be acyclic.  So these class declarations are OK:
2988
2989
2990 <programlisting>
2991   class Functor (m k) => FiniteMap m k where
2992     ...
2993
2994   class (Monad m, Monad (t m)) => Transform t m where
2995     lift :: m a -> (t m) a
2996 </programlisting>
2997
2998
2999 </para>
3000 <para>
3001 As in Haskell 98, The class hierarchy must be acyclic.  However, the definition
3002 of "acyclic" involves only the superclass relationships.  For example,
3003 this is OK:
3004
3005
3006 <programlisting>
3007   class C a where {
3008     op :: D b => a -> b -> b
3009   }
3010
3011   class C a => D a where { ... }
3012 </programlisting>
3013
3014
3015 Here, <literal>C</literal> is a superclass of <literal>D</literal>, but it's OK for a
3016 class operation <literal>op</literal> of <literal>C</literal> to mention <literal>D</literal>.  (It
3017 would not be OK for <literal>D</literal> to be a superclass of <literal>C</literal>.)
3018 </para>
3019 </sect3>
3020
3021
3022
3023
3024 <sect3 id="class-method-types">
3025 <title>Class method types</title>
3026
3027 <para>
3028 Haskell 98 prohibits class method types to mention constraints on the
3029 class type variable, thus:
3030 <programlisting>
3031   class Seq s a where
3032     fromList :: [a] -> s a
3033     elem     :: Eq a => a -> s a -> Bool
3034 </programlisting>
3035 The type of <literal>elem</literal> is illegal in Haskell 98, because it
3036 contains the constraint <literal>Eq a</literal>, constrains only the 
3037 class type variable (in this case <literal>a</literal>).
3038 GHC lifts this restriction (flag <option>-XConstrainedClassMethods</option>).
3039 </para>
3040
3041
3042 </sect3>
3043 </sect2>
3044
3045 <sect2 id="functional-dependencies">
3046 <title>Functional dependencies
3047 </title>
3048
3049 <para> Functional dependencies are implemented as described by Mark Jones
3050 in &ldquo;<ulink url="http://citeseer.ist.psu.edu/jones00type.html">Type Classes with Functional Dependencies</ulink>&rdquo;, Mark P. Jones, 
3051 In Proceedings of the 9th European Symposium on Programming, 
3052 ESOP 2000, Berlin, Germany, March 2000, Springer-Verlag LNCS 1782,
3053 .
3054 </para>
3055 <para>
3056 Functional dependencies are introduced by a vertical bar in the syntax of a 
3057 class declaration;  e.g. 
3058 <programlisting>
3059   class (Monad m) => MonadState s m | m -> s where ...
3060
3061   class Foo a b c | a b -> c where ...
3062 </programlisting>
3063 There should be more documentation, but there isn't (yet).  Yell if you need it.
3064 </para>
3065
3066 <sect3><title>Rules for functional dependencies </title>
3067 <para>
3068 In a class declaration, all of the class type variables must be reachable (in the sense 
3069 mentioned in <xref linkend="type-restrictions"/>)
3070 from the free variables of each method type.
3071 For example:
3072
3073 <programlisting>
3074   class Coll s a where
3075     empty  :: s
3076     insert :: s -> a -> s
3077 </programlisting>
3078
3079 is not OK, because the type of <literal>empty</literal> doesn't mention
3080 <literal>a</literal>.  Functional dependencies can make the type variable
3081 reachable:
3082 <programlisting>
3083   class Coll s a | s -> a where
3084     empty  :: s
3085     insert :: s -> a -> s
3086 </programlisting>
3087
3088 Alternatively <literal>Coll</literal> might be rewritten
3089
3090 <programlisting>
3091   class Coll s a where
3092     empty  :: s a
3093     insert :: s a -> a -> s a
3094 </programlisting>
3095
3096
3097 which makes the connection between the type of a collection of
3098 <literal>a</literal>'s (namely <literal>(s a)</literal>) and the element type <literal>a</literal>.
3099 Occasionally this really doesn't work, in which case you can split the
3100 class like this:
3101
3102
3103 <programlisting>
3104   class CollE s where
3105     empty  :: s
3106
3107   class CollE s => Coll s a where
3108     insert :: s -> a -> s
3109 </programlisting>
3110 </para>
3111 </sect3>
3112
3113
3114 <sect3>
3115 <title>Background on functional dependencies</title>
3116
3117 <para>The following description of the motivation and use of functional dependencies is taken
3118 from the Hugs user manual, reproduced here (with minor changes) by kind
3119 permission of Mark Jones.
3120 </para>
3121 <para> 
3122 Consider the following class, intended as part of a
3123 library for collection types:
3124 <programlisting>
3125    class Collects e ce where
3126        empty  :: ce
3127        insert :: e -> ce -> ce
3128        member :: e -> ce -> Bool
3129 </programlisting>
3130 The type variable e used here represents the element type, while ce is the type
3131 of the container itself. Within this framework, we might want to define
3132 instances of this class for lists or characteristic functions (both of which
3133 can be used to represent collections of any equality type), bit sets (which can
3134 be used to represent collections of characters), or hash tables (which can be
3135 used to represent any collection whose elements have a hash function). Omitting
3136 standard implementation details, this would lead to the following declarations: 
3137 <programlisting>
3138    instance Eq e => Collects e [e] where ...
3139    instance Eq e => Collects e (e -> Bool) where ...
3140    instance Collects Char BitSet where ...
3141    instance (Hashable e, Collects a ce)
3142               => Collects e (Array Int ce) where ...
3143 </programlisting>
3144 All this looks quite promising; we have a class and a range of interesting
3145 implementations. Unfortunately, there are some serious problems with the class
3146 declaration. First, the empty function has an ambiguous type: 
3147 <programlisting>
3148    empty :: Collects e ce => ce
3149 </programlisting>
3150 By "ambiguous" we mean that there is a type variable e that appears on the left
3151 of the <literal>=&gt;</literal> symbol, but not on the right. The problem with
3152 this is that, according to the theoretical foundations of Haskell overloading,
3153 we cannot guarantee a well-defined semantics for any term with an ambiguous
3154 type.
3155 </para>
3156 <para>
3157 We can sidestep this specific problem by removing the empty member from the
3158 class declaration. However, although the remaining members, insert and member,
3159 do not have ambiguous types, we still run into problems when we try to use
3160 them. For example, consider the following two functions: 
3161 <programlisting>
3162    f x y = insert x . insert y
3163    g     = f True 'a'
3164 </programlisting>
3165 for which GHC infers the following types: 
3166 <programlisting>
3167    f :: (Collects a c, Collects b c) => a -> b -> c -> c
3168    g :: (Collects Bool c, Collects Char c) => c -> c
3169 </programlisting>
3170 Notice that the type for f allows the two parameters x and y to be assigned
3171 different types, even though it attempts to insert each of the two values, one
3172 after the other, into the same collection. If we're trying to model collections
3173 that contain only one type of value, then this is clearly an inaccurate
3174 type. Worse still, the definition for g is accepted, without causing a type
3175 error. As a result, the error in this code will not be flagged at the point
3176 where it appears. Instead, it will show up only when we try to use g, which
3177 might even be in a different module.
3178 </para>
3179
3180 <sect4><title>An attempt to use constructor classes</title>
3181
3182 <para>
3183 Faced with the problems described above, some Haskell programmers might be
3184 tempted to use something like the following version of the class declaration: 
3185 <programlisting>
3186    class Collects e c where
3187       empty  :: c e
3188       insert :: e -> c e -> c e
3189       member :: e -> c e -> Bool
3190 </programlisting>
3191 The key difference here is that we abstract over the type constructor c that is
3192 used to form the collection type c e, and not over that collection type itself,
3193 represented by ce in the original class declaration. This avoids the immediate
3194 problems that we mentioned above: empty has type <literal>Collects e c => c
3195 e</literal>, which is not ambiguous. 
3196 </para>
3197 <para>
3198 The function f from the previous section has a more accurate type: 
3199 <programlisting>
3200    f :: (Collects e c) => e -> e -> c e -> c e
3201 </programlisting>
3202 The function g from the previous section is now rejected with a type error as
3203 we would hope because the type of f does not allow the two arguments to have
3204 different types. 
3205 This, then, is an example of a multiple parameter class that does actually work
3206 quite well in practice, without ambiguity problems.
3207 There is, however, a catch. This version of the Collects class is nowhere near
3208 as general as the original class seemed to be: only one of the four instances
3209 for <literal>Collects</literal>
3210 given above can be used with this version of Collects because only one of
3211 them---the instance for lists---has a collection type that can be written in
3212 the form c e, for some type constructor c, and element type e.
3213 </para>
3214 </sect4>
3215
3216 <sect4><title>Adding functional dependencies</title>
3217
3218 <para>
3219 To get a more useful version of the Collects class, Hugs provides a mechanism
3220 that allows programmers to specify dependencies between the parameters of a
3221 multiple parameter class (For readers with an interest in theoretical
3222 foundations and previous work: The use of dependency information can be seen
3223 both as a generalization of the proposal for `parametric type classes' that was
3224 put forward by Chen, Hudak, and Odersky, or as a special case of Mark Jones's
3225 later framework for "improvement" of qualified types. The
3226 underlying ideas are also discussed in a more theoretical and abstract setting
3227 in a manuscript [implparam], where they are identified as one point in a
3228 general design space for systems of implicit parameterization.).
3229
3230 To start with an abstract example, consider a declaration such as: 
3231 <programlisting>
3232    class C a b where ...
3233 </programlisting>
3234 which tells us simply that C can be thought of as a binary relation on types
3235 (or type constructors, depending on the kinds of a and b). Extra clauses can be
3236 included in the definition of classes to add information about dependencies
3237 between parameters, as in the following examples: 
3238 <programlisting>
3239    class D a b | a -> b where ...
3240    class E a b | a -> b, b -> a where ...
3241 </programlisting>
3242 The notation <literal>a -&gt; b</literal> used here between the | and where
3243 symbols --- not to be
3244 confused with a function type --- indicates that the a parameter uniquely
3245 determines the b parameter, and might be read as "a determines b." Thus D is
3246 not just a relation, but actually a (partial) function. Similarly, from the two
3247 dependencies that are included in the definition of E, we can see that E
3248 represents a (partial) one-one mapping between types.
3249 </para>
3250 <para>
3251 More generally, dependencies take the form <literal>x1 ... xn -&gt; y1 ... ym</literal>,
3252 where x1, ..., xn, and y1, ..., yn are type variables with n&gt;0 and
3253 m&gt;=0, meaning that the y parameters are uniquely determined by the x
3254 parameters. Spaces can be used as separators if more than one variable appears
3255 on any single side of a dependency, as in <literal>t -&gt; a b</literal>. Note that a class may be
3256 annotated with multiple dependencies using commas as separators, as in the
3257 definition of E above. Some dependencies that we can write in this notation are
3258 redundant, and will be rejected because they don't serve any useful
3259 purpose, and may instead indicate an error in the program. Examples of
3260 dependencies like this include  <literal>a -&gt; a </literal>,  
3261 <literal>a -&gt; a a </literal>,  
3262 <literal>a -&gt; </literal>, etc. There can also be
3263 some redundancy if multiple dependencies are given, as in  
3264 <literal>a-&gt;b</literal>, 
3265  <literal>b-&gt;c </literal>,  <literal>a-&gt;c </literal>, and
3266 in which some subset implies the remaining dependencies. Examples like this are
3267 not treated as errors. Note that dependencies appear only in class
3268 declarations, and not in any other part of the language. In particular, the
3269 syntax for instance declarations, class constraints, and types is completely
3270 unchanged.
3271 </para>
3272 <para>
3273 By including dependencies in a class declaration, we provide a mechanism for
3274 the programmer to specify each multiple parameter class more precisely. The
3275 compiler, on the other hand, is responsible for ensuring that the set of
3276 instances that are in scope at any given point in the program is consistent
3277 with any declared dependencies. For example, the following pair of instance
3278 declarations cannot appear together in the same scope because they violate the
3279 dependency for D, even though either one on its own would be acceptable: 
3280 <programlisting>
3281    instance D Bool Int where ...
3282    instance D Bool Char where ...
3283 </programlisting>
3284 Note also that the following declaration is not allowed, even by itself: 
3285 <programlisting>
3286    instance D [a] b where ...
3287 </programlisting>
3288 The problem here is that this instance would allow one particular choice of [a]
3289 to be associated with more than one choice for b, which contradicts the
3290 dependency specified in the definition of D. More generally, this means that,
3291 in any instance of the form: 
3292 <programlisting>
3293    instance D t s where ...
3294 </programlisting>
3295 for some particular types t and s, the only variables that can appear in s are
3296 the ones that appear in t, and hence, if the type t is known, then s will be
3297 uniquely determined.
3298 </para>
3299 <para>
3300 The benefit of including dependency information is that it allows us to define
3301 more general multiple parameter classes, without ambiguity problems, and with
3302 the benefit of more accurate types. To illustrate this, we return to the
3303 collection class example, and annotate the original definition of <literal>Collects</literal>
3304 with a simple dependency: 
3305 <programlisting>
3306    class Collects e ce | ce -> e where
3307       empty  :: ce
3308       insert :: e -> ce -> ce
3309       member :: e -> ce -> Bool
3310 </programlisting>
3311 The dependency <literal>ce -&gt; e</literal> here specifies that the type e of elements is uniquely
3312 determined by the type of the collection ce. Note that both parameters of
3313 Collects are of kind *; there are no constructor classes here. Note too that
3314 all of the instances of Collects that we gave earlier can be used
3315 together with this new definition.
3316 </para>
3317 <para>
3318 What about the ambiguity problems that we encountered with the original
3319 definition? The empty function still has type Collects e ce => ce, but it is no
3320 longer necessary to regard that as an ambiguous type: Although the variable e
3321 does not appear on the right of the => symbol, the dependency for class
3322 Collects tells us that it is uniquely determined by ce, which does appear on
3323 the right of the => symbol. Hence the context in which empty is used can still
3324 give enough information to determine types for both ce and e, without
3325 ambiguity. More generally, we need only regard a type as ambiguous if it
3326 contains a variable on the left of the => that is not uniquely determined
3327 (either directly or indirectly) by the variables on the right.
3328 </para>
3329 <para>
3330 Dependencies also help to produce more accurate types for user defined
3331 functions, and hence to provide earlier detection of errors, and less cluttered
3332 types for programmers to work with. Recall the previous definition for a
3333 function f: 
3334 <programlisting>
3335    f x y = insert x y = insert x . insert y
3336 </programlisting>
3337 for which we originally obtained a type: 
3338 <programlisting>
3339    f :: (Collects a c, Collects b c) => a -> b -> c -> c
3340 </programlisting>
3341 Given the dependency information that we have for Collects, however, we can
3342 deduce that a and b must be equal because they both appear as the second
3343 parameter in a Collects constraint with the same first parameter c. Hence we
3344 can infer a shorter and more accurate type for f: 
3345 <programlisting>
3346    f :: (Collects a c) => a -> a -> c -> c
3347 </programlisting>
3348 In a similar way, the earlier definition of g will now be flagged as a type error.
3349 </para>
3350 <para>
3351 Although we have given only a few examples here, it should be clear that the
3352 addition of dependency information can help to make multiple parameter classes
3353 more useful in practice, avoiding ambiguity problems, and allowing more general
3354 sets of instance declarations.
3355 </para>
3356 </sect4>
3357 </sect3>
3358 </sect2>
3359
3360 <sect2 id="instance-decls">
3361 <title>Instance declarations</title>
3362
3363 <para>An instance declaration has the form
3364 <screen>
3365   instance ( <replaceable>assertion</replaceable><subscript>1</subscript>, ..., <replaceable>assertion</replaceable><subscript>n</subscript>) =&gt; <replaceable>class</replaceable> <replaceable>type</replaceable><subscript>1</subscript> ... <replaceable>type</replaceable><subscript>m</subscript> where ...
3366 </screen>
3367 The part before the "<literal>=&gt;</literal>" is the
3368 <emphasis>context</emphasis>, while the part after the
3369 "<literal>=&gt;</literal>" is the <emphasis>head</emphasis> of the instance declaration.
3370 </para>
3371
3372 <sect3 id="flexible-instance-head">
3373 <title>Relaxed rules for the instance head</title>
3374
3375 <para>
3376 In Haskell 98 the head of an instance declaration
3377 must be of the form <literal>C (T a1 ... an)</literal>, where
3378 <literal>C</literal> is the class, <literal>T</literal> is a data type constructor,
3379 and the <literal>a1 ... an</literal> are distinct type variables.
3380 GHC relaxes these rules in two ways.
3381 <itemizedlist>
3382 <listitem>
3383 <para>
3384 The <option>-XFlexibleInstances</option> flag allows the head of the instance
3385 declaration to mention arbitrary nested types.
3386 For example, this becomes a legal instance declaration
3387 <programlisting>
3388   instance C (Maybe Int) where ...
3389 </programlisting>
3390 See also the <link linkend="instance-overlap">rules on overlap</link>.
3391 </para></listitem>
3392 <listitem><para>
3393 With the <option>-XTypeSynonymInstances</option> flag, instance heads may use type
3394 synonyms. As always, using a type synonym is just shorthand for
3395 writing the RHS of the type synonym definition.  For example:
3396
3397
3398 <programlisting>
3399   type Point = (Int,Int)
3400   instance C Point   where ...
3401   instance C [Point] where ...
3402 </programlisting>
3403
3404
3405 is legal.  However, if you added
3406
3407
3408 <programlisting>
3409   instance C (Int,Int) where ...
3410 </programlisting>
3411
3412
3413 as well, then the compiler will complain about the overlapping
3414 (actually, identical) instance declarations.  As always, type synonyms
3415 must be fully applied.  You cannot, for example, write:
3416
3417 <programlisting>
3418   type P a = [[a]]
3419   instance Monad P where ...
3420 </programlisting>
3421
3422 </para></listitem>
3423 </itemizedlist>
3424 </para>
3425 </sect3>
3426
3427 <sect3 id="instance-rules">
3428 <title>Relaxed rules for instance contexts</title>
3429
3430 <para>In Haskell 98, the assertions in the context of the instance declaration
3431 must be of the form <literal>C a</literal> where <literal>a</literal>
3432 is a type variable that occurs in the head.
3433 </para>
3434
3435 <para>
3436 The <option>-XFlexibleContexts</option> flag relaxes this rule, as well
3437 as the corresponding rule for type signatures (see <xref linkend="flexible-contexts"/>).
3438 With this flag the context of the instance declaration can each consist of arbitrary
3439 (well-kinded) assertions <literal>(C t1 ... tn)</literal> subject only to the
3440 following rules:
3441 <orderedlist>
3442 <listitem><para>
3443 The Paterson Conditions: for each assertion in the context
3444 <orderedlist>
3445 <listitem><para>No type variable has more occurrences in the assertion than in the head</para></listitem>
3446 <listitem><para>The assertion has fewer constructors and variables (taken together
3447       and counting repetitions) than the head</para></listitem>
3448 </orderedlist>
3449 </para></listitem>
3450
3451 <listitem><para>The Coverage Condition.  For each functional dependency,
3452 <replaceable>tvs</replaceable><subscript>left</subscript> <literal>-&gt;</literal>
3453 <replaceable>tvs</replaceable><subscript>right</subscript>,  of the class,
3454 every type variable in
3455 S(<replaceable>tvs</replaceable><subscript>right</subscript>) must appear in 
3456 S(<replaceable>tvs</replaceable><subscript>left</subscript>), where S is the
3457 substitution mapping each type variable in the class declaration to the
3458 corresponding type in the instance declaration.
3459 </para></listitem>
3460 </orderedlist>
3461 These restrictions ensure that context reduction terminates: each reduction
3462 step makes the problem smaller by at least one
3463 constructor.  Both the Paterson Conditions and the Coverage Condition are lifted 
3464 if you give the <option>-XUndecidableInstances</option> 
3465 flag (<xref linkend="undecidable-instances"/>).
3466 You can find lots of background material about the reason for these
3467 restrictions in the paper <ulink
3468 url="http://research.microsoft.com/%7Esimonpj/papers/fd%2Dchr/">
3469 Understanding functional dependencies via Constraint Handling Rules</ulink>.
3470 </para>
3471 <para>
3472 For example, these are OK:
3473 <programlisting>
3474   instance C Int [a]          -- Multiple parameters
3475   instance Eq (S [a])         -- Structured type in head
3476
3477       -- Repeated type variable in head
3478   instance C4 a a => C4 [a] [a] 
3479   instance Stateful (ST s) (MutVar s)
3480
3481       -- Head can consist of type variables only
3482   instance C a
3483   instance (Eq a, Show b) => C2 a b
3484
3485       -- Non-type variables in context
3486   instance Show (s a) => Show (Sized s a)
3487   instance C2 Int a => C3 Bool [a]
3488   instance C2 Int a => C3 [a] b
3489 </programlisting>
3490 But these are not:
3491 <programlisting>
3492       -- Context assertion no smaller than head
3493   instance C a => C a where ...
3494       -- (C b b) has more more occurrences of b than the head
3495   instance C b b => Foo [b] where ...
3496 </programlisting>
3497 </para>
3498
3499 <para>
3500 The same restrictions apply to instances generated by
3501 <literal>deriving</literal> clauses.  Thus the following is accepted:
3502 <programlisting>
3503   data MinHeap h a = H a (h a)
3504     deriving (Show)
3505 </programlisting>
3506 because the derived instance
3507 <programlisting>
3508   instance (Show a, Show (h a)) => Show (MinHeap h a)
3509 </programlisting>
3510 conforms to the above rules.
3511 </para>
3512
3513 <para>
3514 A useful idiom permitted by the above rules is as follows.
3515 If one allows overlapping instance declarations then it's quite
3516 convenient to have a "default instance" declaration that applies if
3517 something more specific does not:
3518 <programlisting>
3519   instance C a where
3520     op = ... -- Default
3521 </programlisting>
3522 </para>
3523 </sect3>
3524
3525 <sect3 id="undecidable-instances">
3526 <title>Undecidable instances</title>
3527
3528 <para>
3529 Sometimes even the rules of <xref linkend="instance-rules"/> are too onerous.
3530 For example, sometimes you might want to use the following to get the
3531 effect of a "class synonym":
3532 <programlisting>
3533   class (C1 a, C2 a, C3 a) => C a where { }
3534
3535   instance (C1 a, C2 a, C3 a) => C a where { }
3536 </programlisting>
3537 This allows you to write shorter signatures:
3538 <programlisting>
3539   f :: C a => ...
3540 </programlisting>
3541 instead of
3542 <programlisting>
3543   f :: (C1 a, C2 a, C3 a) => ...
3544 </programlisting>
3545 The restrictions on functional dependencies (<xref
3546 linkend="functional-dependencies"/>) are particularly troublesome.
3547 It is tempting to introduce type variables in the context that do not appear in
3548 the head, something that is excluded by the normal rules. For example:
3549 <programlisting>
3550   class HasConverter a b | a -> b where
3551      convert :: a -> b
3552    
3553   data Foo a = MkFoo a
3554
3555   instance (HasConverter a b,Show b) => Show (Foo a) where
3556      show (MkFoo value) = show (convert value)
3557 </programlisting>
3558 This is dangerous territory, however. Here, for example, is a program that would make the
3559 typechecker loop:
3560 <programlisting>
3561   class D a
3562   class F a b | a->b
3563   instance F [a] [[a]]
3564   instance (D c, F a c) => D [a]   -- 'c' is not mentioned in the head
3565 </programlisting>
3566 Similarly, it can be tempting to lift the coverage condition:
3567 <programlisting>
3568   class Mul a b c | a b -> c where
3569         (.*.) :: a -> b -> c
3570
3571   instance Mul Int Int Int where (.*.) = (*)
3572   instance Mul Int Float Float where x .*. y = fromIntegral x * y
3573   instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v
3574 </programlisting>
3575 The third instance declaration does not obey the coverage condition;
3576 and indeed the (somewhat strange) definition:
3577 <programlisting>
3578   f = \ b x y -> if b then x .*. [y] else y
3579 </programlisting>
3580 makes instance inference go into a loop, because it requires the constraint
3581 <literal>(Mul a [b] b)</literal>.
3582 </para>
3583 <para>
3584 Nevertheless, GHC allows you to experiment with more liberal rules.  If you use
3585 the experimental flag <option>-XUndecidableInstances</option>
3586 <indexterm><primary>-XUndecidableInstances</primary></indexterm>, 
3587 both the Paterson Conditions and the Coverage Condition
3588 (described in <xref linkend="instance-rules"/>) are lifted.  Termination is ensured by having a
3589 fixed-depth recursion stack.  If you exceed the stack depth you get a
3590 sort of backtrace, and the opportunity to increase the stack depth
3591 with <option>-fcontext-stack=</option><emphasis>N</emphasis>.
3592 </para>
3593
3594 </sect3>
3595
3596
3597 <sect3 id="instance-overlap">
3598 <title>Overlapping instances</title>
3599 <para>
3600 In general, <emphasis>GHC requires that that it be unambiguous which instance
3601 declaration
3602 should be used to resolve a type-class constraint</emphasis>. This behaviour
3603 can be modified by two flags: <option>-XOverlappingInstances</option>
3604 <indexterm><primary>-XOverlappingInstances
3605 </primary></indexterm> 
3606 and <option>-XIncoherentInstances</option>
3607 <indexterm><primary>-XIncoherentInstances
3608 </primary></indexterm>, as this section discusses.  Both these
3609 flags are dynamic flags, and can be set on a per-module basis, using 
3610 an <literal>OPTIONS_GHC</literal> pragma if desired (<xref linkend="source-file-options"/>).</para>
3611 <para>
3612 When GHC tries to resolve, say, the constraint <literal>C Int Bool</literal>,
3613 it tries to match every instance declaration against the
3614 constraint,
3615 by instantiating the head of the instance declaration.  For example, consider
3616 these declarations:
3617 <programlisting>
3618   instance context1 => C Int a     where ...  -- (A)
3619   instance context2 => C a   Bool  where ...  -- (B)
3620   instance context3 => C Int [a]   where ...  -- (C)
3621   instance context4 => C Int [Int] where ...  -- (D)
3622 </programlisting>
3623 The instances (A) and (B) match the constraint <literal>C Int Bool</literal>, 
3624 but (C) and (D) do not.  When matching, GHC takes
3625 no account of the context of the instance declaration
3626 (<literal>context1</literal> etc).
3627 GHC's default behaviour is that <emphasis>exactly one instance must match the
3628 constraint it is trying to resolve</emphasis>.  
3629 It is fine for there to be a <emphasis>potential</emphasis> of overlap (by
3630 including both declarations (A) and (B), say); an error is only reported if a 
3631 particular constraint matches more than one.
3632 </para>
3633
3634 <para>
3635 The <option>-XOverlappingInstances</option> flag instructs GHC to allow
3636 more than one instance to match, provided there is a most specific one.  For
3637 example, the constraint <literal>C Int [Int]</literal> matches instances (A),
3638 (C) and (D), but the last is more specific, and hence is chosen.  If there is no
3639 most-specific match, the program is rejected.
3640 </para>
3641 <para>
3642 However, GHC is conservative about committing to an overlapping instance.  For example:
3643 <programlisting>
3644   f :: [b] -> [b]
3645   f x = ...
3646 </programlisting>
3647 Suppose that from the RHS of <literal>f</literal> we get the constraint
3648 <literal>C Int [b]</literal>.  But
3649 GHC does not commit to instance (C), because in a particular
3650 call of <literal>f</literal>, <literal>b</literal> might be instantiate 
3651 to <literal>Int</literal>, in which case instance (D) would be more specific still.
3652 So GHC rejects the program.  
3653 (If you add the flag <option>-XIncoherentInstances</option>,
3654 GHC will instead pick (C), without complaining about 
3655 the problem of subsequent instantiations.)
3656 </para>
3657 <para>
3658 Notice that we gave a type signature to <literal>f</literal>, so GHC had to
3659 <emphasis>check</emphasis> that <literal>f</literal> has the specified type.  
3660 Suppose instead we do not give a type signature, asking GHC to <emphasis>infer</emphasis>
3661 it instead.  In this case, GHC will refrain from
3662 simplifying the constraint <literal>C Int [b]</literal> (for the same reason
3663 as before) but, rather than rejecting the program, it will infer the type
3664 <programlisting>
3665   f :: C Int [b] => [b] -> [b]
3666 </programlisting>
3667 That postpones the question of which instance to pick to the 
3668 call site for <literal>f</literal>
3669 by which time more is known about the type <literal>b</literal>.
3670 You can write this type signature yourself if you use the 
3671 <link linkend="flexible-contexts"><option>-XFlexibleContexts</option></link>
3672 flag.
3673 </para>
3674 <para>
3675 Exactly the same situation can arise in instance declarations themselves.  Suppose we have
3676 <programlisting>
3677   class Foo a where
3678      f :: a -> a
3679   instance Foo [b] where
3680      f x = ...
3681 </programlisting>
3682 and, as before, the constraint <literal>C Int [b]</literal> arises from <literal>f</literal>'s
3683 right hand side.  GHC will reject the instance, complaining as before that it does not know how to resolve
3684 the constraint <literal>C Int [b]</literal>, because it matches more than one instance
3685 declaration.  The solution is to postpone the choice by adding the constraint to the context
3686 of the instance declaration, thus:
3687 <programlisting>
3688   instance C Int [b] => Foo [b] where
3689      f x = ...
3690 </programlisting>
3691 (You need <link linkend="instance-rules"><option>-XFlexibleInstances</option></link> to do this.)
3692 </para>
3693 <para>
3694 The willingness to be overlapped or incoherent is a property of 
3695 the <emphasis>instance declaration</emphasis> itself, controlled by the
3696 presence or otherwise of the <option>-XOverlappingInstances</option> 
3697 and <option>-XIncoherentInstances</option> flags when that module is
3698 being defined.  Neither flag is required in a module that imports and uses the
3699 instance declaration.  Specifically, during the lookup process:
3700 <itemizedlist>
3701 <listitem><para>
3702 An instance declaration is ignored during the lookup process if (a) a more specific
3703 match is found, and (b) the instance declaration was compiled with 
3704 <option>-XOverlappingInstances</option>.  The flag setting for the
3705 more-specific instance does not matter.
3706 </para></listitem>
3707 <listitem><para>
3708 Suppose an instance declaration does not match the constraint being looked up, but
3709 does unify with it, so that it might match when the constraint is further 
3710 instantiated.  Usually GHC will regard this as a reason for not committing to
3711 some other constraint.  But if the instance declaration was compiled with
3712 <option>-XIncoherentInstances</option>, GHC will skip the "does-it-unify?" 
3713 check for that declaration.
3714 </para></listitem>
3715 </itemizedlist>
3716 These rules make it possible for a library author to design a library that relies on 
3717 overlapping instances without the library client having to know.  
3718 </para>
3719 <para>
3720 If an instance declaration is compiled without
3721 <option>-XOverlappingInstances</option>,
3722 then that instance can never be overlapped.  This could perhaps be
3723 inconvenient.  Perhaps the rule should instead say that the
3724 <emphasis>overlapping</emphasis> instance declaration should be compiled in
3725 this way, rather than the <emphasis>overlapped</emphasis> one.  Perhaps overlap
3726 at a usage site should be permitted regardless of how the instance declarations
3727 are compiled, if the <option>-XOverlappingInstances</option> flag is
3728 used at the usage site.  (Mind you, the exact usage site can occasionally be
3729 hard to pin down.)  We are interested to receive feedback on these points.
3730 </para>
3731 <para>The <option>-XIncoherentInstances</option> flag implies the
3732 <option>-XOverlappingInstances</option> flag, but not vice versa.
3733 </para>
3734 </sect3>
3735
3736
3737
3738 </sect2>
3739
3740 <sect2 id="overloaded-strings">
3741 <title>Overloaded string literals
3742 </title>
3743
3744 <para>
3745 GHC supports <emphasis>overloaded string literals</emphasis>.  Normally a
3746 string literal has type <literal>String</literal>, but with overloaded string
3747 literals enabled (with <literal>-XOverloadedStrings</literal>)
3748  a string literal has type <literal>(IsString a) => a</literal>.
3749 </para>
3750 <para>
3751 This means that the usual string syntax can be used, e.g., for packed strings
3752 and other variations of string like types.  String literals behave very much
3753 like integer literals, i.e., they can be used in both expressions and patterns.
3754 If used in a pattern the literal with be replaced by an equality test, in the same
3755 way as an integer literal is.
3756 </para>
3757 <para>
3758 The class <literal>IsString</literal> is defined as:
3759 <programlisting>
3760 class IsString a where
3761     fromString :: String -> a
3762 </programlisting>
3763 The only predefined instance is the obvious one to make strings work as usual:
3764 <programlisting>
3765 instance IsString [Char] where
3766     fromString cs = cs
3767 </programlisting>
3768 The class <literal>IsString</literal> is not in scope by default.  If you want to mention
3769 it explicitly (for example, to give an instance declaration for it), you can import it
3770 from module <literal>GHC.Exts</literal>.
3771 </para>
3772 <para>
3773 Haskell's defaulting mechanism is extended to cover string literals, when <option>-XOverloadedStrings</option> is specified.
3774 Specifically:
3775 <itemizedlist>
3776 <listitem><para>
3777 Each type in a default declaration must be an 
3778 instance of <literal>Num</literal> <emphasis>or</emphasis> of <literal>IsString</literal>.
3779 </para></listitem>
3780
3781 <listitem><para>
3782 The standard defaulting rule (<ulink url="http://www.haskell.org/onlinereport/decls.html#sect4.3.4">Haskell Report, Section 4.3.4</ulink>)
3783 is extended thus: defaulting applies when all the unresolved constraints involve standard classes
3784 <emphasis>or</emphasis> <literal>IsString</literal>; and at least one is a numeric class
3785 <emphasis>or</emphasis> <literal>IsString</literal>.
3786 </para></listitem>
3787 </itemizedlist>
3788 </para>
3789 <para>
3790 A small example:
3791 <programlisting>
3792 module Main where
3793
3794 import GHC.Exts( IsString(..) )
3795
3796 newtype MyString = MyString String deriving (Eq, Show)
3797 instance IsString MyString where
3798     fromString = MyString
3799
3800 greet :: MyString -> MyString
3801 greet "hello" = "world"
3802 greet other = other
3803
3804 main = do
3805     print $ greet "hello"
3806     print $ greet "fool"
3807 </programlisting>
3808 </para>
3809 <para>
3810 Note that deriving <literal>Eq</literal> is necessary for the pattern matching
3811 to work since it gets translated into an equality comparison.
3812 </para>
3813 </sect2>
3814
3815 </sect1>
3816
3817 <sect1 id="type-families">
3818 <title>Type families</title>
3819
3820 <para>
3821   <firstterm>Indexed type families</firstterm> are a new GHC extension to
3822   facilitate type-level 
3823   programming. Type families are a generalisation of <firstterm>associated
3824   data types</firstterm> 
3825   (&ldquo;<ulink url="http://www.cse.unsw.edu.au/~chak/papers/CKPM05.html">Associated 
3826   Types with Class</ulink>&rdquo;, M. Chakravarty, G. Keller, S. Peyton Jones,
3827   and S. Marlow. In Proceedings of &ldquo;The 32nd Annual ACM SIGPLAN-SIGACT
3828      Symposium on Principles of Programming Languages (POPL'05)&rdquo;, pages
3829   1-13, ACM Press, 2005) and <firstterm>associated type synonyms</firstterm>
3830   (&ldquo;<ulink url="http://www.cse.unsw.edu.au/~chak/papers/CKP05.html">Type  
3831   Associated Type Synonyms</ulink>&rdquo;. M. Chakravarty, G. Keller, and
3832   S. Peyton Jones. 
3833   In Proceedings of &ldquo;The Tenth ACM SIGPLAN International Conference on
3834   Functional Programming&rdquo;, ACM Press, pages 241-253, 2005).  Type families
3835   themselves are described in the paper &ldquo;<ulink 
3836   url="http://www.cse.unsw.edu.au/~chak/papers/SPCS08.html">Type
3837   Checking with Open Type Functions</ulink>&rdquo;, T. Schrijvers,
3838   S. Peyton-Jones, 
3839   M. Chakravarty, and M. Sulzmann, in Proceedings of &ldquo;ICFP 2008: The
3840   13th ACM SIGPLAN International Conference on Functional
3841   Programming&rdquo;, ACM Press, pages 51-62, 2008. Type families
3842   essentially provide type-indexed data types and named functions on types,
3843   which are useful for generic programming and highly parameterised library
3844   interfaces as well as interfaces with enhanced static information, much like
3845   dependent types. They might also be regarded as an alternative to functional
3846   dependencies, but provide a more functional style of type-level programming
3847   than the relational style of functional dependencies. 
3848 </para>
3849 <para>
3850   Indexed type families, or type families for short, are type constructors that
3851   represent sets of types. Set members are denoted by supplying the type family
3852   constructor with type parameters, which are called <firstterm>type
3853   indices</firstterm>. The 
3854   difference between vanilla parametrised type constructors and family
3855   constructors is much like between parametrically polymorphic functions and
3856   (ad-hoc polymorphic) methods of type classes. Parametric polymorphic functions
3857   behave the same at all type instances, whereas class methods can change their
3858   behaviour in dependence on the class type parameters. Similarly, vanilla type
3859   constructors imply the same data representation for all type instances, but
3860   family constructors can have varying representation types for varying type
3861   indices. 
3862 </para>
3863 <para>
3864   Indexed type families come in two flavours: <firstterm>data
3865     families</firstterm> and <firstterm>type synonym 
3866     families</firstterm>. They are the indexed family variants of algebraic
3867   data types and type synonyms, respectively. The instances of data families
3868   can be data types and newtypes. 
3869 </para>
3870 <para>
3871   Type families are enabled by the flag <option>-XTypeFamilies</option>.
3872   Additional information on the use of type families in GHC is available on
3873   <ulink url="http://www.haskell.org/haskellwiki/GHC/Indexed_types">the
3874   Haskell wiki page on type families</ulink>.
3875 </para>
3876
3877 <sect2 id="data-families">
3878   <title>Data families</title>
3879
3880   <para>
3881     Data families appear in two flavours: (1) they can be defined on the
3882     toplevel 
3883     or (2) they can appear inside type classes (in which case they are known as
3884     associated types). The former is the more general variant, as it lacks the
3885     requirement for the type-indexes to coincide with the class
3886     parameters. However, the latter can lead to more clearly structured code and
3887     compiler warnings if some type instances were - possibly accidentally -
3888     omitted. In the following, we always discuss the general toplevel form first
3889     and then cover the additional constraints placed on associated types.
3890   </para>
3891
3892   <sect3 id="data-family-declarations"> 
3893     <title>Data family declarations</title>
3894
3895     <para>
3896       Indexed data families are introduced by a signature, such as 
3897 <programlisting>
3898 data family GMap k :: * -> *
3899 </programlisting>
3900       The special <literal>family</literal> distinguishes family from standard
3901       data declarations.  The result kind annotation is optional and, as
3902       usual, defaults to <literal>*</literal> if omitted.  An example is
3903 <programlisting>
3904 data family Array e
3905 </programlisting>
3906       Named arguments can also be given explicit kind signatures if needed.
3907       Just as with
3908       [http://www.haskell.org/ghc/docs/latest/html/users_guide/gadt.html GADT
3909       declarations] named arguments are entirely optional, so that we can
3910       declare <literal>Array</literal> alternatively with 
3911 <programlisting>
3912 data family Array :: * -> *
3913 </programlisting>
3914     </para>
3915
3916     <sect4 id="assoc-data-family-decl">
3917       <title>Associated data family declarations</title>
3918       <para>
3919         When a data family is declared as part of a type class, we drop
3920         the <literal>family</literal> special.  The <literal>GMap</literal>
3921         declaration takes the following form 
3922 <programlisting>
3923 class GMapKey k where
3924   data GMap k :: * -> *
3925   ...
3926 </programlisting>
3927         In contrast to toplevel declarations, named arguments must be used for
3928         all type parameters that are to be used as type-indexes.  Moreover,
3929         the argument names must be class parameters.  Each class parameter may
3930         only be used at most once per associated type, but some may be omitted
3931         and they may be in an order other than in the class head.  Hence, the
3932         following contrived example is admissible: 
3933 <programlisting>
3934   class C a b c where
3935   data T c a :: *
3936 </programlisting>
3937       </para>
3938     </sect4>
3939   </sect3>
3940
3941   <sect3 id="data-instance-declarations"> 
3942     <title>Data instance declarations</title>
3943
3944     <para>
3945       Instance declarations of data and newtype families are very similar to
3946       standard data and newtype declarations.  The only two differences are
3947       that the keyword <literal>data</literal> or <literal>newtype</literal>
3948       is followed by <literal>instance</literal> and that some or all of the
3949       type arguments can be non-variable types, but may not contain forall
3950       types or type synonym families.  However, data families are generally
3951       allowed in type parameters, and type synonyms are allowed as long as
3952       they are fully applied and expand to a type that is itself admissible -
3953       exactly as this is required for occurrences of type synonyms in class
3954       instance parameters.  For example, the <literal>Either</literal>
3955       instance for <literal>GMap</literal> is 
3956 <programlisting>
3957 data instance GMap (Either a b) v = GMapEither (GMap a v) (GMap b v)
3958 </programlisting>
3959       In this example, the declaration has only one variant.  In general, it
3960       can be any number.
3961     </para>
3962     <para>
3963       Data and newtype instance declarations are only permitted when an
3964       appropriate family declaration is in scope - just as a class instance declaratoin
3965       requires the class declaration to be visible.  Moreover, each instance
3966       declaration has to conform to the kind determined by its family
3967       declaration.  This implies that the number of parameters of an instance
3968       declaration matches the arity determined by the kind of the family.
3969     </para>
3970     <para>
3971       A data family instance declaration can use the full exprssiveness of
3972       ordinary <literal>data</literal> or <literal>newtype</literal> declarations:
3973       <itemizedlist>
3974       <listitem><para> Although, a data family is <emphasis>introduced</emphasis> with
3975       the keyword "<literal>data</literal>", a data family <emphasis>instance</emphasis> can 
3976       use either <literal>data</literal> or <literal>newtype</literal>. For example:
3977 <programlisting>
3978 data family T a
3979 data    instance T Int  = T1 Int | T2 Bool
3980 newtype instance T Char = TC Bool
3981 </programlisting>
3982       </para></listitem>
3983       <listitem><para> A <literal>data instance</literal> can use GADT syntax for the data constructors,
3984       and indeed can define a GADT.  For example:
3985 <programlisting>
3986 data family G a b
3987 data instance G [a] b where
3988    G1 :: c -> G [Int] b
3989    G2 :: G [a] Bool
3990 </programlisting>
3991       </para></listitem>
3992       <listitem><para> You can use a <literal>deriving</literal> clause on a
3993       <literal>data instance</literal> or <literal>newtype instance</literal>
3994       declaration.
3995       </para></listitem>
3996       </itemizedlist>
3997     </para>
3998
3999     <para>
4000       Even if type families are defined as toplevel declarations, functions
4001       that perform different computations for different family instances may still
4002       need to be defined as methods of type classes.  In particular, the
4003       following is not possible: 
4004 <programlisting>
4005 data family T a
4006 data instance T Int  = A
4007 data instance T Char = B
4008 foo :: T a -> Int
4009 foo A = 1             -- WRONG: These two equations together...
4010 foo B = 2             -- ...will produce a type error.
4011 </programlisting>
4012 Instead, you would have to write <literal>foo</literal> as a class operation, thus:
4013 <programlisting>
4014 class C a where 
4015   foo :: T a -> Int
4016 instance Foo Int where
4017   foo A = 1
4018 instance Foo Char where
4019   foo B = 2
4020 </programlisting>
4021       (Given the functionality provided by GADTs (Generalised Algebraic Data
4022       Types), it might seem as if a definition, such as the above, should be
4023       feasible.  However, type families are - in contrast to GADTs - are
4024       <emphasis>open;</emphasis> i.e., new instances can always be added,
4025       possibly in other 
4026       modules.  Supporting pattern matching across different data instances
4027       would require a form of extensible case construct.)
4028     </para>
4029
4030     <sect4 id="assoc-data-inst">
4031       <title>Associated data instances</title>
4032       <para>
4033         When an associated data family instance is declared within a type
4034         class instance, we drop the <literal>instance</literal> keyword in the
4035         family instance.  So, the <literal>Either</literal> instance
4036         for <literal>GMap</literal> becomes: 
4037 <programlisting>
4038 instance (GMapKey a, GMapKey b) => GMapKey (Either a b) where
4039   data GMap (Either a b) v = GMapEither (GMap a v) (GMap b v)
4040   ...
4041 </programlisting>
4042         The most important point about associated family instances is that the
4043         type indexes corresponding to class parameters must be identical to
4044         the type given in the instance head; here this is the first argument
4045         of <literal>GMap</literal>, namely <literal>Either a b</literal>,
4046         which coincides with the only class parameter.  Any parameters to the
4047         family constructor that do not correspond to class parameters, need to
4048         be variables in every instance; here this is the
4049         variable <literal>v</literal>. 
4050       </para>
4051       <para>
4052         Instances for an associated family can only appear as part of
4053         instances declarations of the class in which the family was declared -
4054         just as with the equations of the methods of a class.  Also in
4055         correspondence to how methods are handled, declarations of associated
4056         types can be omitted in class instances.  If an associated family
4057         instance is omitted, the corresponding instance type is not inhabited;
4058         i.e., only diverging expressions, such
4059         as <literal>undefined</literal>, can assume the type. 
4060       </para>
4061     </sect4>
4062
4063     <sect4 id="scoping-class-params">
4064       <title>Scoping of class parameters</title>
4065       <para>
4066         In the case of multi-parameter type classes, the visibility of class
4067         parameters in the right-hand side of associated family instances
4068         depends <emphasis>solely</emphasis> on the parameters of the data
4069         family.  As an example, consider the simple class declaration 
4070 <programlisting>
4071 class C a b where
4072   data T a
4073 </programlisting>
4074         Only one of the two class parameters is a parameter to the data
4075         family.  Hence, the following instance declaration is invalid: 
4076 <programlisting>
4077 instance C [c] d where
4078   data T [c] = MkT (c, d)    -- WRONG!!  'd' is not in scope
4079 </programlisting>
4080         Here, the right-hand side of the data instance mentions the type
4081         variable <literal>d</literal> that does not occur in its left-hand
4082         side.  We cannot admit such data instances as they would compromise
4083         type safety. 
4084       </para>
4085     </sect4>
4086
4087     <sect4 id="family-class-inst">
4088       <title>Type class instances of family instances</title>
4089       <para>
4090         Type class instances of instances of data families can be defined as
4091         usual, and in particular data instance declarations can
4092         have <literal>deriving</literal> clauses.  For example, we can write 
4093 <programlisting>
4094 data GMap () v = GMapUnit (Maybe v)
4095                deriving Show
4096 </programlisting>
4097         which implicitly defines an instance of the form
4098 <programlisting>
4099 instance Show v => Show (GMap () v) where ...
4100 </programlisting>
4101       </para>
4102       <para>
4103         Note that class instances are always for
4104         particular <emphasis>instances</emphasis> of a data family and never
4105         for an entire family as a whole.  This is for essentially the same
4106         reasons that we cannot define a toplevel function that performs
4107         pattern matching on the data constructors
4108         of <emphasis>different</emphasis> instances of a single type family.
4109         It would require a form of extensible case construct. 
4110       </para>
4111     </sect4>
4112
4113     <sect4 id="data-family-overlap">
4114       <title>Overlap of data instances</title>
4115       <para>
4116         The instance declarations of a data family used in a single program
4117         may not overlap at all, independent of whether they are associated or
4118         not.  In contrast to type class instances, this is not only a matter
4119         of consistency, but one of type safety. 
4120       </para>
4121     </sect4>
4122
4123   </sect3>
4124
4125   <sect3 id="data-family-import-export">
4126     <title>Import and export</title>
4127
4128     <para>
4129       The association of data constructors with type families is more dynamic
4130       than that is the case with standard data and newtype declarations.  In
4131       the standard case, the notation <literal>T(..)</literal> in an import or
4132       export list denotes the type constructor and all the data constructors
4133       introduced in its declaration.  However, a family declaration never
4134       introduces any data constructors; instead, data constructors are
4135       introduced by family instances.  As a result, which data constructors
4136       are associated with a type family depends on the currently visible
4137       instance declarations for that family.  Consequently, an import or
4138       export item of the form <literal>T(..)</literal> denotes the family
4139       constructor and all currently visible data constructors - in the case of
4140       an export item, these may be either imported or defined in the current
4141       module.  The treatment of import and export items that explicitly list
4142       data constructors, such as <literal>GMap(GMapEither)</literal>, is
4143       analogous. 
4144     </para>
4145
4146     <sect4 id="data-family-impexp-assoc">
4147       <title>Associated families</title>
4148       <para>
4149         As expected, an import or export item of the
4150         form <literal>C(..)</literal> denotes all of the class' methods and
4151         associated types.  However, when associated types are explicitly
4152         listed as subitems of a class, we need some new syntax, as uppercase
4153         identifiers as subitems are usually data constructors, not type
4154         constructors.  To clarify that we denote types here, each associated
4155         type name needs to be prefixed by the keyword <literal>type</literal>.
4156         So for example, when explicitly listing the components of
4157         the <literal>GMapKey</literal> class, we write <literal>GMapKey(type
4158         GMap, empty, lookup, insert)</literal>. 
4159       </para>
4160     </sect4>
4161
4162     <sect4 id="data-family-impexp-examples">
4163       <title>Examples</title>
4164       <para>
4165         Assuming our running <literal>GMapKey</literal> class example, let us
4166         look at some export lists and their meaning: 
4167         <itemizedlist>
4168           <listitem>
4169             <para><literal>module GMap (GMapKey) where...</literal>: Exports
4170               just the class name.</para>
4171           </listitem>
4172           <listitem>
4173             <para><literal>module GMap (GMapKey(..)) where...</literal>:
4174               Exports the class, the associated type <literal>GMap</literal>
4175               and the member
4176               functions <literal>empty</literal>, <literal>lookup</literal>,
4177               and <literal>insert</literal>.  None of the data constructors is 
4178               exported.</para>
4179           </listitem> 
4180           <listitem>
4181             <para><literal>module GMap (GMapKey(..), GMap(..))
4182                 where...</literal>: As before, but also exports all the data
4183               constructors <literal>GMapInt</literal>, 
4184               <literal>GMapChar</literal>,  
4185               <literal>GMapUnit</literal>, <literal>GMapPair</literal>,
4186               and <literal>GMapUnit</literal>.</para>
4187           </listitem>
4188           <listitem>
4189             <para><literal>module GMap (GMapKey(empty, lookup, insert),
4190             GMap(..)) where...</literal>: As before.</para>
4191           </listitem>
4192           <listitem>
4193             <para><literal>module GMap (GMapKey, empty, lookup, insert, GMap(..))
4194                 where...</literal>: As before.</para>
4195           </listitem>
4196         </itemizedlist>
4197       </para>
4198       <para>
4199         Finally, you can write <literal>GMapKey(type GMap)</literal> to denote
4200         both the class <literal>GMapKey</literal> as well as its associated
4201         type <literal>GMap</literal>.  However, you cannot
4202         write <literal>GMapKey(type GMap(..))</literal> &mdash; i.e.,
4203         sub-component specifications cannot be nested.  To
4204         specify <literal>GMap</literal>'s data constructors, you have to list
4205         it separately. 
4206       </para>
4207     </sect4>
4208
4209     <sect4 id="data-family-impexp-instances">
4210       <title>Instances</title>
4211       <para>
4212         Family instances are implicitly exported, just like class instances.
4213         However, this applies only to the heads of instances, not to the data
4214         constructors an instance defines. 
4215       </para>
4216     </sect4>
4217
4218   </sect3>
4219
4220 </sect2>
4221
4222 <sect2 id="synonym-families">
4223   <title>Synonym families</title>
4224
4225   <para>
4226     Type families appear in two flavours: (1) they can be defined on the
4227     toplevel or (2) they can appear inside type classes (in which case they
4228     are known as associated type synonyms).  The former is the more general
4229     variant, as it lacks the requirement for the type-indexes to coincide with
4230     the class parameters.  However, the latter can lead to more clearly
4231     structured code and compiler warnings if some type instances were -
4232     possibly accidentally - omitted.  In the following, we always discuss the
4233     general toplevel form first and then cover the additional constraints
4234     placed on associated types.
4235   </para>
4236
4237   <sect3 id="type-family-declarations">
4238     <title>Type family declarations</title>
4239
4240     <para>
4241       Indexed type families are introduced by a signature, such as 
4242 <programlisting>
4243 type family Elem c :: *
4244 </programlisting>
4245       The special <literal>family</literal> distinguishes family from standard
4246       type declarations.  The result kind annotation is optional and, as
4247       usual, defaults to <literal>*</literal> if omitted.  An example is 
4248 <programlisting>
4249 type family Elem c
4250 </programlisting>
4251       Parameters can also be given explicit kind signatures if needed.  We
4252       call the number of parameters in a type family declaration, the family's
4253       arity, and all applications of a type family must be fully saturated
4254       w.r.t. to that arity.  This requirement is unlike ordinary type synonyms
4255       and it implies that the kind of a type family is not sufficient to
4256       determine a family's arity, and hence in general, also insufficient to
4257       determine whether a type family application is well formed.  As an
4258       example, consider the following declaration: 
4259 <programlisting>
4260 type family F a b :: * -> *   -- F's arity is 2, 
4261                               -- although it's overall kind is * -> * -> * -> *
4262 </programlisting>
4263       Given this declaration the following are examples of well-formed and
4264       malformed types: 
4265 <programlisting>
4266 F Char [Int]       -- OK!  Kind: * -> *
4267 F Char [Int] Bool  -- OK!  Kind: *
4268 F IO Bool          -- WRONG: kind mismatch in the first argument
4269 F Bool             -- WRONG: unsaturated application
4270 </programlisting>
4271       </para>
4272
4273     <sect4 id="assoc-type-family-decl">
4274       <title>Associated type family declarations</title>
4275       <para>
4276         When a type family is declared as part of a type class, we drop
4277         the <literal>family</literal> special.  The <literal>Elem</literal>
4278         declaration takes the following form 
4279 <programlisting>
4280 class Collects ce where
4281   type Elem ce :: *
4282   ...
4283 </programlisting>
4284         The argument names of the type family must be class parameters.  Each
4285         class parameter may only be used at most once per associated type, but
4286         some may be omitted and they may be in an order other than in the
4287         class head.  Hence, the following contrived example is admissible: 
4288 <programlisting>
4289 class C a b c where
4290   type T c a :: *
4291 </programlisting>
4292         These rules are exactly as for associated data families.
4293       </para>
4294     </sect4>
4295   </sect3>
4296
4297   <sect3 id="type-instance-declarations">
4298     <title>Type instance declarations</title>
4299     <para>
4300       Instance declarations of type families are very similar to standard type
4301       synonym declarations.  The only two differences are that the
4302       keyword <literal>type</literal> is followed
4303       by <literal>instance</literal> and that some or all of the type
4304       arguments can be non-variable types, but may not contain forall types or
4305       type synonym families. However, data families are generally allowed, and
4306       type synonyms are allowed as long as they are fully applied and expand
4307       to a type that is admissible - these are the exact same requirements as
4308       for data instances.  For example, the <literal>[e]</literal> instance
4309       for <literal>Elem</literal> is 
4310 <programlisting>
4311 type instance Elem [e] = e
4312 </programlisting>
4313     </para>
4314     <para>
4315       Type family instance declarations are only legitimate when an
4316       appropriate family declaration is in scope - just like class instances
4317       require the class declaration to be visible.  Moreover, each instance
4318       declaration has to conform to the kind determined by its family
4319       declaration, and the number of type parameters in an instance
4320       declaration must match the number of type parameters in the family
4321       declaration.   Finally, the right-hand side of a type instance must be a
4322       monotype (i.e., it may not include foralls) and after the expansion of
4323       all saturated vanilla type synonyms, no synonyms, except family synonyms
4324       may remain.  Here are some examples of admissible and illegal type
4325       instances: 
4326 <programlisting>
4327 type family F a :: *
4328 type instance F [Int]              = Int         -- OK!
4329 type instance F String             = Char        -- OK!
4330 type instance F (F a)              = a           -- WRONG: type parameter mentions a type family
4331 type instance F (forall a. (a, b)) = b           -- WRONG: a forall type appears in a type parameter
4332 type instance F Float              = forall a.a  -- WRONG: right-hand side may not be a forall type
4333
4334 type family G a b :: * -> *
4335 type instance G Int            = (,)     -- WRONG: must be two type parameters
4336 type instance G Int Char Float = Double  -- WRONG: must be two type parameters
4337 </programlisting>
4338     </para>
4339
4340     <sect4 id="assoc-type-instance">
4341       <title>Associated type instance declarations</title>
4342       <para>
4343         When an associated family instance is declared within a type class
4344         instance, we drop the <literal>instance</literal> keyword in the family
4345         instance.  So, the <literal>[e]</literal> instance
4346         for <literal>Elem</literal> becomes: 
4347 <programlisting>
4348 instance (Eq (Elem [e])) => Collects ([e]) where
4349   type Elem [e] = e
4350   ...
4351 </programlisting>
4352         The most important point about associated family instances is that the
4353         type indexes corresponding to class parameters must be identical to the
4354         type given in the instance head; here this is <literal>[e]</literal>,
4355         which coincides with the only class parameter. 
4356       </para>
4357       <para>
4358         Instances for an associated family can only appear as part of  instances
4359         declarations of the class in which the family was declared - just as
4360         with the equations of the methods of a class.  Also in correspondence to
4361         how methods are handled, declarations of associated types can be omitted
4362         in class instances.  If an associated family instance is omitted, the
4363         corresponding instance type is not inhabited; i.e., only diverging
4364         expressions, such as <literal>undefined</literal>, can assume the type. 
4365       </para>
4366     </sect4>
4367
4368     <sect4 id="type-family-overlap">
4369       <title>Overlap of type synonym instances</title>
4370       <para>
4371         The instance declarations of a type family used in a single program
4372         may only overlap if the right-hand sides of the overlapping instances
4373         coincide for the overlapping types.  More formally, two instance
4374         declarations overlap if there is a substitution that makes the
4375         left-hand sides of the instances syntactically the same.  Whenever
4376         that is the case, the right-hand sides of the instances must also be
4377         syntactically equal under the same substitution.  This condition is
4378         independent of whether the type family is associated or not, and it is
4379         not only a matter of consistency, but one of type safety. 
4380       </para>
4381       <para>
4382         Here are two example to illustrate the condition under which overlap
4383         is permitted. 
4384 <programlisting>
4385 type instance F (a, Int) = [a]
4386 type instance F (Int, b) = [b]   -- overlap permitted
4387
4388 type instance G (a, Int)  = [a]
4389 type instance G (Char, a) = [a]  -- ILLEGAL overlap, as [Char] /= [Int]
4390 </programlisting>
4391       </para>
4392     </sect4>
4393
4394     <sect4 id="type-family-decidability">
4395       <title>Decidability of type synonym instances</title>
4396       <para>
4397         In order to guarantee that type inference in the presence of type
4398         families decidable, we need to place a number of additional
4399         restrictions on the formation of type instance declarations (c.f.,
4400         Definition 5 (Relaxed Conditions) of &ldquo;<ulink 
4401         url="http://www.cse.unsw.edu.au/~chak/papers/SPCS08.html">Type
4402           Checking with Open Type Functions</ulink>&rdquo;).  Instance
4403           declarations have the general form 
4404 <programlisting>
4405 type instance F t1 .. tn = t
4406 </programlisting>
4407         where we require that for every type family application <literal>(G s1
4408         .. sm)</literal> in <literal>t</literal>,  
4409         <orderedlist>
4410           <listitem>
4411             <para><literal>s1 .. sm</literal> do not contain any type family
4412             constructors,</para>
4413           </listitem>
4414           <listitem>
4415             <para>the total number of symbols (data type constructors and type
4416             variables) in <literal>s1 .. sm</literal> is strictly smaller than
4417             in <literal>t1 .. tn</literal>, and</para> 
4418           </listitem>
4419           <listitem>
4420             <para>for every type
4421             variable <literal>a</literal>, <literal>a</literal> occurs
4422             in <literal>s1 .. sm</literal> at most as often as in <literal>t1
4423             .. tn</literal>.</para>
4424           </listitem>
4425         </orderedlist>
4426         These restrictions are easily verified and ensure termination of type
4427         inference.  However, they are not sufficient to guarantee completeness
4428         of type inference in the presence of, so called, ''loopy equalities'',
4429         such as <literal>a ~ [F a]</literal>, where a recursive occurrence of
4430         a type variable is underneath a family application and data
4431         constructor application - see the above mentioned paper for details.   
4432       </para>
4433       <para>
4434         If the option <option>-XUndecidableInstances</option> is passed to the
4435         compiler, the above restrictions are not enforced and it is on the
4436         programmer to ensure termination of the normalisation of type families
4437         during type inference. 
4438       </para>
4439     </sect4>
4440   </sect3>
4441
4442   <sect3 id-="equality-constraints">
4443     <title>Equality constraints</title>
4444     <para>
4445       Type context can include equality constraints of the form <literal>t1 ~
4446       t2</literal>, which denote that the types <literal>t1</literal>
4447       and <literal>t2</literal> need to be the same.  In the presence of type
4448       families, whether two types are equal cannot generally be decided
4449       locally.  Hence, the contexts of function signatures may include
4450       equality constraints, as in the following example: 
4451 <programlisting>
4452 sumCollects :: (Collects c1, Collects c2, Elem c1 ~ Elem c2) => c1 -> c2 -> c2
4453 </programlisting>
4454       where we require that the element type of <literal>c1</literal>
4455       and <literal>c2</literal> are the same.  In general, the
4456       types <literal>t1</literal> and <literal>t2</literal> of an equality
4457       constraint may be arbitrary monotypes; i.e., they may not contain any
4458       quantifiers, independent of whether higher-rank types are otherwise
4459       enabled. 
4460     </para>
4461     <para>
4462       Equality constraints can also appear in class and instance contexts.
4463       The former enable a simple translation of programs using functional
4464       dependencies into programs using family synonyms instead.  The general
4465       idea is to rewrite a class declaration of the form 
4466 <programlisting>
4467 class C a b | a -> b
4468 </programlisting>
4469       to
4470 <programlisting>
4471 class (F a ~ b) => C a b where
4472   type F a
4473 </programlisting>
4474       That is, we represent every functional dependency (FD) <literal>a1 .. an
4475       -> b</literal> by an FD type family <literal>F a1 .. an</literal> and a
4476       superclass context equality <literal>F a1 .. an ~ b</literal>,
4477       essentially giving a name to the functional dependency.  In class
4478       instances, we define the type instances of FD families in accordance
4479       with the class head.  Method signatures are not affected by that
4480       process. 
4481     </para>
4482     <para>
4483       NB: Equalities in superclass contexts are not fully implemented in
4484       GHC 6.10. 
4485     </para>
4486   </sect3>
4487
4488   <sect3 id-="ty-fams-in-instances">
4489     <title>Type families and instance declarations</title>
4490     <para>Type families require us to extend the rules for 
4491       the form of instance heads, which are given 
4492       in <xref linkend="flexible-instance-head"/>.
4493       Specifically:
4494 <itemizedlist>
4495  <listitem><para>Data type families may appear in an instance head</para></listitem>
4496  <listitem><para>Type synonym families may not appear (at all) in an instance head</para></listitem>
4497 </itemizedlist>
4498 The reason for the latter restriction is that there is no way to check for. Consider
4499 <programlisting>
4500    type family F a
4501    type instance F Bool = Int
4502
4503    class C a
4504
4505    instance C Int
4506    instance C (F a)
4507 </programlisting>
4508 Now a constraint <literal>(C (F Bool))</literal> would match both instances.
4509 The situation is especially bad because the type instance for <literal>F Bool</literal>
4510 might be in another module, or even in a module that is not yet written.
4511 </para>
4512 </sect3>
4513 </sect2>
4514
4515 </sect1>
4516
4517 <sect1 id="other-type-extensions">
4518 <title>Other type system extensions</title>
4519
4520 <sect2 id="type-restrictions">
4521 <title>Type signatures</title>
4522
4523 <sect3 id="flexible-contexts"><title>The context of a type signature</title>
4524 <para>
4525 The <option>-XFlexibleContexts</option> flag lifts the Haskell 98 restriction
4526 that the type-class constraints in a type signature must have the 
4527 form <emphasis>(class type-variable)</emphasis> or
4528 <emphasis>(class (type-variable type-variable ...))</emphasis>. 
4529 With <option>-XFlexibleContexts</option>
4530 these type signatures are perfectly OK
4531 <programlisting>
4532   g :: Eq [a] => ...
4533   g :: Ord (T a ()) => ...
4534 </programlisting>
4535 </para>
4536 <para>
4537 GHC imposes the following restrictions on the constraints in a type signature.
4538 Consider the type:
4539
4540 <programlisting>
4541   forall tv1..tvn (c1, ...,cn) => type
4542 </programlisting>
4543
4544 (Here, we write the "foralls" explicitly, although the Haskell source
4545 language omits them; in Haskell 98, all the free type variables of an
4546 explicit source-language type signature are universally quantified,
4547 except for the class type variables in a class declaration.  However,
4548 in GHC, you can give the foralls if you want.  See <xref linkend="universal-quantification"/>).
4549 </para>
4550
4551 <para>
4552
4553 <orderedlist>
4554 <listitem>
4555
4556 <para>
4557  <emphasis>Each universally quantified type variable
4558 <literal>tvi</literal> must be reachable from <literal>type</literal></emphasis>.
4559
4560 A type variable <literal>a</literal> is "reachable" if it appears
4561 in the same constraint as either a type variable free in
4562 <literal>type</literal>, or another reachable type variable.  
4563 A value with a type that does not obey 
4564 this reachability restriction cannot be used without introducing
4565 ambiguity; that is why the type is rejected.
4566 Here, for example, is an illegal type:
4567
4568
4569 <programlisting>
4570   forall a. Eq a => Int
4571 </programlisting>
4572
4573
4574 When a value with this type was used, the constraint <literal>Eq tv</literal>
4575 would be introduced where <literal>tv</literal> is a fresh type variable, and
4576 (in the dictionary-translation implementation) the value would be
4577 applied to a dictionary for <literal>Eq tv</literal>.  The difficulty is that we
4578 can never know which instance of <literal>Eq</literal> to use because we never
4579 get any more information about <literal>tv</literal>.
4580 </para>
4581 <para>
4582 Note
4583 that the reachability condition is weaker than saying that <literal>a</literal> is
4584 functionally dependent on a type variable free in
4585 <literal>type</literal> (see <xref
4586 linkend="functional-dependencies"/>).  The reason for this is there
4587 might be a "hidden" dependency, in a superclass perhaps.  So
4588 "reachable" is a conservative approximation to "functionally dependent".
4589 For example, consider:
4590 <programlisting>
4591   class C a b | a -> b where ...
4592   class C a b => D a b where ...
4593   f :: forall a b. D a b => a -> a
4594 </programlisting>
4595 This is fine, because in fact <literal>a</literal> does functionally determine <literal>b</literal>
4596 but that is not immediately apparent from <literal>f</literal>'s type.
4597 </para>
4598 </listitem>
4599 <listitem>
4600
4601 <para>
4602  <emphasis>Every constraint <literal>ci</literal> must mention at least one of the
4603 universally quantified type variables <literal>tvi</literal></emphasis>.
4604
4605 For example, this type is OK because <literal>C a b</literal> mentions the
4606 universally quantified type variable <literal>b</literal>:
4607
4608
4609 <programlisting>
4610   forall a. C a b => burble
4611 </programlisting>
4612
4613
4614 The next type is illegal because the constraint <literal>Eq b</literal> does not
4615 mention <literal>a</literal>:
4616
4617
4618 <programlisting>
4619   forall a. Eq b => burble
4620 </programlisting>
4621
4622
4623 The reason for this restriction is milder than the other one.  The
4624 excluded types are never useful or necessary (because the offending
4625 context doesn't need to be witnessed at this point; it can be floated
4626 out).  Furthermore, floating them out increases sharing. Lastly,
4627 excluding them is a conservative choice; it leaves a patch of
4628 territory free in case we need it later.
4629
4630 </para>
4631 </listitem>
4632
4633 </orderedlist>
4634
4635 </para>
4636 </sect3>
4637
4638
4639
4640 </sect2>
4641
4642 <sect2 id="implicit-parameters">
4643 <title>Implicit parameters</title>
4644
4645 <para> Implicit parameters are implemented as described in 
4646 "Implicit parameters: dynamic scoping with static types", 
4647 J Lewis, MB Shields, E Meijer, J Launchbury,
4648 27th ACM Symposium on Principles of Programming Languages (POPL'00),
4649 Boston, Jan 2000.
4650 </para>
4651
4652 <para>(Most of the following, still rather incomplete, documentation is
4653 due to Jeff Lewis.)</para>
4654
4655 <para>Implicit parameter support is enabled with the option
4656 <option>-XImplicitParams</option>.</para>
4657
4658 <para>
4659 A variable is called <emphasis>dynamically bound</emphasis> when it is bound by the calling
4660 context of a function and <emphasis>statically bound</emphasis> when bound by the callee's
4661 context. In Haskell, all variables are statically bound. Dynamic
4662 binding of variables is a notion that goes back to Lisp, but was later
4663 discarded in more modern incarnations, such as Scheme. Dynamic binding
4664 can be very confusing in an untyped language, and unfortunately, typed
4665 languages, in particular Hindley-Milner typed languages like Haskell,
4666 only support static scoping of variables.
4667 </para>
4668 <para>
4669 However, by a simple extension to the type class system of Haskell, we
4670 can support dynamic binding. Basically, we express the use of a
4671 dynamically bound variable as a constraint on the type. These
4672 constraints lead to types of the form <literal>(?x::t') => t</literal>, which says "this
4673 function uses a dynamically-bound variable <literal>?x</literal> 
4674 of type <literal>t'</literal>". For
4675 example, the following expresses the type of a sort function,
4676 implicitly parameterized by a comparison function named <literal>cmp</literal>.
4677 <programlisting>
4678   sort :: (?cmp :: a -> a -> Bool) => [a] -> [a]
4679 </programlisting>
4680 The dynamic binding constraints are just a new form of predicate in the type class system.
4681 </para>
4682 <para>
4683 An implicit parameter occurs in an expression using the special form <literal>?x</literal>, 
4684 where <literal>x</literal> is
4685 any valid identifier (e.g. <literal>ord ?x</literal> is a valid expression). 
4686 Use of this construct also introduces a new
4687 dynamic-binding constraint in the type of the expression. 
4688 For example, the following definition
4689 shows how we can define an implicitly parameterized sort function in
4690 terms of an explicitly parameterized <literal>sortBy</literal> function:
4691 <programlisting>
4692   sortBy :: (a -> a -> Bool) -> [a] -> [a]
4693
4694   sort   :: (?cmp :: a -> a -> Bool) => [a] -> [a]
4695   sort    = sortBy ?cmp
4696 </programlisting>
4697 </para>
4698
4699 <sect3>
4700 <title>Implicit-parameter type constraints</title>
4701 <para>
4702 Dynamic binding constraints behave just like other type class
4703 constraints in that they are automatically propagated. Thus, when a
4704 function is used, its implicit parameters are inherited by the
4705 function that called it. For example, our <literal>sort</literal> function might be used
4706 to pick out the least value in a list:
4707 <programlisting>
4708   least   :: (?cmp :: a -> a -> Bool) => [a] -> a
4709   least xs = head (sort xs)
4710 </programlisting>
4711 Without lifting a finger, the <literal>?cmp</literal> parameter is
4712 propagated to become a parameter of <literal>least</literal> as well. With explicit
4713 parameters, the default is that parameters must always be explicit
4714 propagated. With implicit parameters, the default is to always
4715 propagate them.
4716 </para>
4717 <para>
4718 An implicit-parameter type constraint differs from other type class constraints in the
4719 following way: All uses of a particular implicit parameter must have
4720 the same type. This means that the type of <literal>(?x, ?x)</literal> 
4721 is <literal>(?x::a) => (a,a)</literal>, and not 
4722 <literal>(?x::a, ?x::b) => (a, b)</literal>, as would be the case for type
4723 class constraints.
4724 </para>
4725
4726 <para> You can't have an implicit parameter in the context of a class or instance
4727 declaration.  For example, both these declarations are illegal:
4728 <programlisting>
4729   class (?x::Int) => C a where ...
4730   instance (?x::a) => Foo [a] where ...
4731 </programlisting>
4732 Reason: exactly which implicit parameter you pick up depends on exactly where
4733 you invoke a function. But the ``invocation'' of instance declarations is done
4734 behind the scenes by the compiler, so it's hard to figure out exactly where it is done.
4735 Easiest thing is to outlaw the offending types.</para>
4736 <para>
4737 Implicit-parameter constraints do not cause ambiguity.  For example, consider:
4738 <programlisting>
4739    f :: (?x :: [a]) => Int -> Int
4740    f n = n + length ?x
4741
4742    g :: (Read a, Show a) => String -> String
4743    g s = show (read s)
4744 </programlisting>
4745 Here, <literal>g</literal> has an ambiguous type, and is rejected, but <literal>f</literal>
4746 is fine.  The binding for <literal>?x</literal> at <literal>f</literal>'s call site is 
4747 quite unambiguous, and fixes the type <literal>a</literal>.
4748 </para>
4749 </sect3>
4750
4751 <sect3>
4752 <title>Implicit-parameter bindings</title>
4753
4754 <para>
4755 An implicit parameter is <emphasis>bound</emphasis> using the standard
4756 <literal>let</literal> or <literal>where</literal> binding forms.
4757 For example, we define the <literal>min</literal> function by binding
4758 <literal>cmp</literal>.
4759 <programlisting>
4760   min :: [a] -> a
4761   min  = let ?cmp = (&lt;=) in least
4762 </programlisting>
4763 </para>
4764 <para>
4765 A group of implicit-parameter bindings may occur anywhere a normal group of Haskell
4766 bindings can occur, except at top level.  That is, they can occur in a <literal>let</literal> 
4767 (including in a list comprehension, or do-notation, or pattern guards), 
4768 or a <literal>where</literal> clause.
4769 Note the following points:
4770 <itemizedlist>
4771 <listitem><para>
4772 An implicit-parameter binding group must be a
4773 collection of simple bindings to implicit-style variables (no
4774 function-style bindings, and no type signatures); these bindings are
4775 neither polymorphic or recursive.  
4776 </para></listitem>
4777 <listitem><para>
4778 You may not mix implicit-parameter bindings with ordinary bindings in a 
4779 single <literal>let</literal>
4780 expression; use two nested <literal>let</literal>s instead.
4781 (In the case of <literal>where</literal> you are stuck, since you can't nest <literal>where</literal> clauses.)
4782 </para></listitem>
4783
4784 <listitem><para>
4785 You may put multiple implicit-parameter bindings in a
4786 single binding group; but they are <emphasis>not</emphasis> treated
4787 as a mutually recursive group (as ordinary <literal>let</literal> bindings are).
4788 Instead they are treated as a non-recursive group, simultaneously binding all the implicit
4789 parameter.  The bindings are not nested, and may be re-ordered without changing
4790 the meaning of the program.
4791 For example, consider:
4792 <programlisting>
4793   f t = let { ?x = t; ?y = ?x+(1::Int) } in ?x + ?y
4794 </programlisting>
4795 The use of <literal>?x</literal> in the binding for <literal>?y</literal> does not "see"
4796 the binding for <literal>?x</literal>, so the type of <literal>f</literal> is
4797 <programlisting>
4798   f :: (?x::Int) => Int -> Int
4799 </programlisting>
4800 </para></listitem>
4801 </itemizedlist>
4802 </para>
4803
4804 </sect3>
4805
4806 <sect3><title>Implicit parameters and polymorphic recursion</title>
4807
4808 <para>
4809 Consider these two definitions:
4810 <programlisting>
4811   len1 :: [a] -> Int
4812   len1 xs = let ?acc = 0 in len_acc1 xs
4813
4814   len_acc1 [] = ?acc
4815   len_acc1 (x:xs) = let ?acc = ?acc + (1::Int) in len_acc1 xs
4816
4817   ------------
4818
4819   len2 :: [a] -> Int
4820   len2 xs = let ?acc = 0 in len_acc2 xs
4821
4822   len_acc2 :: (?acc :: Int) => [a] -> Int
4823   len_acc2 [] = ?acc
4824   len_acc2 (x:xs) = let ?acc = ?acc + (1::Int) in len_acc2 xs
4825 </programlisting>
4826 The only difference between the two groups is that in the second group
4827 <literal>len_acc</literal> is given a type signature.
4828 In the former case, <literal>len_acc1</literal> is monomorphic in its own
4829 right-hand side, so the implicit parameter <literal>?acc</literal> is not
4830 passed to the recursive call.  In the latter case, because <literal>len_acc2</literal>
4831 has a type signature, the recursive call is made to the
4832 <emphasis>polymorphic</emphasis> version, which takes <literal>?acc</literal>
4833 as an implicit parameter.  So we get the following results in GHCi:
4834 <programlisting>
4835   Prog> len1 "hello"
4836   0
4837   Prog> len2 "hello"
4838   5
4839 </programlisting>
4840 Adding a type signature dramatically changes the result!  This is a rather
4841 counter-intuitive phenomenon, worth watching out for.
4842 </para>
4843 </sect3>
4844
4845 <sect3><title>Implicit parameters and monomorphism</title>
4846
4847 <para>GHC applies the dreaded Monomorphism Restriction (section 4.5.5 of the
4848 Haskell Report) to implicit parameters.  For example, consider:
4849 <programlisting>
4850  f :: Int -> Int
4851   f v = let ?x = 0     in
4852         let y = ?x + v in
4853         let ?x = 5     in
4854         y
4855 </programlisting>
4856 Since the binding for <literal>y</literal> falls under the Monomorphism
4857 Restriction it is not generalised, so the type of <literal>y</literal> is
4858 simply <literal>Int</literal>, not <literal>(?x::Int) => Int</literal>.
4859 Hence, <literal>(f 9)</literal> returns result <literal>9</literal>.
4860 If you add a type signature for <literal>y</literal>, then <literal>y</literal>
4861 will get type <literal>(?x::Int) => Int</literal>, so the occurrence of
4862 <literal>y</literal> in the body of the <literal>let</literal> will see the
4863 inner binding of <literal>?x</literal>, so <literal>(f 9)</literal> will return
4864 <literal>14</literal>.
4865 </para>
4866 </sect3>
4867 </sect2>
4868
4869     <!--   ======================= COMMENTED OUT ========================
4870
4871     We intend to remove linear implicit parameters, so I'm at least removing
4872     them from the 6.6 user manual
4873
4874 <sect2 id="linear-implicit-parameters">
4875 <title>Linear implicit parameters</title>
4876 <para>
4877 Linear implicit parameters are an idea developed by Koen Claessen,
4878 Mark Shields, and Simon PJ.  They address the long-standing
4879 problem that monads seem over-kill for certain sorts of problem, notably:
4880 </para>
4881 <itemizedlist>
4882 <listitem> <para> distributing a supply of unique names </para> </listitem>
4883 <listitem> <para> distributing a supply of random numbers </para> </listitem>
4884 <listitem> <para> distributing an oracle (as in QuickCheck) </para> </listitem>
4885 </itemizedlist>
4886
4887 <para>
4888 Linear implicit parameters are just like ordinary implicit parameters,
4889 except that they are "linear"; that is, they cannot be copied, and
4890 must be explicitly "split" instead.  Linear implicit parameters are
4891 written '<literal>%x</literal>' instead of '<literal>?x</literal>'.  
4892 (The '/' in the '%' suggests the split!)
4893 </para>
4894 <para>
4895 For example:
4896 <programlisting>
4897     import GHC.Exts( Splittable )
4898
4899     data NameSupply = ...
4900     
4901     splitNS :: NameSupply -> (NameSupply, NameSupply)
4902     newName :: NameSupply -> Name
4903
4904     instance Splittable NameSupply where
4905         split = splitNS
4906
4907
4908     f :: (%ns :: NameSupply) => Env -> Expr -> Expr
4909     f env (Lam x e) = Lam x' (f env e)
4910                     where
4911                       x'   = newName %ns
4912                       env' = extend env x x'
4913     ...more equations for f...
4914 </programlisting>
4915 Notice that the implicit parameter %ns is consumed 
4916 <itemizedlist>
4917 <listitem> <para> once by the call to <literal>newName</literal> </para> </listitem>
4918 <listitem> <para> once by the recursive call to <literal>f</literal> </para></listitem>
4919 </itemizedlist>
4920 </para>
4921 <para>
4922 So the translation done by the type checker makes
4923 the parameter explicit:
4924 <programlisting>
4925     f :: NameSupply -> Env -> Expr -> Expr
4926     f ns env (Lam x e) = Lam x' (f ns1 env e)
4927                        where
4928                          (ns1,ns2) = splitNS ns
4929                          x' = newName ns2
4930                          env = extend env x x'
4931 </programlisting>
4932 Notice the call to 'split' introduced by the type checker.
4933 How did it know to use 'splitNS'?  Because what it really did
4934 was to introduce a call to the overloaded function 'split',
4935 defined by the class <literal>Splittable</literal>:
4936 <programlisting>
4937         class Splittable a where
4938           split :: a -> (a,a)
4939 </programlisting>
4940 The instance for <literal>Splittable NameSupply</literal> tells GHC how to implement
4941 split for name supplies.  But we can simply write
4942 <programlisting>
4943         g x = (x, %ns, %ns)
4944 </programlisting>
4945 and GHC will infer
4946 <programlisting>
4947         g :: (Splittable a, %ns :: a) => b -> (b,a,a)
4948 </programlisting>
4949 The <literal>Splittable</literal> class is built into GHC.  It's exported by module 
4950 <literal>GHC.Exts</literal>.
4951 </para>
4952 <para>
4953 Other points:
4954 <itemizedlist>
4955 <listitem> <para> '<literal>?x</literal>' and '<literal>%x</literal>' 
4956 are entirely distinct implicit parameters: you 
4957   can use them together and they won't interfere with each other. </para>
4958 </listitem>
4959
4960 <listitem> <para> You can bind linear implicit parameters in 'with' clauses. </para> </listitem>
4961
4962 <listitem> <para>You cannot have implicit parameters (whether linear or not)
4963   in the context of a class or instance declaration. </para></listitem>
4964 </itemizedlist>
4965 </para>
4966
4967 <sect3><title>Warnings</title>
4968
4969 <para>
4970 The monomorphism restriction is even more important than usual.
4971 Consider the example above:
4972 <programlisting>
4973     f :: (%ns :: NameSupply) => Env -> Expr -> Expr
4974     f env (Lam x e) = Lam x' (f env e)
4975                     where
4976                       x'   = newName %ns
4977                       env' = extend env x x'
4978 </programlisting>
4979 If we replaced the two occurrences of x' by (newName %ns), which is
4980 usually a harmless thing to do, we get:
4981 <programlisting>
4982     f :: (%ns :: NameSupply) => Env -> Expr -> Expr
4983     f env (Lam x e) = Lam (newName %ns) (f env e)
4984                     where
4985                       env' = extend env x (newName %ns)
4986 </programlisting>
4987 But now the name supply is consumed in <emphasis>three</emphasis> places
4988 (the two calls to newName,and the recursive call to f), so
4989 the result is utterly different.  Urk!  We don't even have 
4990 the beta rule.
4991 </para>
4992 <para>
4993 Well, this is an experimental change.  With implicit
4994 parameters we have already lost beta reduction anyway, and
4995 (as John Launchbury puts it) we can't sensibly reason about
4996 Haskell programs without knowing their typing.
4997 </para>
4998
4999 </sect3>
5000
5001 <sect3><title>Recursive functions</title>
5002 <para>Linear implicit parameters can be particularly tricky when you have a recursive function
5003 Consider
5004 <programlisting>
5005         foo :: %x::T => Int -> [Int]
5006         foo 0 = []
5007         foo n = %x : foo (n-1)
5008 </programlisting>
5009 where T is some type in class Splittable.</para>
5010 <para>
5011 Do you get a list of all the same T's or all different T's
5012 (assuming that split gives two distinct T's back)?
5013 </para><para>
5014 If you supply the type signature, taking advantage of polymorphic
5015 recursion, you get what you'd probably expect.  Here's the
5016 translated term, where the implicit param is made explicit:
5017 <programlisting>
5018         foo x 0 = []
5019         foo x n = let (x1,x2) = split x
5020                   in x1 : foo x2 (n-1)
5021 </programlisting>
5022 But if you don't supply a type signature, GHC uses the Hindley
5023 Milner trick of using a single monomorphic instance of the function
5024 for the recursive calls. That is what makes Hindley Milner type inference
5025 work.  So the translation becomes
5026 <programlisting>
5027         foo x = let
5028                   foom 0 = []
5029                   foom n = x : foom (n-1)
5030                 in
5031                 foom
5032 </programlisting>
5033 Result: 'x' is not split, and you get a list of identical T's.  So the
5034 semantics of the program depends on whether or not foo has a type signature.
5035 Yikes!
5036 </para><para>
5037 You may say that this is a good reason to dislike linear implicit parameters
5038 and you'd be right.  That is why they are an experimental feature. 
5039 </para>
5040 </sect3>
5041
5042 </sect2>
5043
5044 ================ END OF Linear Implicit Parameters commented out -->
5045
5046 <sect2 id="kinding">
5047 <title>Explicitly-kinded quantification</title>
5048
5049 <para>
5050 Haskell infers the kind of each type variable.  Sometimes it is nice to be able
5051 to give the kind explicitly as (machine-checked) documentation, 
5052 just as it is nice to give a type signature for a function.  On some occasions,
5053 it is essential to do so.  For example, in his paper "Restricted Data Types in Haskell" (Haskell Workshop 1999)
5054 John Hughes had to define the data type:
5055 <screen>
5056      data Set cxt a = Set [a]
5057                     | Unused (cxt a -> ())
5058 </screen>
5059 The only use for the <literal>Unused</literal> constructor was to force the correct
5060 kind for the type variable <literal>cxt</literal>.
5061 </para>
5062 <para>
5063 GHC now instead allows you to specify the kind of a type variable directly, wherever
5064 a type variable is explicitly bound, with the flag <option>-XKindSignatures</option>.
5065 </para>
5066 <para>
5067 This flag enables kind signatures in the following places:
5068 <itemizedlist>
5069 <listitem><para><literal>data</literal> declarations:
5070 <screen>
5071   data Set (cxt :: * -> *) a = Set [a]
5072 </screen></para></listitem>
5073 <listitem><para><literal>type</literal> declarations:
5074 <screen>
5075   type T (f :: * -> *) = f Int
5076 </screen></para></listitem>
5077 <listitem><para><literal>class</literal> declarations:
5078 <screen>
5079   class (Eq a) => C (f :: * -> *) a where ...
5080 </screen></para></listitem>
5081 <listitem><para><literal>forall</literal>'s in type signatures:
5082 <screen>
5083   f :: forall (cxt :: * -> *). Set cxt Int
5084 </screen></para></listitem>
5085 </itemizedlist>
5086 </para>
5087
5088 <para>
5089 The parentheses are required.  Some of the spaces are required too, to
5090 separate the lexemes.  If you write <literal>(f::*->*)</literal> you
5091 will get a parse error, because "<literal>::*->*</literal>" is a
5092 single lexeme in Haskell.
5093 </para>
5094
5095 <para>
5096 As part of the same extension, you can put kind annotations in types
5097 as well.  Thus:
5098 <screen>
5099    f :: (Int :: *) -> Int
5100    g :: forall a. a -> (a :: *)
5101 </screen>
5102 The syntax is
5103 <screen>
5104    atype ::= '(' ctype '::' kind ')
5105 </screen>
5106 The parentheses are required.
5107 </para>
5108 </sect2>
5109
5110
5111 <sect2 id="universal-quantification">
5112 <title>Arbitrary-rank polymorphism
5113 </title>
5114
5115 <para>
5116 Haskell type signatures are implicitly quantified.  The new keyword <literal>forall</literal>
5117 allows us to say exactly what this means.  For example:
5118 </para>
5119 <para>
5120 <programlisting>
5121         g :: b -> b
5122 </programlisting>
5123 means this:
5124 <programlisting>
5125         g :: forall b. (b -> b)
5126 </programlisting>
5127 The two are treated identically.
5128 </para>
5129
5130 <para>
5131 However, GHC's type system supports <emphasis>arbitrary-rank</emphasis> 
5132 explicit universal quantification in
5133 types. 
5134 For example, all the following types are legal:
5135 <programlisting>
5136     f1 :: forall a b. a -> b -> a
5137     g1 :: forall a b. (Ord a, Eq  b) => a -> b -> a
5138
5139     f2 :: (forall a. a->a) -> Int -> Int
5140     g2 :: (forall a. Eq a => [a] -> a -> Bool) -> Int -> Int
5141
5142     f3 :: ((forall a. a->a) -> Int) -> Bool -> Bool
5143
5144     f4 :: Int -> (forall a. a -> a)
5145 </programlisting>
5146 Here, <literal>f1</literal> and <literal>g1</literal> are rank-1 types, and
5147 can be written in standard Haskell (e.g. <literal>f1 :: a->b->a</literal>).
5148 The <literal>forall</literal> makes explicit the universal quantification that
5149 is implicitly added by Haskell.
5150 </para>
5151 <para>
5152 The functions <literal>f2</literal> and <literal>g2</literal> have rank-2 types;
5153 the <literal>forall</literal> is on the left of a function arrow.  As <literal>g2</literal>
5154 shows, the polymorphic type on the left of the function arrow can be overloaded.
5155 </para>
5156 <para>
5157 The function <literal>f3</literal> has a rank-3 type;
5158 it has rank-2 types on the left of a function arrow.
5159 </para>
5160 <para>
5161 GHC has three flags to control higher-rank types:
5162 <itemizedlist>
5163 <listitem><para>
5164  <option>-XPolymorphicComponents</option>: data constructors (only) can have polymorphic argument types.
5165 </para></listitem>
5166 <listitem><para>
5167  <option>-XRank2Types</option>: any function (including data constructors) can have a rank-2 type.
5168 </para></listitem>
5169 <listitem><para>
5170  <option>-XRankNTypes</option>: any function (including data constructors) can have an arbitrary-rank type.
5171 That is,  you can nest <literal>forall</literal>s
5172 arbitrarily deep in function arrows.
5173 In particular, a forall-type (also called a "type scheme"),
5174 including an operational type class context, is legal:
5175 <itemizedlist>
5176 <listitem> <para> On the left or right (see <literal>f4</literal>, for example)
5177 of a function arrow </para> </listitem>
5178 <listitem> <para> As the argument of a constructor, or type of a field, in a data type declaration. For
5179 example, any of the <literal>f1,f2,f3,g1,g2</literal> above would be valid
5180 field type signatures.</para> </listitem>
5181 <listitem> <para> As the type of an implicit parameter </para> </listitem>
5182 <listitem> <para> In a pattern type signature (see <xref linkend="scoped-type-variables"/>) </para> </listitem>
5183 </itemizedlist>
5184 </para></listitem>
5185 </itemizedlist>
5186 Of course <literal>forall</literal> becomes a keyword; you can't use <literal>forall</literal> as
5187 a type variable any more!
5188 </para>
5189
5190
5191 <sect3 id="univ">
5192 <title>Examples
5193 </title>
5194
5195 <para>
5196 In a <literal>data</literal> or <literal>newtype</literal> declaration one can quantify
5197 the types of the constructor arguments.  Here are several examples:
5198 </para>
5199
5200 <para>
5201
5202 <programlisting>
5203 data T a = T1 (forall b. b -> b -> b) a
5204
5205 data MonadT m = MkMonad { return :: forall a. a -> m a,
5206                           bind   :: forall a b. m a -> (a -> m b) -> m b
5207                         }
5208
5209 newtype Swizzle = MkSwizzle (Ord a => [a] -> [a])
5210 </programlisting>
5211
5212 </para>
5213
5214 <para>
5215 The constructors have rank-2 types:
5216 </para>
5217
5218 <para>
5219
5220 <programlisting>
5221 T1 :: forall a. (forall b. b -> b -> b) -> a -> T a
5222 MkMonad :: forall m. (forall a. a -> m a)
5223                   -> (forall a b. m a -> (a -> m b) -> m b)
5224                   -> MonadT m
5225 MkSwizzle :: (Ord a => [a] -> [a]) -> Swizzle
5226 </programlisting>
5227
5228 </para>
5229
5230 <para>
5231 Notice that you don't need to use a <literal>forall</literal> if there's an
5232 explicit context.  For example in the first argument of the
5233 constructor <function>MkSwizzle</function>, an implicit "<literal>forall a.</literal>" is
5234 prefixed to the argument type.  The implicit <literal>forall</literal>
5235 quantifies all type variables that are not already in scope, and are
5236 mentioned in the type quantified over.
5237 </para>
5238
5239 <para>
5240 As for type signatures, implicit quantification happens for non-overloaded
5241 types too.  So if you write this:
5242
5243 <programlisting>
5244   data T a = MkT (Either a b) (b -> b)
5245 </programlisting>
5246
5247 it's just as if you had written this:
5248
5249 <programlisting>
5250   data T a = MkT (forall b. Either a b) (forall b. b -> b)
5251 </programlisting>
5252
5253 That is, since the type variable <literal>b</literal> isn't in scope, it's
5254 implicitly universally quantified.  (Arguably, it would be better
5255 to <emphasis>require</emphasis> explicit quantification on constructor arguments
5256 where that is what is wanted.  Feedback welcomed.)
5257 </para>
5258
5259 <para>
5260 You construct values of types <literal>T1, MonadT, Swizzle</literal> by applying
5261 the constructor to suitable values, just as usual.  For example,
5262 </para>
5263
5264 <para>
5265
5266 <programlisting>
5267     a1 :: T Int
5268     a1 = T1 (\xy->x) 3
5269     
5270     a2, a3 :: Swizzle
5271     a2 = MkSwizzle sort
5272     a3 = MkSwizzle reverse
5273     
5274     a4 :: MonadT Maybe
5275     a4 = let r x = Just x
5276              b m k = case m of
5277                        Just y -> k y
5278                        Nothing -> Nothing
5279          in
5280          MkMonad r b
5281
5282     mkTs :: (forall b. b -> b -> b) -> a -> [T a]
5283     mkTs f x y = [T1 f x, T1 f y]
5284 </programlisting>
5285
5286 </para>
5287
5288 <para>
5289 The type of the argument can, as usual, be more general than the type
5290 required, as <literal>(MkSwizzle reverse)</literal> shows.  (<function>reverse</function>
5291 does not need the <literal>Ord</literal> constraint.)
5292 </para>
5293
5294 <para>
5295 When you use pattern matching, the bound variables may now have
5296 polymorphic types.  For example:
5297 </para>
5298
5299 <para>
5300
5301 <programlisting>
5302     f :: T a -> a -> (a, Char)
5303     f (T1 w k) x = (w k x, w 'c' 'd')
5304
5305     g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b]
5306     g (MkSwizzle s) xs f = s (map f (s xs))
5307
5308     h :: MonadT m -> [m a] -> m [a]
5309     h m [] = return m []
5310     h m (x:xs) = bind m x          $ \y ->
5311                  bind m (h m xs)   $ \ys ->
5312                  return m (y:ys)
5313 </programlisting>
5314
5315 </para>
5316
5317 <para>
5318 In the function <function>h</function> we use the record selectors <literal>return</literal>
5319 and <literal>bind</literal> to extract the polymorphic bind and return functions
5320 from the <literal>MonadT</literal> data structure, rather than using pattern
5321 matching.
5322 </para>
5323 </sect3>
5324
5325 <sect3>
5326 <title>Type inference</title>
5327
5328 <para>
5329 In general, type inference for arbitrary-rank types is undecidable.
5330 GHC uses an algorithm proposed by Odersky and Laufer ("Putting type annotations to work", POPL'96)
5331 to get a decidable algorithm by requiring some help from the programmer.
5332 We do not yet have a formal specification of "some help" but the rule is this:
5333 </para>
5334 <para>
5335 <emphasis>For a lambda-bound or case-bound variable, x, either the programmer
5336 provides an explicit polymorphic type for x, or GHC's type inference will assume
5337 that x's type has no foralls in it</emphasis>.
5338 </para>
5339 <para>
5340 What does it mean to "provide" an explicit type for x?  You can do that by 
5341 giving a type signature for x directly, using a pattern type signature
5342 (<xref linkend="scoped-type-variables"/>), thus:
5343 <programlisting>
5344      \ f :: (forall a. a->a) -> (f True, f 'c')
5345 </programlisting>
5346 Alternatively, you can give a type signature to the enclosing
5347 context, which GHC can "push down" to find the type for the variable:
5348 <programlisting>
5349      (\ f -> (f True, f 'c')) :: (forall a. a->a) -> (Bool,Char)
5350 </programlisting>
5351 Here the type signature on the expression can be pushed inwards
5352 to give a type signature for f.  Similarly, and more commonly,
5353 one can give a type signature for the function itself:
5354 <programlisting>
5355      h :: (forall a. a->a) -> (Bool,Char)
5356      h f = (f True, f 'c')
5357 </programlisting>
5358 You don't need to give a type signature if the lambda bound variable
5359 is a constructor argument.  Here is an example we saw earlier:
5360 <programlisting>
5361     f :: T a -> a -> (a, Char)
5362     f (T1 w k) x = (w k x, w 'c' 'd')
5363 </programlisting>
5364 Here we do not need to give a type signature to <literal>w</literal>, because
5365 it is an argument of constructor <literal>T1</literal> and that tells GHC all
5366 it needs to know.
5367 </para>
5368
5369 </sect3>
5370
5371
5372 <sect3 id="implicit-quant">
5373 <title>Implicit quantification</title>
5374
5375 <para>
5376 GHC performs implicit quantification as follows.  <emphasis>At the top level (only) of 
5377 user-written types, if and only if there is no explicit <literal>forall</literal>,
5378 GHC finds all the type variables mentioned in the type that are not already
5379 in scope, and universally quantifies them.</emphasis>  For example, the following pairs are 
5380 equivalent:
5381 <programlisting>
5382   f :: a -> a
5383   f :: forall a. a -> a
5384
5385   g (x::a) = let
5386                 h :: a -> b -> b
5387                 h x y = y
5388              in ...
5389   g (x::a) = let
5390                 h :: forall b. a -> b -> b
5391                 h x y = y
5392              in ...
5393 </programlisting>
5394 </para>
5395 <para>
5396 Notice that GHC does <emphasis>not</emphasis> find the innermost possible quantification
5397 point.  For example:
5398 <programlisting>
5399   f :: (a -> a) -> Int
5400            -- MEANS
5401   f :: forall a. (a -> a) -> Int
5402            -- NOT
5403   f :: (forall a. a -> a) -> Int
5404
5405
5406   g :: (Ord a => a -> a) -> Int
5407            -- MEANS the illegal type
5408   g :: forall a. (Ord a => a -> a) -> Int
5409            -- NOT
5410   g :: (forall a. Ord a => a -> a) -> Int
5411 </programlisting>
5412 The latter produces an illegal type, which you might think is silly,
5413 but at least the rule is simple.  If you want the latter type, you
5414 can write your for-alls explicitly.  Indeed, doing so is strongly advised
5415 for rank-2 types.
5416 </para>
5417 </sect3>
5418 </sect2>
5419
5420
5421 <sect2 id="impredicative-polymorphism">
5422 <title>Impredicative polymorphism
5423 </title>
5424 <para>GHC supports <emphasis>impredicative polymorphism</emphasis>, 
5425 enabled with <option>-XImpredicativeTypes</option>.  
5426 This means
5427 that you can call a polymorphic function at a polymorphic type, and
5428 parameterise data structures over polymorphic types.  For example:
5429 <programlisting>
5430   f :: Maybe (forall a. [a] -> [a]) -> Maybe ([Int], [Char])
5431   f (Just g) = Just (g [3], g "hello")
5432   f Nothing  = Nothing
5433 </programlisting>
5434 Notice here that the <literal>Maybe</literal> type is parameterised by the
5435 <emphasis>polymorphic</emphasis> type <literal>(forall a. [a] ->
5436 [a])</literal>.
5437 </para>
5438 <para>The technical details of this extension are described in the paper
5439 <ulink url="http://research.microsoft.com/%7Esimonpj/papers/boxy/">Boxy types:
5440 type inference for higher-rank types and impredicativity</ulink>,
5441 which appeared at ICFP 2006.  
5442 </para>
5443 </sect2>
5444
5445 <sect2 id="scoped-type-variables">
5446 <title>Lexically scoped type variables
5447 </title>
5448
5449 <para>
5450 GHC supports <emphasis>lexically scoped type variables</emphasis>, without
5451 which some type signatures are simply impossible to write. For example:
5452 <programlisting>
5453 f :: forall a. [a] -> [a]
5454 f xs = ys ++ ys
5455      where
5456        ys :: [a]
5457        ys = reverse xs
5458 </programlisting>
5459 The type signature for <literal>f</literal> brings the type variable <literal>a</literal> into scope,
5460 because of the explicit <literal>forall</literal> (<xref linkend="decl-type-sigs"/>).
5461 The type variables bound by a <literal>forall</literal> scope over
5462 the entire definition of the accompanying value declaration.
5463 In this example, the type variable <literal>a</literal> scopes over the whole 
5464 definition of <literal>f</literal>, including over
5465 the type signature for <varname>ys</varname>. 
5466 In Haskell 98 it is not possible to declare
5467 a type for <varname>ys</varname>; a major benefit of scoped type variables is that
5468 it becomes possible to do so.
5469 </para>
5470 <para>Lexically-scoped type variables are enabled by
5471 <option>-XScopedTypeVariables</option>.  This flag implies <option>-XRelaxedPolyRec</option>.
5472 </para>
5473 <para>Note: GHC 6.6 contains substantial changes to the way that scoped type
5474 variables work, compared to earlier releases.  Read this section
5475 carefully!</para>
5476
5477 <sect3>
5478 <title>Overview</title>
5479
5480 <para>The design follows the following principles
5481 <itemizedlist>
5482 <listitem><para>A scoped type variable stands for a type <emphasis>variable</emphasis>, and not for
5483 a <emphasis>type</emphasis>. (This is a change from GHC's earlier
5484 design.)</para></listitem>
5485 <listitem><para>Furthermore, distinct lexical type variables stand for distinct
5486 type variables.  This means that every programmer-written type signature
5487 (including one that contains free scoped type variables) denotes a
5488 <emphasis>rigid</emphasis> type; that is, the type is fully known to the type
5489 checker, and no inference is involved.</para></listitem>
5490 <listitem><para>Lexical type variables may be alpha-renamed freely, without
5491 changing the program.</para></listitem>
5492 </itemizedlist>
5493 </para>
5494 <para>
5495 A <emphasis>lexically scoped type variable</emphasis> can be bound by:
5496 <itemizedlist>
5497 <listitem><para>A declaration type signature (<xref linkend="decl-type-sigs"/>)</para></listitem>
5498 <listitem><para>An expression type signature (<xref linkend="exp-type-sigs"/>)</para></listitem>
5499 <listitem><para>A pattern type signature (<xref linkend="pattern-type-sigs"/>)</para></listitem>
5500 <listitem><para>Class and instance declarations (<xref linkend="cls-inst-scoped-tyvars"/>)</para></listitem>
5501 </itemizedlist>
5502 </para>
5503 <para>
5504 In Haskell, a programmer-written type signature is implicitly quantified over
5505 its free type variables (<ulink
5506 url="http://www.haskell.org/onlinereport/decls.html#sect4.1.2">Section
5507 4.1.2</ulink> 
5508 of the Haskell Report).
5509 Lexically scoped type variables affect this implicit quantification rules
5510 as follows: any type variable that is in scope is <emphasis>not</emphasis> universally
5511 quantified. For example, if type variable <literal>a</literal> is in scope,
5512 then
5513 <programlisting>
5514   (e :: a -> a)     means     (e :: a -> a)
5515   (e :: b -> b)     means     (e :: forall b. b->b)
5516   (e :: a -> b)     means     (e :: forall b. a->b)
5517 </programlisting>
5518 </para>
5519
5520
5521 </sect3>
5522
5523
5524 <sect3 id="decl-type-sigs">
5525 <title>Declaration type signatures</title>
5526 <para>A declaration type signature that has <emphasis>explicit</emphasis>
5527 quantification (using <literal>forall</literal>) brings into scope the
5528 explicitly-quantified
5529 type variables, in the definition of the named function.  For example:
5530 <programlisting>
5531   f :: forall a. [a] -> [a]
5532   f (x:xs) = xs ++ [ x :: a ]
5533 </programlisting>
5534 The "<literal>forall a</literal>" brings "<literal>a</literal>" into scope in
5535 the definition of "<literal>f</literal>".
5536 </para>
5537 <para>This only happens if:
5538 <itemizedlist>
5539 <listitem><para> The quantification in <literal>f</literal>'s type
5540 signature is explicit.  For example:
5541 <programlisting>
5542   g :: [a] -> [a]
5543   g (x:xs) = xs ++ [ x :: a ]
5544 </programlisting>
5545 This program will be rejected, because "<literal>a</literal>" does not scope
5546 over the definition of "<literal>f</literal>", so "<literal>x::a</literal>"
5547 means "<literal>x::forall a. a</literal>" by Haskell's usual implicit
5548 quantification rules.
5549 </para></listitem>
5550 <listitem><para> The signature gives a type for a function binding or a bare variable binding, 
5551 not a pattern binding.
5552 For example:
5553 <programlisting>
5554   f1 :: forall a. [a] -> [a]
5555   f1 (x:xs) = xs ++ [ x :: a ]   -- OK
5556
5557   f2 :: forall a. [a] -> [a]
5558   f2 = \(x:xs) -> xs ++ [ x :: a ]   -- OK
5559
5560   f3 :: forall a. [a] -> [a] 
5561   Just f3 = Just (\(x:xs) -> xs ++ [ x :: a ])   -- Not OK!
5562 </programlisting>
5563 The binding for <literal>f3</literal> is a pattern binding, and so its type signature
5564 does not bring <literal>a</literal> into scope.   However <literal>f1</literal> is a
5565 function binding, and <literal>f2</literal> binds a bare variable; in both cases
5566 the type signature brings <literal>a</literal> into scope.
5567 </para></listitem>
5568 </itemizedlist>
5569 </para>
5570 </sect3>
5571
5572 <sect3 id="exp-type-sigs">
5573 <title>Expression type signatures</title>
5574
5575 <para>An expression type signature that has <emphasis>explicit</emphasis>
5576 quantification (using <literal>forall</literal>) brings into scope the
5577 explicitly-quantified
5578 type variables, in the annotated expression.  For example:
5579 <programlisting>
5580   f = runST ( (op >>= \(x :: STRef s Int) -> g x) :: forall s. ST s Bool )
5581 </programlisting>
5582 Here, the type signature <literal>forall a. ST s Bool</literal> brings the 
5583 type variable <literal>s</literal> into scope, in the annotated expression 
5584 <literal>(op >>= \(x :: STRef s Int) -> g x)</literal>.
5585 </para>
5586
5587 </sect3>
5588
5589 <sect3 id="pattern-type-sigs">
5590 <title>Pattern type signatures</title>
5591 <para>
5592 A type signature may occur in any pattern; this is a <emphasis>pattern type
5593 signature</emphasis>. 
5594 For example:
5595 <programlisting>
5596   -- f and g assume that 'a' is already in scope
5597   f = \(x::Int, y::a) -> x
5598   g (x::a) = x
5599   h ((x,y) :: (Int,Bool)) = (y,x)
5600 </programlisting>
5601 In the case where all the type variables in the pattern type signature are
5602 already in scope (i.e. bound by the enclosing context), matters are simple: the
5603 signature simply constrains the type of the pattern in the obvious way.
5604 </para>
5605 <para>
5606 Unlike expression and declaration type signatures, pattern type signatures are not implicitly generalised.
5607 The pattern in a <emphasis>pattern binding</emphasis> may only mention type variables
5608 that are already in scope.  For example:
5609 <programlisting>
5610   f :: forall a. [a] -> (Int, [a])
5611   f xs = (n, zs)
5612     where
5613       (ys::[a], n) = (reverse xs, length xs) -- OK
5614       zs::[a] = xs ++ ys                     -- OK
5615
5616       Just (v::b) = ...  -- Not OK; b is not in scope
5617 </programlisting>
5618 Here, the pattern signatures for <literal>ys</literal> and <literal>zs</literal>
5619 are fine, but the one for <literal>v</literal> is not because <literal>b</literal> is
5620 not in scope. 
5621 </para>
5622 <para>
5623 However, in all patterns <emphasis>other</emphasis> than pattern bindings, a pattern
5624 type signature may mention a type variable that is not in scope; in this case,
5625 <emphasis>the signature brings that type variable into scope</emphasis>.
5626 This is particularly important for existential data constructors.  For example:
5627 <programlisting>
5628   data T = forall a. MkT [a]
5629
5630   k :: T -> T
5631   k (MkT [t::a]) = MkT t3
5632                  where
5633                    t3::[a] = [t,t,t]
5634 </programlisting>
5635 Here, the pattern type signature <literal>(t::a)</literal> mentions a lexical type
5636 variable that is not already in scope.  Indeed, it <emphasis>cannot</emphasis> already be in scope,
5637 because it is bound by the pattern match.  GHC's rule is that in this situation
5638 (and only then), a pattern type signature can mention a type variable that is
5639 not already in scope; the effect is to bring it into scope, standing for the
5640 existentially-bound type variable.
5641 </para>
5642 <para>
5643 When a pattern type signature binds a type variable in this way, GHC insists that the 
5644 type variable is bound to a <emphasis>rigid</emphasis>, or fully-known, type variable.
5645 This means that any user-written type signature always stands for a completely known type.
5646 </para>
5647 <para>
5648 If all this seems a little odd, we think so too.  But we must have
5649 <emphasis>some</emphasis> way to bring such type variables into scope, else we
5650 could not name existentially-bound type variables in subsequent type signatures.
5651 </para>
5652 <para>
5653 This is (now) the <emphasis>only</emphasis> situation in which a pattern type 
5654 signature is allowed to mention a lexical variable that is not already in
5655 scope.
5656 For example, both <literal>f</literal> and <literal>g</literal> would be
5657 illegal if <literal>a</literal> was not already in scope.
5658 </para>
5659
5660
5661 </sect3>
5662
5663 <!-- ==================== Commented out part about result type signatures 
5664
5665 <sect3 id="result-type-sigs">
5666 <title>Result type signatures</title>
5667
5668 <para>
5669 The result type of a function, lambda, or case expression alternative can be given a signature, thus:
5670
5671 <programlisting>
5672   {- f assumes that 'a' is already in scope -}
5673   f x y :: [a] = [x,y,x]
5674
5675   g = \ x :: [Int] -> [3,4]
5676
5677   h :: forall a. [a] -> a
5678   h xs = case xs of
5679             (y:ys) :: a -> y
5680 </programlisting>
5681 The final <literal>:: [a]</literal> after the patterns of <literal>f</literal> gives the type of 
5682 the result of the function.  Similarly, the body of the lambda in the RHS of
5683 <literal>g</literal> is <literal>[Int]</literal>, and the RHS of the case
5684 alternative in <literal>h</literal> is <literal>a</literal>.
5685 </para>
5686 <para> A result type signature never brings new type variables into scope.</para>
5687 <para>
5688 There are a couple of syntactic wrinkles.  First, notice that all three
5689 examples would parse quite differently with parentheses:
5690 <programlisting>
5691   {- f assumes that 'a' is already in scope -}
5692   f x (y :: [a]) = [x,y,x]
5693
5694   g = \ (x :: [Int]) -> [3,4]
5695
5696   h :: forall a. [a] -> a
5697   h xs = case xs of
5698             ((y:ys) :: a) -> y
5699 </programlisting>
5700 Now the signature is on the <emphasis>pattern</emphasis>; and
5701 <literal>h</literal> would certainly be ill-typed (since the pattern
5702 <literal>(y:ys)</literal> cannot have the type <literal>a</literal>.
5703
5704 Second, to avoid ambiguity, the type after the &ldquo;<literal>::</literal>&rdquo; in a result
5705 pattern signature on a lambda or <literal>case</literal> must be atomic (i.e. a single
5706 token or a parenthesised type of some sort).  To see why,
5707 consider how one would parse this:
5708 <programlisting>
5709   \ x :: a -> b -> x
5710 </programlisting>
5711 </para>
5712 </sect3>
5713
5714  -->
5715
5716 <sect3 id="cls-inst-scoped-tyvars">
5717 <title>Class and instance declarations</title>
5718 <para>
5719
5720 The type variables in the head of a <literal>class</literal> or <literal>instance</literal> declaration
5721 scope over the methods defined in the <literal>where</literal> part.  For example:
5722
5723
5724 <programlisting>
5725   class C a where
5726     op :: [a] -> a
5727
5728     op xs = let ys::[a]
5729                 ys = reverse xs
5730             in
5731             head ys
5732 </programlisting>
5733 </para>
5734 </sect3>
5735
5736 </sect2>
5737
5738
5739 <sect2 id="typing-binds">
5740 <title>Generalised typing of mutually recursive bindings</title>
5741
5742 <para>
5743 The Haskell Report specifies that a group of bindings (at top level, or in a
5744 <literal>let</literal> or <literal>where</literal>) should be sorted into
5745 strongly-connected components, and then type-checked in dependency order
5746 (<ulink url="http://www.haskell.org/onlinereport/decls.html#sect4.5.1">Haskell
5747 Report, Section 4.5.1</ulink>).  
5748 As each group is type-checked, any binders of the group that
5749 have
5750 an explicit type signature are put in the type environment with the specified
5751 polymorphic type,
5752 and all others are monomorphic until the group is generalised 
5753 (<ulink url="http://www.haskell.org/onlinereport/decls.html#sect4.5.2">Haskell Report, Section 4.5.2</ulink>).
5754 </para>
5755
5756 <para>Following a suggestion of Mark Jones, in his paper
5757 <ulink url="http://citeseer.ist.psu.edu/424440.html">Typing Haskell in
5758 Haskell</ulink>,
5759 GHC implements a more general scheme.  If <option>-XRelaxedPolyRec</option> is
5760 specified:
5761 <emphasis>the dependency analysis ignores references to variables that have an explicit
5762 type signature</emphasis>.
5763 As a result of this refined dependency analysis, the dependency groups are smaller, and more bindings will
5764 typecheck.  For example, consider:
5765 <programlisting>
5766   f :: Eq a =&gt; a -> Bool
5767   f x = (x == x) || g True || g "Yes"
5768   
5769   g y = (y &lt;= y) || f True
5770 </programlisting>
5771 This is rejected by Haskell 98, but under Jones's scheme the definition for
5772 <literal>g</literal> is typechecked first, separately from that for
5773 <literal>f</literal>,
5774 because the reference to <literal>f</literal> in <literal>g</literal>'s right
5775 hand side is ignored by the dependency analysis.  Then <literal>g</literal>'s
5776 type is generalised, to get
5777 <programlisting>
5778   g :: Ord a =&gt; a -> Bool
5779 </programlisting>
5780 Now, the definition for <literal>f</literal> is typechecked, with this type for
5781 <literal>g</literal> in the type environment.
5782 </para>
5783
5784 <para>
5785 The same refined dependency analysis also allows the type signatures of 
5786 mutually-recursive functions to have different contexts, something that is illegal in
5787 Haskell 98 (Section 4.5.2, last sentence).  With
5788 <option>-XRelaxedPolyRec</option>
5789 GHC only insists that the type signatures of a <emphasis>refined</emphasis> group have identical
5790 type signatures; in practice this means that only variables bound by the same
5791 pattern binding must have the same context.  For example, this is fine:
5792 <programlisting>
5793   f :: Eq a =&gt; a -> Bool
5794   f x = (x == x) || g True
5795   
5796   g :: Ord a =&gt; a -> Bool
5797   g y = (y &lt;= y) || f True
5798 </programlisting>
5799 </para>
5800 </sect2>
5801
5802 </sect1>
5803 <!-- ==================== End of type system extensions =================  -->
5804   
5805 <!-- ====================== TEMPLATE HASKELL =======================  -->
5806
5807 <sect1 id="template-haskell">
5808 <title>Template Haskell</title>
5809
5810 <para>Template Haskell allows you to do compile-time meta-programming in
5811 Haskell.  
5812 The background to
5813 the main technical innovations is discussed in "<ulink
5814 url="http://research.microsoft.com/~simonpj/papers/meta-haskell/">
5815 Template Meta-programming for Haskell</ulink>" (Proc Haskell Workshop 2002).
5816 </para>
5817 <para>
5818 There is a Wiki page about
5819 Template Haskell at <ulink url="http://www.haskell.org/haskellwiki/Template_Haskell">
5820 http://www.haskell.org/haskellwiki/Template_Haskell</ulink>, and that is the best place to look for
5821 further details.
5822 You may also 
5823 consult the <ulink
5824 url="http://www.haskell.org/ghc/docs/latest/html/libraries/index.html">online
5825 Haskell library reference material</ulink> 
5826 (look for module <literal>Language.Haskell.TH</literal>).
5827 Many changes to the original design are described in 
5828       <ulink url="http://research.microsoft.com/~simonpj/papers/meta-haskell/notes2.ps">
5829 Notes on Template Haskell version 2</ulink>.
5830 Not all of these changes are in GHC, however.
5831 </para>
5832
5833 <para> The first example from that paper is set out below (<xref linkend="th-example"/>) 
5834 as a worked example to help get you started. 
5835 </para>
5836
5837 <para>
5838 The documentation here describes the realisation of Template Haskell in GHC.  It is not detailed enough to 
5839 understand Template Haskell; see the <ulink url="http://haskell.org/haskellwiki/Template_Haskell">
5840 Wiki page</ulink>.
5841 </para>
5842
5843     <sect2>
5844       <title>Syntax</title>
5845
5846       <para> Template Haskell has the following new syntactic
5847       constructions.  You need to use the flag
5848       <option>-XTemplateHaskell</option>
5849         <indexterm><primary><option>-XTemplateHaskell</option></primary>
5850       </indexterm>to switch these syntactic extensions on
5851       (<option>-XTemplateHaskell</option> is no longer implied by
5852       <option>-fglasgow-exts</option>).</para>
5853
5854         <itemizedlist>
5855               <listitem><para>
5856                   A splice is written <literal>$x</literal>, where <literal>x</literal> is an
5857                   identifier, or <literal>$(...)</literal>, where the "..." is an arbitrary expression.
5858                   There must be no space between the "$" and the identifier or parenthesis.  This use
5859                   of "$" overrides its meaning as an infix operator, just as "M.x" overrides the meaning
5860                   of "." as an infix operator.  If you want the infix operator, put spaces around it.
5861                   </para>
5862               <para> A splice can occur in place of 
5863                   <itemizedlist>
5864                     <listitem><para> an expression; the spliced expression must
5865                     have type <literal>Q Exp</literal></para></listitem>
5866                     <listitem><para> an type; the spliced expression must
5867                     have type <literal>Q Typ</literal></para></listitem>
5868                     <listitem><para> a list of top-level declarations; the spliced expression must have type <literal>Q [Dec]</literal></para></listitem>
5869                     </itemizedlist>
5870                 </para>
5871             Inside a splice you can can only call functions defined in imported modules,
5872         not functions defined elsewhere in the same module.</listitem>
5873
5874
5875               <listitem><para>
5876                   A expression quotation is written in Oxford brackets, thus:
5877                   <itemizedlist>
5878                     <listitem><para> <literal>[| ... |]</literal>, where the "..." is an expression; 
5879                              the quotation has type <literal>Q Exp</literal>.</para></listitem>
5880                     <listitem><para> <literal>[d| ... |]</literal>, where the "..." is a list of top-level declarations;
5881                              the quotation has type <literal>Q [Dec]</literal>.</para></listitem>
5882                     <listitem><para> <literal>[t| ... |]</literal>, where the "..." is a type;
5883                              the quotation has type <literal>Q Typ</literal>.</para></listitem>
5884                   </itemizedlist></para></listitem>
5885
5886               <listitem><para>
5887                   A quasi-quotation can appear in either a pattern context or an
5888                   expression context and is also written in Oxford brackets:
5889                   <itemizedlist>
5890                     <listitem><para> <literal>[:<replaceable>varid</replaceable>| ... |]</literal>,
5891                         where the "..." is an arbitrary string; a full description of the
5892                         quasi-quotation facility is given in <xref linkend="th-quasiquotation"/>.</para></listitem>
5893                   </itemizedlist></para></listitem>
5894
5895               <listitem><para>
5896                   A name can be quoted with either one or two prefix single quotes:
5897                   <itemizedlist>
5898                     <listitem><para> <literal>'f</literal> has type <literal>Name</literal>, and names the function <literal>f</literal>.
5899                   Similarly <literal>'C</literal> has type <literal>Name</literal> and names the data constructor <literal>C</literal>.
5900                   In general <literal>'</literal><replaceable>thing</replaceable> interprets <replaceable>thing</replaceable> in an expression context.
5901                      </para></listitem> 
5902                     <listitem><para> <literal>''T</literal> has type <literal>Name</literal>, and names the type constructor  <literal>T</literal>.
5903                   That is, <literal>''</literal><replaceable>thing</replaceable> interprets <replaceable>thing</replaceable> in a type context.
5904                      </para></listitem> 
5905                   </itemizedlist>
5906                   These <literal>Names</literal> can be used to construct Template Haskell expressions, patterns, declarations etc.  They
5907                   may also be given as an argument to the <literal>reify</literal> function.
5908                  </para>
5909                 </listitem>
5910
5911                   
5912         </itemizedlist>
5913 (Compared to the original paper, there are many differences of detail.
5914 The syntax for a declaration splice uses "<literal>$</literal>" not "<literal>splice</literal>".
5915 The type of the enclosed expression must be  <literal>Q [Dec]</literal>, not  <literal>[Q Dec]</literal>.
5916 Pattern splices and quotations are not implemented.)
5917
5918 </sect2>
5919
5920 <sect2>  <title> Using Template Haskell </title>
5921 <para>
5922 <itemizedlist>
5923     <listitem><para>
5924     The data types and monadic constructor functions for Template Haskell are in the library
5925     <literal>Language.Haskell.THSyntax</literal>.
5926     </para></listitem>
5927
5928     <listitem><para>
5929     You can only run a function at compile time if it is imported from another module.  That is,
5930             you can't define a function in a module, and call it from within a splice in the same module.
5931             (It would make sense to do so, but it's hard to implement.)
5932    </para></listitem>
5933
5934    <listitem><para>
5935    You can only run a function at compile time if it is imported
5936    from another module <emphasis>that is not part of a mutually-recursive group of modules
5937    that includes the module currently being compiled</emphasis>.  Furthermore, all of the modules of 
5938    the mutually-recursive group must be reachable by non-SOURCE imports from the module where the
5939    splice is to be run.</para>
5940    <para>
5941    For example, when compiling module A,
5942    you can only run Template Haskell functions imported from B if B does not import A (directly or indirectly).
5943    The reason should be clear: to run B we must compile and run A, but we are currently type-checking A.
5944    </para></listitem>
5945
5946     <listitem><para>
5947             The flag <literal>-ddump-splices</literal> shows the expansion of all top-level splices as they happen.
5948    </para></listitem>
5949     <listitem><para>
5950             If you are building GHC from source, you need at least a stage-2 bootstrap compiler to
5951               run Template Haskell.  A stage-1 compiler will reject the TH constructs.  Reason: TH
5952               compiles and runs a program, and then looks at the result.  So it's important that
5953               the program it compiles produces results whose representations are identical to
5954               those of the compiler itself.
5955    </para></listitem>
5956 </itemizedlist>
5957 </para>
5958 <para> Template Haskell works in any mode (<literal>--make</literal>, <literal>--interactive</literal>,
5959         or file-at-a-time).  There used to be a restriction to the former two, but that restriction 
5960         has been lifted.
5961 </para>
5962 </sect2>
5963  
5964 <sect2 id="th-example">  <title> A Template Haskell Worked Example </title>
5965 <para>To help you get over the confidence barrier, try out this skeletal worked example.
5966   First cut and paste the two modules below into "Main.hs" and "Printf.hs":</para>
5967
5968 <programlisting>
5969
5970 {- Main.hs -}
5971 module Main where
5972
5973 -- Import our template "pr"
5974 import Printf ( pr )
5975
5976 -- The splice operator $ takes the Haskell source code
5977 -- generated at compile time by "pr" and splices it into
5978 -- the argument of "putStrLn".
5979 main = putStrLn ( $(pr "Hello") )
5980
5981
5982 {- Printf.hs -}
5983 module Printf where
5984
5985 -- Skeletal printf from the paper.
5986 -- It needs to be in a separate module to the one where
5987 -- you intend to use it.
5988
5989 -- Import some Template Haskell syntax
5990 import Language.Haskell.TH
5991
5992 -- Describe a format string
5993 data Format = D | S | L String
5994
5995 -- Parse a format string.  This is left largely to you
5996 -- as we are here interested in building our first ever
5997 -- Template Haskell program and not in building printf.
5998 parse :: String -> [Format]
5999 parse s   = [ L s ]
6000
6001 -- Generate Haskell source code from a parsed representation
6002 -- of the format string.  This code will be spliced into
6003 -- the module which calls "pr", at compile time.
6004 gen :: [Format] -> Q Exp
6005 gen [D]   = [| \n -> show n |]
6006 gen [S]   = [| \s -> s |]
6007 gen [L s] = stringE s
6008
6009 -- Here we generate the Haskell code for the splice
6010 -- from an input format string.
6011 pr :: String -> Q Exp
6012 pr s = gen (parse s)
6013 </programlisting>
6014
6015 <para>Now run the compiler (here we are a Cygwin prompt on Windows):
6016 </para>
6017 <programlisting>
6018 $ ghc --make -XTemplateHaskell main.hs -o main.exe
6019 </programlisting>
6020
6021 <para>Run "main.exe" and here is your output:</para>
6022
6023 <programlisting>
6024 $ ./main
6025 Hello
6026 </programlisting>
6027
6028 </sect2>
6029
6030 <sect2>
6031 <title>Using Template Haskell with Profiling</title>
6032 <indexterm><primary>profiling</primary><secondary>with Template Haskell</secondary></indexterm>
6033  
6034 <para>Template Haskell relies on GHC's built-in bytecode compiler and
6035 interpreter to run the splice expressions.  The bytecode interpreter
6036 runs the compiled expression on top of the same runtime on which GHC
6037 itself is running; this means that the compiled code referred to by
6038 the interpreted expression must be compatible with this runtime, and
6039 in particular this means that object code that is compiled for
6040 profiling <emphasis>cannot</emphasis> be loaded and used by a splice
6041 expression, because profiled object code is only compatible with the
6042 profiling version of the runtime.</para>
6043
6044 <para>This causes difficulties if you have a multi-module program
6045 containing Template Haskell code and you need to compile it for
6046 profiling, because GHC cannot load the profiled object code and use it
6047 when executing the splices.  Fortunately GHC provides a workaround.
6048 The basic idea is to compile the program twice:</para>
6049
6050 <orderedlist>
6051 <listitem>
6052   <para>Compile the program or library first the normal way, without
6053   <option>-prof</option><indexterm><primary><option>-prof</option></primary></indexterm>.</para>
6054 </listitem>
6055 <listitem>
6056   <para>Then compile it again with <option>-prof</option>, and
6057   additionally use <option>-osuf
6058   p_o</option><indexterm><primary><option>-osuf</option></primary></indexterm>
6059   to name the object files differently (you can choose any suffix
6060   that isn't the normal object suffix here).  GHC will automatically
6061   load the object files built in the first step when executing splice
6062   expressions.  If you omit the <option>-osuf</option> flag when
6063   building with <option>-prof</option> and Template Haskell is used,
6064   GHC will emit an error message. </para>
6065 </listitem>
6066 </orderedlist>
6067 </sect2>
6068
6069 <sect2 id="th-quasiquotation">  <title> Template Haskell Quasi-quotation </title>
6070 <para>Quasi-quotation allows patterns and expressions to be written using
6071 programmer-defined concrete syntax; the motivation behind the extension and
6072 several examples are documented in
6073 "<ulink url="http://www.eecs.harvard.edu/~mainland/ghc-quasiquoting/">Why It's
6074 Nice to be Quoted: Quasiquoting for Haskell</ulink>" (Proc Haskell Workshop
6075 2007). The example below shows how to write a quasiquoter for a simple
6076 expression language.</para>
6077
6078 <para>
6079 In the example, the quasiquoter <literal>expr</literal> is bound to a value of
6080 type <literal>Language.Haskell.TH.Quote.QuasiQuoter</literal> which contains two
6081 functions for quoting expressions and patterns, respectively. The first argument
6082 to each quoter is the (arbitrary) string enclosed in the Oxford brackets. The
6083 context of the quasi-quotation statement determines which of the two parsers is
6084 called: if the quasi-quotation occurs in an expression context, the expression
6085 parser is called, and if it occurs in a pattern context, the pattern parser is
6086 called.</para>
6087
6088 <para>
6089 Note that in the example we make use of an antiquoted
6090 variable <literal>n</literal>, indicated by the syntax <literal>'int:n</literal>
6091 (this syntax for anti-quotation was defined by the parser's
6092 author, <emphasis>not</emphasis> by GHC). This binds <literal>n</literal> to the
6093 integer value argument of the constructor <literal>IntExpr</literal> when
6094 pattern matching. Please see the referenced paper for further details regarding
6095 anti-quotation as well as the description of a technique that uses SYB to
6096 leverage a single parser of type <literal>String -> a</literal> to generate both
6097 an expression parser that returns a value of type <literal>Q Exp</literal> and a
6098 pattern parser that returns a value of type <literal>Q Pat</literal>.
6099 </para>
6100
6101 <para>In general, a quasi-quote has the form
6102 <literal>[$<replaceable>quoter</replaceable>| <replaceable>string</replaceable> |]</literal>.
6103 The <replaceable>quoter</replaceable> must be the name of an imported quoter; it
6104 cannot be an arbitrary expression.  The quoted <replaceable>string</replaceable> 
6105 can be arbitrary, and may contain newlines.
6106 </para>
6107 <para>
6108 Quasiquoters must obey the same stage restrictions as Template Haskell, e.g., in
6109 the example, <literal>expr</literal> cannot be defined
6110 in <literal>Main.hs</literal> where it is used, but must be imported.
6111 </para>
6112
6113 <programlisting>
6114
6115 {- Main.hs -}
6116 module Main where
6117
6118 import Expr
6119
6120 main :: IO ()
6121 main = do { print $ eval [$expr|1 + 2|]
6122           ; case IntExpr 1 of
6123               { [$expr|'int:n|] -> print n
6124               ;  _              -> return ()
6125               }
6126           }
6127
6128
6129 {- Expr.hs -}
6130 module Expr where
6131
6132 import qualified Language.Haskell.TH as TH
6133 import Language.Haskell.TH.Quote
6134
6135 data Expr  =  IntExpr Integer
6136            |  AntiIntExpr String
6137            |  BinopExpr BinOp Expr Expr
6138            |  AntiExpr String
6139     deriving(Show, Typeable, Data)
6140
6141 data BinOp  =  AddOp
6142             |  SubOp
6143             |  MulOp
6144             |  DivOp
6145     deriving(Show, Typeable, Data)
6146
6147 eval :: Expr -> Integer
6148 eval (IntExpr n)        = n
6149 eval (BinopExpr op x y) = (opToFun op) (eval x) (eval y)
6150   where
6151     opToFun AddOp = (+)
6152     opToFun SubOp = (-)
6153     opToFun MulOp = (*)
6154     opToFun DivOp = div
6155
6156 expr = QuasiQuoter parseExprExp parseExprPat
6157
6158 -- Parse an Expr, returning its representation as
6159 -- either a Q Exp or a Q Pat. See the referenced paper
6160 -- for how to use SYB to do this by writing a single
6161 -- parser of type String -> Expr instead of two
6162 -- separate parsers.
6163
6164 parseExprExp :: String -> Q Exp
6165 parseExprExp ...
6166
6167 parseExprPat :: String -> Q Pat
6168 parseExprPat ...
6169 </programlisting>
6170
6171 <para>Now run the compiler:
6172 </para>
6173 <programlisting>
6174 $ ghc --make -XQuasiQuotes Main.hs -o main
6175 </programlisting>
6176
6177 <para>Run "main" and here is your output:</para>
6178
6179 <programlisting>
6180 $ ./main
6181 3
6182 1
6183 </programlisting>
6184
6185 </sect2>
6186
6187 </sect1>
6188
6189 <!-- ===================== Arrow notation ===================  -->
6190
6191 <sect1 id="arrow-notation">
6192 <title>Arrow notation
6193 </title>
6194
6195 <para>Arrows are a generalization of monads introduced by John Hughes.
6196 For more details, see
6197 <itemizedlist>
6198
6199 <listitem>
6200 <para>
6201 &ldquo;Generalising Monads to Arrows&rdquo;,
6202 John Hughes, in <citetitle>Science of Computer Programming</citetitle> 37,
6203 pp67&ndash;111, May 2000.
6204 The paper that introduced arrows: a friendly introduction, motivated with
6205 programming examples.
6206 </para>
6207 </listitem>
6208
6209 <listitem>
6210 <para>
6211 &ldquo;<ulink url="http://www.soi.city.ac.uk/~ross/papers/notation.html">A New Notation for Arrows</ulink>&rdquo;,
6212 Ross Paterson, in <citetitle>ICFP</citetitle>, Sep 2001.
6213 Introduced the notation described here.
6214 </para>
6215 </listitem>
6216
6217 <listitem>
6218 <para>
6219 &ldquo;<ulink url="http://www.soi.city.ac.uk/~ross/papers/fop.html">Arrows and Computation</ulink>&rdquo;,
6220 Ross Paterson, in <citetitle>The Fun of Programming</citetitle>,
6221 Palgrave, 2003.
6222 </para>
6223 </listitem>
6224
6225 <listitem>
6226 <para>
6227 &ldquo;<ulink url="http://www.cs.chalmers.se/~rjmh/afp-arrows.pdf">Programming with Arrows</ulink>&rdquo;,
6228 John Hughes, in <citetitle>5th International Summer School on
6229 Advanced Functional Programming</citetitle>,
6230 <citetitle>Lecture Notes in Computer Science</citetitle> vol. 3622,
6231 Springer, 2004.
6232 This paper includes another introduction to the notation,
6233 with practical examples.
6234 </para>
6235 </listitem>
6236
6237 <listitem>
6238 <para>
6239 &ldquo;<ulink url="http://www.haskell.org/ghc/docs/papers/arrow-rules.pdf">Type and Translation Rules for Arrow Notation in GHC</ulink>&rdquo;,
6240 Ross Paterson and Simon Peyton Jones, September 16, 2004.
6241 A terse enumeration of the formal rules used
6242 (extracted from comments in the source code).
6243 </para>
6244 </listitem>
6245
6246 <listitem>
6247 <para>
6248 The arrows web page at
6249 <ulink url="http://www.haskell.org/arrows/"><literal>http://www.haskell.org/arrows/</literal></ulink>.
6250 </para>
6251 </listitem>
6252
6253 </itemizedlist>
6254 With the <option>-XArrows</option> flag, GHC supports the arrow
6255 notation described in the second of these papers,
6256 translating it using combinators from the
6257 <ulink url="../libraries/base/Control-Arrow.html"><literal>Control.Arrow</literal></ulink>
6258 module.
6259 What follows is a brief introduction to the notation;
6260 it won't make much sense unless you've read Hughes's paper.
6261 </para>
6262
6263 <para>The extension adds a new kind of expression for defining arrows:
6264 <screen>
6265 <replaceable>exp</replaceable><superscript>10</superscript> ::= ...
6266        |  proc <replaceable>apat</replaceable> -> <replaceable>cmd</replaceable>
6267 </screen>
6268 where <literal>proc</literal> is a new keyword.
6269 The variables of the pattern are bound in the body of the 
6270 <literal>proc</literal>-expression,
6271 which is a new sort of thing called a <firstterm>command</firstterm>.
6272 The syntax of commands is as follows:
6273 <screen>
6274 <replaceable>cmd</replaceable>   ::= <replaceable>exp</replaceable><superscript>10</superscript> -&lt;  <replaceable>exp</replaceable>
6275        |  <replaceable>exp</replaceable><superscript>10</superscript> -&lt;&lt; <replaceable>exp</replaceable>
6276        |  <replaceable>cmd</replaceable><superscript>0</superscript>
6277 </screen>
6278 with <replaceable>cmd</replaceable><superscript>0</superscript> up to
6279 <replaceable>cmd</replaceable><superscript>9</superscript> defined using
6280 infix operators as for expressions, and
6281 <screen>
6282 <replaceable>cmd</replaceable><superscript>10</superscript> ::= \ <replaceable>apat</replaceable> ... <replaceable>apat</replaceable> -> <replaceable>cmd</replaceable>
6283        |  let <replaceable>decls</replaceable> in <replaceable>cmd</replaceable>
6284        |  if <replaceable>exp</replaceable> then <replaceable>cmd</replaceable> else <replaceable>cmd</replaceable>
6285        |  case <replaceable>exp</replaceable> of { <replaceable>calts</replaceable> }
6286        |  do { <replaceable>cstmt</replaceable> ; ... <replaceable>cstmt</replaceable> ; <replaceable>cmd</replaceable> }
6287        |  <replaceable>fcmd</replaceable>
6288
6289 <replaceable>fcmd</replaceable>  ::= <replaceable>fcmd</replaceable> <replaceable>aexp</replaceable>
6290        |  ( <replaceable>cmd</replaceable> )
6291        |  (| <replaceable>aexp</replaceable> <replaceable>cmd</replaceable> ... <replaceable>cmd</replaceable> |)
6292
6293 <replaceable>cstmt</replaceable> ::= let <replaceable>decls</replaceable>
6294        |  <replaceable>pat</replaceable> &lt;- <replaceable>cmd</replaceable>
6295        |  rec { <replaceable>cstmt</replaceable> ; ... <replaceable>cstmt</replaceable> [;] }
6296        |  <replaceable>cmd</replaceable>
6297 </screen>
6298 where <replaceable>calts</replaceable> are like <replaceable>alts</replaceable>
6299 except that the bodies are commands instead of expressions.
6300 </para>
6301
6302 <para>
6303 Commands produce values, but (like monadic computations)
6304 may yield more than one value,
6305 or none, and may do other things as well.
6306 For the most part, familiarity with monadic notation is a good guide to
6307 using commands.
6308 However the values of expressions, even monadic ones,
6309 are determined by the values of the variables they contain;
6310 this is not necessarily the case for commands.
6311 </para>
6312
6313 <para>
6314 A simple example of the new notation is the expression
6315 <screen>
6316 proc x -> f -&lt; x+1
6317 </screen>
6318 We call this a <firstterm>procedure</firstterm> or
6319 <firstterm>arrow abstraction</firstterm>.
6320 As with a lambda expression, the variable <literal>x</literal>
6321 is a new variable bound within the <literal>proc</literal>-expression.
6322 It refers to the input to the arrow.
6323 In the above example, <literal>-&lt;</literal> is not an identifier but an
6324 new reserved symbol used for building commands from an expression of arrow
6325 type and an expression to be fed as input to that arrow.
6326 (The weird look will make more sense later.)
6327 It may be read as analogue of application for arrows.
6328 The above example is equivalent to the Haskell expression
6329 <screen>
6330 arr (\ x -> x+1) >>> f
6331 </screen>
6332 That would make no sense if the expression to the left of
6333 <literal>-&lt;</literal> involves the bound variable <literal>x</literal>.
6334 More generally, the expression to the left of <literal>-&lt;</literal>
6335 may not involve any <firstterm>local variable</firstterm>,
6336 i.e. a variable bound in the current arrow abstraction.
6337 For such a situation there is a variant <literal>-&lt;&lt;</literal>, as in
6338 <screen>
6339 proc x -> f x -&lt;&lt; x+1
6340 </screen>
6341 which is equivalent to
6342 <screen>
6343 arr (\ x -> (f x, x+1)) >>> app
6344 </screen>
6345 so in this case the arrow must belong to the <literal>ArrowApply</literal>
6346 class.
6347 Such an arrow is equivalent to a monad, so if you're using this form
6348 you may find a monadic formulation more convenient.
6349 </para>
6350
6351 <sect2>
6352 <title>do-notation for commands</title>
6353
6354 <para>
6355 Another form of command is a form of <literal>do</literal>-notation.
6356 For example, you can write
6357 <screen>
6358 proc x -> do
6359         y &lt;- f -&lt; x+1
6360         g -&lt; 2*y
6361         let z = x+y
6362         t &lt;- h -&lt; x*z
6363         returnA -&lt; t+z
6364 </screen>
6365 You can read this much like ordinary <literal>do</literal>-notation,
6366 but with commands in place of monadic expressions.
6367 The first line sends the value of <literal>x+1</literal> as an input to
6368 the arrow <literal>f</literal>, and matches its output against
6369 <literal>y</literal>.
6370 In the next line, the output is discarded.
6371 The arrow <function>returnA</function> is defined in the
6372 <ulink url="../libraries/base/Control-Arrow.html"><literal>Control.Arrow</literal></ulink>
6373 module as <literal>arr id</literal>.
6374 The above example is treated as an abbreviation for
6375 <screen>
6376 arr (\ x -> (x, x)) >>>
6377         first (arr (\ x -> x+1) >>> f) >>>
6378         arr (\ (y, x) -> (y, (x, y))) >>>
6379         first (arr (\ y -> 2*y) >>> g) >>>
6380         arr snd >>>
6381         arr (\ (x, y) -> let z = x+y in ((x, z), z)) >>>
6382         first (arr (\ (x, z) -> x*z) >>> h) >>>
6383         arr (\ (t, z) -> t+z) >>>
6384         returnA
6385 </screen>
6386 Note that variables not used later in the composition are projected out.
6387 After simplification using rewrite rules (see <xref linkend="rewrite-rules"/>)
6388 defined in the
6389 <ulink url="../libraries/base/Control-Arrow.html"><literal>Control.Arrow</literal></ulink>
6390 module, this reduces to
6391 <screen>
6392 arr (\ x -> (x+1, x)) >>>
6393         first f >>>
6394         arr (\ (y, x) -> (2*y, (x, y))) >>>
6395         first g >>>
6396         arr (\ (_, (x, y)) -> let z = x+y in (x*z, z)) >>>
6397         first h >>>
6398         arr (\ (t, z) -> t+z)
6399 </screen>
6400 which is what you might have written by hand.
6401 With arrow notation, GHC keeps track of all those tuples of variables for you.
6402 </para>
6403
6404 <para>
6405 Note that although the above translation suggests that
6406 <literal>let</literal>-bound variables like <literal>z</literal> must be
6407 monomorphic, the actual translation produces Core,
6408 so polymorphic variables are allowed.
6409 </para>
6410
6411 <para>
6412 It's also possible to have mutually recursive bindings,
6413 using the new <literal>rec</literal> keyword, as in the following example:
6414 <programlisting>
6415 counter :: ArrowCircuit a => a Bool Int
6416 counter = proc reset -> do
6417         rec     output &lt;- returnA -&lt; if reset then 0 else next
6418                 next &lt;- delay 0 -&lt; output+1
6419         returnA -&lt; output
6420 </programlisting>
6421 The translation of such forms uses the <function>loop</function> combinator,
6422 so the arrow concerned must belong to the <literal>ArrowLoop</literal> class.
6423 </para>
6424
6425 </sect2>
6426
6427 <sect2>
6428 <title>Conditional commands</title>
6429
6430 <para>
6431 In the previous example, we used a conditional expression to construct the
6432 input for an arrow.
6433 Sometimes we want to conditionally execute different commands, as in
6434 <screen>
6435 proc (x,y) ->
6436         if f x y
6437         then g -&lt; x+1
6438         else h -&lt; y+2
6439 </screen>
6440 which is translated to
6441 <screen>
6442 arr (\ (x,y) -> if f x y then Left x else Right y) >>>
6443         (arr (\x -> x+1) >>> f) ||| (arr (\y -> y+2) >>> g)
6444 </screen>
6445 Since the translation uses <function>|||</function>,
6446 the arrow concerned must belong to the <literal>ArrowChoice</literal> class.
6447 </para>
6448
6449 <para>
6450 There are also <literal>case</literal> commands, like
6451 <screen>
6452 case input of
6453     [] -> f -&lt; ()
6454     [x] -> g -&lt; x+1
6455     x1:x2:xs -> do
6456         y &lt;- h -&lt; (x1, x2)
6457         ys &lt;- k -&lt; xs
6458         returnA -&lt; y:ys
6459 </screen>
6460 The syntax is the same as for <literal>case</literal> expressions,
6461 except that the bodies of the alternatives are commands rather than expressions.
6462 The translation is similar to that of <literal>if</literal> commands.
6463 </para>
6464
6465 </sect2>
6466
6467 <sect2>
6468 <title>Defining your own control structures</title>
6469
6470 <para>
6471 As we're seen, arrow notation provides constructs,
6472 modelled on those for expressions,
6473 for sequencing, value recursion and conditionals.
6474 But suitable combinators,
6475 which you can define in ordinary Haskell,
6476 may also be used to build new commands out of existing ones.
6477 The basic idea is that a command defines an arrow from environments to values.
6478 These environments assign values to the free local variables of the command.
6479 Thus combinators that produce arrows from arrows
6480 may also be used to build commands from commands.
6481 For example, the <literal>ArrowChoice</literal> class includes a combinator
6482 <programlisting>
6483 ArrowChoice a => (&lt;+>) :: a e c -> a e c -> a e c
6484 </programlisting>
6485 so we can use it to build commands:
6486 <programlisting>
6487 expr' = proc x -> do
6488                 returnA -&lt; x
6489         &lt;+> do
6490                 symbol Plus -&lt; ()
6491                 y &lt;- term -&lt; ()
6492                 expr' -&lt; x + y
6493         &lt;+> do
6494                 symbol Minus -&lt; ()
6495                 y &lt;- term -&lt; ()
6496                 expr' -&lt; x - y
6497 </programlisting>
6498 (The <literal>do</literal> on the first line is needed to prevent the first
6499 <literal>&lt;+> ...</literal> from being interpreted as part of the
6500 expression on the previous line.)
6501 This is equivalent to
6502 <programlisting>
6503 expr' = (proc x -> returnA -&lt; x)
6504         &lt;+> (proc x -> do
6505                 symbol Plus -&lt; ()
6506                 y &lt;- term -&lt; ()
6507                 expr' -&lt; x + y)
6508         &lt;+> (proc x -> do
6509                 symbol Minus -&lt; ()
6510                 y &lt;- term -&lt; ()
6511                 expr' -&lt; x - y)
6512 </programlisting>
6513 It is essential that this operator be polymorphic in <literal>e</literal>
6514 (representing the environment input to the command
6515 and thence to its subcommands)
6516 and satisfy the corresponding naturality property
6517 <screen>
6518 arr k >>> (f &lt;+> g) = (arr k >>> f) &lt;+> (arr k >>> g)
6519 </screen>
6520 at least for strict <literal>k</literal>.
6521 (This should be automatic if you're not using <function>seq</function>.)
6522 This ensures that environments seen by the subcommands are environments
6523 of the whole command,
6524 and also allows the translation to safely trim these environments.
6525 The operator must also not use any variable defined within the current
6526 arrow abstraction.
6527 </para>
6528
6529 <para>
6530 We could define our own operator
6531 <programlisting>
6532 untilA :: ArrowChoice a => a e () -> a e Bool -> a e ()
6533 untilA body cond = proc x ->
6534         b &lt;- cond -&lt; x
6535         if b then returnA -&lt; ()
6536         else do
6537                 body -&lt; x
6538                 untilA body cond -&lt; x
6539 </programlisting>
6540 and use it in the same way.
6541 Of course this infix syntax only makes sense for binary operators;
6542 there is also a more general syntax involving special brackets:
6543 <screen>
6544 proc x -> do
6545         y &lt;- f -&lt; x+1
6546         (|untilA (increment -&lt; x+y) (within 0.5 -&lt; x)|)
6547 </screen>
6548 </para>
6549
6550 </sect2>
6551
6552 <sect2>
6553 <title>Primitive constructs</title>
6554
6555 <para>
6556 Some operators will need to pass additional inputs to their subcommands.
6557 For example, in an arrow type supporting exceptions,
6558 the operator that attaches an exception handler will wish to pass the
6559 exception that occurred to the handler.
6560 Such an operator might have a type
6561 <screen>
6562 handleA :: ... => a e c -> a (e,Ex) c -> a e c
6563 </screen>
6564 where <literal>Ex</literal> is the type of exceptions handled.
6565 You could then use this with arrow notation by writing a command
6566 <screen>
6567 body `handleA` \ ex -> handler
6568 </screen>
6569 so that if an exception is raised in the command <literal>body</literal>,
6570 the variable <literal>ex</literal> is bound to the value of the exception
6571 and the command <literal>handler</literal>,
6572 which typically refers to <literal>ex</literal>, is entered.
6573 Though the syntax here looks like a functional lambda,
6574 we are talking about commands, and something different is going on.
6575 The input to the arrow represented by a command consists of values for
6576 the free local variables in the command, plus a stack of anonymous values.
6577 In all the prior examples, this stack was empty.
6578 In the second argument to <function>handleA</function>,
6579 this stack consists of one value, the value of the exception.
6580 The command form of lambda merely gives this value a name.
6581 </para>
6582
6583 <para>
6584 More concretely,
6585 the values on the stack are paired to the right of the environment.
6586 So operators like <function>handleA</function> that pass
6587 extra inputs to their subcommands can be designed for use with the notation
6588 by pairing the values with the environment in this way.
6589 More precisely, the type of each argument of the operator (and its result)
6590 should have the form
6591 <screen>
6592 a (...(e,t1), ... tn) t
6593 </screen>
6594 where <replaceable>e</replaceable> is a polymorphic variable
6595 (representing the environment)
6596 and <replaceable>ti</replaceable> are the types of the values on the stack,
6597 with <replaceable>t1</replaceable> being the <quote>top</quote>.
6598 The polymorphic variable <replaceable>e</replaceable> must not occur in
6599 <replaceable>a</replaceable>, <replaceable>ti</replaceable> or
6600 <replaceable>t</replaceable>.
6601 However the arrows involved need not be the same.
6602 Here are some more examples of suitable operators:
6603 <screen>
6604 bracketA :: ... => a e b -> a (e,b) c -> a (e,c) d -> a e d
6605 runReader :: ... => a e c -> a' (e,State) c
6606 runState :: ... => a e c -> a' (e,State) (c,State)
6607 </screen>
6608 We can supply the extra input required by commands built with the last two
6609 by applying them to ordinary expressions, as in
6610 <screen>
6611 proc x -> do
6612         s &lt;- ...
6613         (|runReader (do { ... })|) s
6614 </screen>
6615 which adds <literal>s</literal> to the stack of inputs to the command
6616 built using <function>runReader</function>.
6617 </para>
6618
6619 <para>
6620 The command versions of lambda abstraction and application are analogous to
6621 the expression versions.
6622 In particular, the beta and eta rules describe equivalences of commands.
6623 These three features (operators, lambda abstraction and application)
6624 are the core of the notation; everything else can be built using them,
6625 though the results would be somewhat clumsy.
6626 For example, we could simulate <literal>do</literal>-notation by defining
6627 <programlisting>
6628 bind :: Arrow a => a e b -> a (e,b) c -> a e c
6629 u `bind` f = returnA &amp;&amp;&amp; u >>> f
6630
6631 bind_ :: Arrow a => a e b -> a e c -> a e c
6632 u `bind_` f = u `bind` (arr fst >>> f)
6633 </programlisting>
6634 We could simulate <literal>if</literal> by defining
6635 <programlisting>
6636 cond :: ArrowChoice a => a e b -> a e b -> a (e,Bool) b
6637 cond f g = arr (\ (e,b) -> if b then Left e else Right e) >>> f ||| g
6638 </programlisting>
6639 </para>
6640
6641 </sect2>
6642
6643 <sect2>
6644 <title>Differences with the paper</title>
6645
6646 <itemizedlist>
6647
6648 <listitem>
6649 <para>Instead of a single form of arrow application (arrow tail) with two
6650 translations, the implementation provides two forms
6651 <quote><literal>-&lt;</literal></quote> (first-order)
6652 and <quote><literal>-&lt;&lt;</literal></quote> (higher-order).
6653 </para>
6654 </listitem>
6655
6656 <listitem>
6657 <para>User-defined operators are flagged with banana brackets instead of
6658 a new <literal>form</literal> keyword.
6659 </para>
6660 </listitem>
6661
6662 </itemizedlist>
6663
6664 </sect2>
6665
6666 <sect2>
6667 <title>Portability</title>
6668
6669 <para>
6670 Although only GHC implements arrow notation directly,
6671 there is also a preprocessor
6672 (available from the 
6673 <ulink url="http://www.haskell.org/arrows/">arrows web page</ulink>)
6674 that translates arrow notation into Haskell 98
6675 for use with other Haskell systems.
6676 You would still want to check arrow programs with GHC;
6677 tracing type errors in the preprocessor output is not easy.
6678 Modules intended for both GHC and the preprocessor must observe some
6679 additional restrictions:
6680 <itemizedlist>
6681
6682 <listitem>
6683 <para>
6684 The module must import
6685 <ulink url="../libraries/base/Control-Arrow.html"><literal>Control.Arrow</literal></ulink>.
6686 </para>
6687 </listitem>
6688
6689 <listitem>
6690 <para>
6691 The preprocessor cannot cope with other Haskell extensions.
6692 These would have to go in separate modules.
6693 </para>
6694 </listitem>
6695
6696 <listitem>
6697 <para>
6698 Because the preprocessor targets Haskell (rather than Core),
6699 <literal>let</literal>-bound variables are monomorphic.
6700 </para>
6701 </listitem>
6702
6703 </itemizedlist>
6704 </para>
6705
6706 </sect2>
6707
6708 </sect1>
6709
6710 <!-- ==================== BANG PATTERNS =================  -->
6711
6712 <sect1 id="bang-patterns">
6713 <title>Bang patterns
6714 <indexterm><primary>Bang patterns</primary></indexterm>
6715 </title>
6716 <para>GHC supports an extension of pattern matching called <emphasis>bang
6717 patterns</emphasis>, written <literal>!<replaceable>pat</replaceable></literal>.   
6718 Bang patterns are under consideration for Haskell Prime.
6719 The <ulink
6720 url="http://hackage.haskell.org/trac/haskell-prime/wiki/BangPatterns">Haskell
6721 prime feature description</ulink> contains more discussion and examples
6722 than the material below.
6723 </para>
6724 <para>
6725 The key change is the addition of a new rule to the 
6726 <ulink url="http://haskell.org/onlinereport/exps.html#sect3.17.2">semantics of pattern matching in the Haskell 98 report</ulink>.
6727 Add new bullet 10, saying: Matching the pattern <literal>!</literal><replaceable>pat</replaceable> 
6728 against a value <replaceable>v</replaceable> behaves as follows:
6729 <itemizedlist>
6730 <listitem><para>if <replaceable>v</replaceable> is bottom, the match diverges</para></listitem>
6731 <listitem><para>otherwise, <replaceable>pat</replaceable> is matched against <replaceable>v</replaceable>  </para></listitem>
6732 </itemizedlist>
6733 </para>
6734 <para>
6735 Bang patterns are enabled by the flag <option>-XBangPatterns</option>.
6736 </para>
6737
6738 <sect2 id="bang-patterns-informal">
6739 <title>Informal description of bang patterns
6740 </title>
6741 <para>
6742 The main idea is to add a single new production to the syntax of patterns:
6743 <programlisting>
6744   pat ::= !pat
6745 </programlisting>
6746 Matching an expression <literal>e</literal> against a pattern <literal>!p</literal> is done by first
6747 evaluating <literal>e</literal> (to WHNF) and then matching the result against <literal>p</literal>.
6748 Example:
6749 <programlisting>
6750 f1 !x = True
6751 </programlisting>
6752 This definition makes <literal>f1</literal> is strict in <literal>x</literal>,
6753 whereas without the bang it would be lazy.
6754 Bang patterns can be nested of course:
6755 <programlisting>
6756 f2 (!x, y) = [x,y]
6757 </programlisting>
6758 Here, <literal>f2</literal> is strict in <literal>x</literal> but not in
6759 <literal>y</literal>.  
6760 A bang only really has an effect if it precedes a variable or wild-card pattern:
6761 <programlisting>
6762 f3 !(x,y) = [x,y]
6763 f4 (x,y)  = [x,y]
6764 </programlisting>
6765 Here, <literal>f3</literal> and <literal>f4</literal> are identical; 
6766 putting a bang before a pattern that
6767 forces evaluation anyway does nothing.
6768 </para>
6769 <para>
6770 There is one (apparent) exception to this general rule that a bang only
6771 makes a difference when it precedes a variable or wild-card: a bang at the
6772 top level of a <literal>let</literal> or <literal>where</literal>
6773 binding makes the binding strict, regardless of the pattern. For example:
6774 <programlisting>
6775 let ![x,y] = e in b
6776 </programlisting>
6777 is a strict binding: operationally, it evaluates <literal>e</literal>, matches
6778 it against the pattern <literal>[x,y]</literal>, and then evaluates <literal>b</literal>.
6779 (We say "apparent" exception because the Right Way to think of it is that the bang
6780 at the top of a binding is not part of the <emphasis>pattern</emphasis>; rather it
6781 is part of the syntax of the <emphasis>binding</emphasis>.)
6782 Nested bangs in a pattern binding behave uniformly with all other forms of 
6783 pattern matching.  For example
6784 <programlisting>
6785 let (!x,[y]) = e in b
6786 </programlisting>
6787 is equivalent to this:
6788 <programlisting>
6789 let { t = case e of (x,[y]) -> x `seq` (x,y)
6790       x = fst t
6791       y = snd t }
6792 in b
6793 </programlisting>
6794 The binding is lazy, but when either <literal>x</literal> or <literal>y</literal> is
6795 evaluated by <literal>b</literal> the entire pattern is matched, including forcing the
6796 evaluation of <literal>x</literal>.
6797 </para>
6798 <para>
6799 Bang patterns work in <literal>case</literal> expressions too, of course:
6800 <programlisting>
6801 g5 x = let y = f x in body
6802 g6 x = case f x of { y -&gt; body }
6803 g7 x = case f x of { !y -&gt; body }
6804 </programlisting>
6805 The functions <literal>g5</literal> and <literal>g6</literal> mean exactly the same thing.  
6806 But <literal>g7</literal> evaluates <literal>(f x)</literal>, binds <literal>y</literal> to the
6807 result, and then evaluates <literal>body</literal>.
6808 </para>
6809 </sect2>
6810
6811
6812 <sect2 id="bang-patterns-sem">
6813 <title>Syntax and semantics
6814 </title>
6815 <para>
6816
6817 We add a single new production to the syntax of patterns:
6818 <programlisting>
6819   pat ::= !pat
6820 </programlisting>
6821 There is one problem with syntactic ambiguity.  Consider:
6822 <programlisting>
6823 f !x = 3
6824 </programlisting>
6825 Is this a definition of the infix function "<literal>(!)</literal>",
6826 or of the "<literal>f</literal>" with a bang pattern? GHC resolves this
6827 ambiguity in favour of the latter.  If you want to define
6828 <literal>(!)</literal> with bang-patterns enabled, you have to do so using
6829 prefix notation:
6830 <programlisting>
6831 (!) f x = 3
6832 </programlisting>
6833 The semantics of Haskell pattern matching is described in <ulink
6834 url="http://www.haskell.org/onlinereport/exps.html#sect3.17.2">
6835 Section 3.17.2</ulink> of the Haskell Report.  To this description add 
6836 one extra item 10, saying:
6837 <itemizedlist><listitem><para>Matching
6838 the pattern <literal>!pat</literal> against a value <literal>v</literal> behaves as follows:
6839 <itemizedlist><listitem><para>if <literal>v</literal> is bottom, the match diverges</para></listitem>
6840                 <listitem><para>otherwise, <literal>pat</literal> is matched against
6841                 <literal>v</literal></para></listitem>
6842 </itemizedlist>
6843 </para></listitem></itemizedlist>
6844 Similarly, in Figure 4 of  <ulink url="http://www.haskell.org/onlinereport/exps.html#sect3.17.3">
6845 Section 3.17.3</ulink>, add a new case (t):
6846 <programlisting>
6847 case v of { !pat -> e; _ -> e' }
6848    = v `seq` case v of { pat -> e; _ -> e' }
6849 </programlisting>
6850 </para><para>
6851 That leaves let expressions, whose translation is given in 
6852 <ulink url="http://www.haskell.org/onlinereport/exps.html#sect3.12">Section
6853 3.12</ulink>
6854 of the Haskell Report.
6855 In the translation box, first apply 
6856 the following transformation:  for each pattern <literal>pi</literal> that is of 
6857 form <literal>!qi = ei</literal>, transform it to <literal>(xi,!qi) = ((),ei)</literal>, and and replace <literal>e0</literal> 
6858 by <literal>(xi `seq` e0)</literal>.  Then, when none of the left-hand-side patterns
6859 have a bang at the top, apply the rules in the existing box.
6860 </para>
6861 <para>The effect of the let rule is to force complete matching of the pattern
6862 <literal>qi</literal> before evaluation of the body is begun.  The bang is
6863 retained in the translated form in case <literal>qi</literal> is a variable,
6864 thus:
6865 <programlisting>
6866   let !y = f x in b
6867 </programlisting>
6868
6869 </para>
6870 <para>
6871 The let-binding can be recursive.  However, it is much more common for
6872 the let-binding to be non-recursive, in which case the following law holds:
6873 <literal>(let !p = rhs in body)</literal>
6874      is equivalent to
6875 <literal>(case rhs of !p -> body)</literal>
6876 </para>
6877 <para>
6878 A pattern with a bang at the outermost level is not allowed at the top level of
6879 a module.
6880 </para>
6881 </sect2>
6882 </sect1>
6883
6884 <!-- ==================== ASSERTIONS =================  -->
6885
6886 <sect1 id="assertions">
6887 <title>Assertions
6888 <indexterm><primary>Assertions</primary></indexterm>
6889 </title>
6890
6891 <para>
6892 If you want to make use of assertions in your standard Haskell code, you
6893 could define a function like the following:
6894 </para>
6895
6896 <para>
6897
6898 <programlisting>
6899 assert :: Bool -> a -> a
6900 assert False x = error "assertion failed!"
6901 assert _     x = x
6902 </programlisting>
6903
6904 </para>
6905
6906 <para>
6907 which works, but gives you back a less than useful error message --
6908 an assertion failed, but which and where?
6909 </para>
6910
6911 <para>
6912 One way out is to define an extended <function>assert</function> function which also
6913 takes a descriptive string to include in the error message and
6914 perhaps combine this with the use of a pre-processor which inserts
6915 the source location where <function>assert</function> was used.
6916 </para>
6917
6918 <para>
6919 Ghc offers a helping hand here, doing all of this for you. For every
6920 use of <function>assert</function> in the user's source:
6921 </para>
6922
6923 <para>
6924
6925 <programlisting>
6926 kelvinToC :: Double -> Double
6927 kelvinToC k = assert (k &gt;= 0.0) (k+273.15)
6928 </programlisting>
6929
6930 </para>
6931
6932 <para>
6933 Ghc will rewrite this to also include the source location where the
6934 assertion was made,
6935 </para>
6936
6937 <para>
6938
6939 <programlisting>
6940 assert pred val ==> assertError "Main.hs|15" pred val
6941 </programlisting>
6942
6943 </para>
6944
6945 <para>
6946 The rewrite is only performed by the compiler when it spots
6947 applications of <function>Control.Exception.assert</function>, so you
6948 can still define and use your own versions of
6949 <function>assert</function>, should you so wish. If not, import
6950 <literal>Control.Exception</literal> to make use
6951 <function>assert</function> in your code.
6952 </para>
6953
6954 <para>
6955 GHC ignores assertions when optimisation is turned on with the
6956       <option>-O</option><indexterm><primary><option>-O</option></primary></indexterm> flag.  That is, expressions of the form
6957 <literal>assert pred e</literal> will be rewritten to
6958 <literal>e</literal>.  You can also disable assertions using the
6959       <option>-fignore-asserts</option>
6960       option<indexterm><primary><option>-fignore-asserts</option></primary>
6961       </indexterm>.</para>
6962
6963 <para>
6964 Assertion failures can be caught, see the documentation for the
6965 <literal>Control.Exception</literal> library for the details.
6966 </para>
6967
6968 </sect1>
6969
6970
6971 <!-- =============================== PRAGMAS ===========================  -->
6972
6973   <sect1 id="pragmas">
6974     <title>Pragmas</title>
6975
6976     <indexterm><primary>pragma</primary></indexterm>
6977
6978     <para>GHC supports several pragmas, or instructions to the
6979     compiler placed in the source code.  Pragmas don't normally affect
6980     the meaning of the program, but they might affect the efficiency
6981     of the generated code.</para>
6982
6983     <para>Pragmas all take the form
6984
6985 <literal>{-# <replaceable>word</replaceable> ... #-}</literal>  
6986
6987     where <replaceable>word</replaceable> indicates the type of
6988     pragma, and is followed optionally by information specific to that
6989     type of pragma.  Case is ignored in
6990     <replaceable>word</replaceable>.  The various values for
6991     <replaceable>word</replaceable> that GHC understands are described
6992     in the following sections; any pragma encountered with an
6993     unrecognised <replaceable>word</replaceable> is
6994     ignored. The layout rule applies in pragmas, so the closing <literal>#-}</literal>
6995     should start in a column to the right of the opening <literal>{-#</literal>. </para> 
6996
6997     <para>Certain pragmas are <emphasis>file-header pragmas</emphasis>:
6998       <itemizedlist>
6999       <listitem><para>
7000           A file-header
7001           pragma must precede the <literal>module</literal> keyword in the file.
7002           </para></listitem>
7003       <listitem><para>
7004       There can be as many file-header pragmas as you please, and they can be
7005       preceded or followed by comments.  
7006           </para></listitem>
7007       <listitem><para>
7008       File-header pragmas are read once only, before
7009       pre-processing the file (e.g. with cpp).
7010           </para></listitem>
7011       <listitem><para>
7012          The file-header pragmas are: <literal>{-# LANGUAGE #-}</literal>,
7013         <literal>{-# OPTIONS_GHC #-}</literal>, and
7014         <literal>{-# INCLUDE #-}</literal>.
7015           </para></listitem>
7016       </itemizedlist>
7017       </para>
7018
7019     <sect2 id="language-pragma">
7020       <title>LANGUAGE pragma</title>
7021
7022       <indexterm><primary>LANGUAGE</primary><secondary>pragma</secondary></indexterm>
7023       <indexterm><primary>pragma</primary><secondary>LANGUAGE</secondary></indexterm>
7024
7025       <para>The <literal>LANGUAGE</literal> pragma allows language extensions to be enabled 
7026         in a portable way.
7027         It is the intention that all Haskell compilers support the
7028         <literal>LANGUAGE</literal> pragma with the same syntax, although not
7029         all extensions are supported by all compilers, of
7030         course.  The <literal>LANGUAGE</literal> pragma should be used instead
7031         of <literal>OPTIONS_GHC</literal>, if possible.</para>
7032
7033       <para>For example, to enable the FFI and preprocessing with CPP:</para>
7034
7035 <programlisting>{-# LANGUAGE ForeignFunctionInterface, CPP #-}</programlisting>
7036
7037         <para><literal>LANGUAGE</literal> is a file-header pragma (see <xref linkend="pragmas"/>).</para>
7038
7039       <para>Every language extension can also be turned into a command-line flag
7040         by prefixing it with "<literal>-X</literal>"; for example <option>-XForeignFunctionInterface</option>.
7041         (Similarly, all "<literal>-X</literal>" flags can be written as <literal>LANGUAGE</literal> pragmas.
7042       </para>
7043
7044       <para>A list of all supported language extensions can be obtained by invoking
7045         <literal>ghc --supported-languages</literal> (see <xref linkend="modes"/>).</para>
7046
7047       <para>Any extension from the <literal>Extension</literal> type defined in
7048         <ulink
7049           url="../libraries/Cabal/Language-Haskell-Extension.html"><literal>Language.Haskell.Extension</literal></ulink>
7050         may be used.  GHC will report an error if any of the requested extensions are not supported.</para>
7051     </sect2>
7052
7053
7054     <sect2 id="options-pragma">
7055       <title>OPTIONS_GHC pragma</title>
7056       <indexterm><primary>OPTIONS_GHC</primary>
7057       </indexterm>
7058       <indexterm><primary>pragma</primary><secondary>OPTIONS_GHC</secondary>
7059       </indexterm>
7060
7061       <para>The <literal>OPTIONS_GHC</literal> pragma is used to specify
7062       additional options that are given to the compiler when compiling
7063       this source file.  See <xref linkend="source-file-options"/> for
7064       details.</para>
7065
7066       <para>Previous versions of GHC accepted <literal>OPTIONS</literal> rather
7067         than <literal>OPTIONS_GHC</literal>, but that is now deprecated.</para>
7068     </sect2>
7069
7070         <para><literal>OPTIONS_GHC</literal> is a file-header pragma (see <xref linkend="pragmas"/>).</para>
7071
7072     <sect2 id="include-pragma">
7073       <title>INCLUDE pragma</title>
7074
7075       <para>The <literal>INCLUDE</literal> pragma is for specifying the names
7076         of C header files that should be <literal>#include</literal>'d into
7077         the C source code generated by the compiler for the current module (if
7078         compiling via C).  For example:</para>
7079
7080 <programlisting>
7081 {-# INCLUDE "foo.h" #-}
7082 {-# INCLUDE &lt;stdio.h&gt; #-}</programlisting>
7083
7084         <para><literal>INCLUDE</literal> is a file-header pragma (see <xref linkend="pragmas"/>).</para>
7085
7086       <para>An <literal>INCLUDE</literal> pragma is  the preferred alternative
7087         to the <option>-#include</option> option (<xref
7088           linkend="options-C-compiler" />), because the
7089         <literal>INCLUDE</literal> pragma is understood by other
7090         compilers.  Yet another alternative is to add the include file to each
7091         <literal>foreign import</literal> declaration in your code, but we
7092         don't recommend using this approach with GHC.</para>
7093     </sect2>
7094
7095     <sect2 id="warning-deprecated-pragma">
7096       <title>WARNING and DEPRECATED pragmas</title>
7097       <indexterm><primary>WARNING</primary></indexterm>
7098       <indexterm><primary>DEPRECATED</primary></indexterm>
7099
7100       <para>The WARNING pragma allows you to attach an arbitrary warning
7101       to a particular function, class, or type.
7102       A DEPRECATED pragma lets you specify that
7103       a particular function, class, or type is deprecated.
7104       There are two ways of using these pragmas.
7105
7106       <itemizedlist>
7107         <listitem>
7108           <para>You can work on an entire module thus:</para>
7109 <programlisting>
7110    module Wibble {-# DEPRECATED "Use Wobble instead" #-} where
7111      ...
7112 </programlisting>
7113       <para>Or:</para>
7114 <programlisting>
7115    module Wibble {-# WARNING "This is an unstable interface." #-} where
7116      ...
7117 </programlisting>
7118           <para>When you compile any module that import
7119           <literal>Wibble</literal>, GHC will print the specified
7120           message.</para>
7121         </listitem>
7122
7123         <listitem>
7124           <para>You can attach a warning to a function, class, type, or data constructor, with the
7125           following top-level declarations:</para>
7126 <programlisting>
7127    {-# DEPRECATED f, C, T "Don't use these" #-}
7128    {-# WARNING unsafePerformIO "This is unsafe; I hope you know what you're doing" #-}
7129 </programlisting>
7130           <para>When you compile any module that imports and uses any
7131           of the specified entities, GHC will print the specified
7132           message.</para>
7133           <para> You can only attach to entities declared at top level in the module
7134           being compiled, and you can only use unqualified names in the list of
7135           entities. A capitalised name, such as <literal>T</literal>
7136           refers to <emphasis>either</emphasis> the type constructor <literal>T</literal>
7137           <emphasis>or</emphasis> the data constructor <literal>T</literal>, or both if
7138           both are in scope.  If both are in scope, there is currently no way to
7139       specify one without the other (c.f. fixities
7140       <xref linkend="infix-tycons"/>).</para>
7141         </listitem>
7142       </itemizedlist>
7143       Warnings and deprecations are not reported for
7144       (a) uses within the defining module, and
7145       (b) uses in an export list.
7146       The latter reduces spurious complaints within a library
7147       in which one module gathers together and re-exports 
7148       the exports of several others.
7149       </para>
7150       <para>You can suppress the warnings with the flag
7151       <option>-fno-warn-warnings-deprecations</option>.</para>
7152     </sect2>
7153
7154     <sect2 id="inline-noinline-pragma">
7155       <title>INLINE and NOINLINE pragmas</title>
7156
7157       <para>These pragmas control the inlining of function
7158       definitions.</para>
7159
7160       <sect3 id="inline-pragma">
7161         <title>INLINE pragma</title>
7162         <indexterm><primary>INLINE</primary></indexterm>
7163
7164         <para>GHC (with <option>-O</option>, as always) tries to
7165         inline (or &ldquo;unfold&rdquo;) functions/values that are
7166         &ldquo;small enough,&rdquo; thus avoiding the call overhead
7167         and possibly exposing other more-wonderful optimisations.
7168         Normally, if GHC decides a function is &ldquo;too
7169         expensive&rdquo; to inline, it will not do so, nor will it
7170         export that unfolding for other modules to use.</para>
7171
7172         <para>The sledgehammer you can bring to bear is the
7173         <literal>INLINE</literal><indexterm><primary>INLINE
7174         pragma</primary></indexterm> pragma, used thusly:</para>
7175
7176 <programlisting>
7177 key_function :: Int -> String -> (Bool, Double)
7178 {-# INLINE key_function #-}
7179 </programlisting>
7180
7181         <para>The major effect of an <literal>INLINE</literal> pragma
7182         is to declare a function's &ldquo;cost&rdquo; to be very low.
7183         The normal unfolding machinery will then be very keen to
7184         inline it.  However, an <literal>INLINE</literal> pragma for a 
7185         function "<literal>f</literal>" has a number of other effects:
7186 <itemizedlist>
7187 <listitem><para>
7188 No functions are inlined into <literal>f</literal>.  Otherwise
7189 GHC might inline a big function into <literal>f</literal>'s right hand side, 
7190 making <literal>f</literal> big; and then inline <literal>f</literal> blindly.
7191 </para></listitem>
7192 <listitem><para>
7193 The float-in, float-out, and common-sub-expression transformations are not 
7194 applied to the body of <literal>f</literal>.  
7195 </para></listitem>
7196 <listitem><para>
7197 An INLINE function is not worker/wrappered by strictness analysis.
7198 It's going to be inlined wholesale instead.
7199 </para></listitem>
7200 </itemizedlist>
7201 All of these effects are aimed at ensuring that what gets inlined is
7202 exactly what you asked for, no more and no less.
7203 </para>
7204 <para>GHC ensures that inlining cannot go on forever: every mutually-recursive
7205 group is cut by one or more <emphasis>loop breakers</emphasis> that is never inlined
7206 (see <ulink url="http://research.microsoft.com/%7Esimonpj/Papers/inlining/index.htm">
7207 Secrets of the GHC inliner, JFP 12(4) July 2002</ulink>).
7208 GHC tries not to select a function with an INLINE pragma as a loop breaker, but
7209 when there is no choice even an INLINE function can be selected, in which case
7210 the INLINE pragma is ignored.
7211 For example, for a self-recursive function, the loop breaker can only be the function
7212 itself, so an INLINE pragma is always ignored.</para>
7213
7214         <para>Syntactically, an <literal>INLINE</literal> pragma for a
7215         function can be put anywhere its type signature could be
7216         put.</para>
7217
7218         <para><literal>INLINE</literal> pragmas are a particularly
7219         good idea for the
7220         <literal>then</literal>/<literal>return</literal> (or
7221         <literal>bind</literal>/<literal>unit</literal>) functions in
7222         a monad.  For example, in GHC's own
7223         <literal>UniqueSupply</literal> monad code, we have:</para>
7224
7225 <programlisting>
7226 {-# INLINE thenUs #-}
7227 {-# INLINE returnUs #-}
7228 </programlisting>
7229
7230         <para>See also the <literal>NOINLINE</literal> pragma (<xref
7231         linkend="noinline-pragma"/>).</para>
7232
7233         <para>Note: the HBC compiler doesn't like <literal>INLINE</literal> pragmas,
7234           so if you want your code to be HBC-compatible you'll have to surround
7235           the pragma with C pre-processor directives 
7236           <literal>#ifdef __GLASGOW_HASKELL__</literal>...<literal>#endif</literal>.</para>
7237
7238       </sect3>
7239
7240       <sect3 id="noinline-pragma">
7241         <title>NOINLINE pragma</title>
7242         
7243         <indexterm><primary>NOINLINE</primary></indexterm>
7244         <indexterm><primary>NOTINLINE</primary></indexterm>
7245
7246         <para>The <literal>NOINLINE</literal> pragma does exactly what
7247         you'd expect: it stops the named function from being inlined
7248         by the compiler.  You shouldn't ever need to do this, unless
7249         you're very cautious about code size.</para>
7250
7251         <para><literal>NOTINLINE</literal> is a synonym for
7252         <literal>NOINLINE</literal> (<literal>NOINLINE</literal> is
7253         specified by Haskell 98 as the standard way to disable
7254         inlining, so it should be used if you want your code to be
7255         portable).</para>
7256       </sect3>
7257
7258       <sect3 id="phase-control">
7259         <title>Phase control</title>
7260
7261         <para> Sometimes you want to control exactly when in GHC's
7262         pipeline the INLINE pragma is switched on.  Inlining happens
7263         only during runs of the <emphasis>simplifier</emphasis>.  Each
7264         run of the simplifier has a different <emphasis>phase
7265         number</emphasis>; the phase number decreases towards zero.
7266         If you use <option>-dverbose-core2core</option> you'll see the
7267         sequence of phase numbers for successive runs of the
7268         simplifier.  In an INLINE pragma you can optionally specify a
7269         phase number, thus:
7270         <itemizedlist>
7271           <listitem>
7272             <para>"<literal>INLINE[k] f</literal>" means: do not inline
7273             <literal>f</literal>
7274               until phase <literal>k</literal>, but from phase
7275               <literal>k</literal> onwards be very keen to inline it.
7276             </para></listitem>
7277           <listitem>
7278             <para>"<literal>INLINE[~k] f</literal>" means: be very keen to inline
7279             <literal>f</literal>
7280               until phase <literal>k</literal>, but from phase
7281               <literal>k</literal> onwards do not inline it.
7282             </para></listitem>
7283           <listitem>
7284             <para>"<literal>NOINLINE[k] f</literal>" means: do not inline
7285             <literal>f</literal>
7286               until phase <literal>k</literal>, but from phase
7287               <literal>k</literal> onwards be willing to inline it (as if
7288               there was no pragma).
7289             </para></listitem>
7290             <listitem>
7291             <para>"<literal>NOINLINE[~k] f</literal>" means: be willing to inline
7292             <literal>f</literal>
7293               until phase <literal>k</literal>, but from phase
7294               <literal>k</literal> onwards do not inline it.
7295             </para></listitem>
7296         </itemizedlist>
7297 The same information is summarised here:
7298 <programlisting>
7299                            -- Before phase 2     Phase 2 and later
7300   {-# INLINE   [2]  f #-}  --      No                 Yes
7301   {-# INLINE   [~2] f #-}  --      Yes                No
7302   {-# NOINLINE [2]  f #-}  --      No                 Maybe
7303   {-# NOINLINE [~2] f #-}  --      Maybe              No
7304
7305   {-# INLINE   f #-}       --      Yes                Yes
7306   {-# NOINLINE f #-}       --      No                 No
7307 </programlisting>
7308 By "Maybe" we mean that the usual heuristic inlining rules apply (if the
7309 function body is small, or it is applied to interesting-looking arguments etc).
7310 Another way to understand the semantics is this:
7311 <itemizedlist>
7312 <listitem><para>For both INLINE and NOINLINE, the phase number says
7313 when inlining is allowed at all.</para></listitem>
7314 <listitem><para>The INLINE pragma has the additional effect of making the
7315 function body look small, so that when inlining is allowed it is very likely to
7316 happen.
7317 </para></listitem>
7318 </itemizedlist>
7319 </para>
7320 <para>The same phase-numbering control is available for RULES
7321         (<xref linkend="rewrite-rules"/>).</para>
7322       </sect3>
7323     </sect2>
7324
7325     <sect2 id="annotation-pragmas">
7326       <title>ANN pragmas</title>
7327       
7328       <para>GHC offers the ability to annotate various code constructs with additional
7329       data by using three pragmas.  This data can then be inspected at a later date by
7330       using GHC-as-a-library.</para>
7331             
7332       <sect3 id="ann-pragma">
7333         <title>Annotating values</title>
7334         
7335         <indexterm><primary>ANN</primary></indexterm>
7336         
7337         <para>Any expression that has both <literal>Typeable</literal> and <literal>Data</literal> instances may be attached to a top-level value
7338         binding using an <literal>ANN</literal> pragma. In particular, this means you can use <literal>ANN</literal>
7339         to annotate data constructors (e.g. <literal>Just</literal>) as well as normal values (e.g. <literal>take</literal>).
7340         By way of example, to annotate the function <literal>foo</literal> with the annotation <literal>Just "Hello"</literal>
7341         you would do this:</para>
7342         
7343 <programlisting>
7344 {-# ANN foo (Just "Hello") #-}
7345 foo = ...
7346 </programlisting>
7347         
7348         <para>
7349           A number of restrictions apply to use of annotations:
7350           <itemizedlist>
7351             <listitem><para>The binder being annotated must be at the top level (i.e. no nested binders)</para></listitem>
7352             <listitem><para>The binder being annotated must be declared in the current module</para></listitem>
7353             <listitem><para>The expression you are annotating with must have a type with <literal>Typeable</literal> and <literal>Data</literal> instances</para></listitem>
7354             <listitem><para>The <ulink linkend="using-template-haskell">Template Haskell staging restrictions</ulink> apply to the
7355             expression being annotated with, so for example you cannot run a function from the module being compiled.</para>
7356             
7357             <para>To be precise, the annotation <literal>{-# ANN x e #-}</literal> is well staged if and only if <literal>$(e)</literal> would be 
7358             (disregarding the usual type restrictions of the splice syntax, and the usual restriction on splicing inside a splice - <literal>$([|1|])</literal> is fine as an annotation, albeit redundant).</para></listitem>
7359           </itemizedlist>
7360           
7361           If you feel strongly that any of these restrictions are too onerous, <ulink url="http://hackage.haskell.org/trac/ghc/wiki/MailingListsAndIRC">
7362           please give the GHC team a shout</ulink>.
7363         </para>
7364         
7365         <para>However, apart from these restrictions, many things are allowed, including expressions which are not fully evaluated!
7366         Annotation expressions will be evaluated by the compiler just like Template Haskell splices are. So, this annotation is fine:</para>
7367         
7368 <programlisting>
7369 {-# ANN f SillyAnnotation { foo = (id 10) + $([| 20 |]), bar = 'f } #-}
7370 f = ...
7371 </programlisting>
7372       </sect3>
7373       
7374       <sect3 id="typeann-pragma">
7375         <title>Annotating types</title>
7376         
7377         <indexterm><primary>ANN type</primary></indexterm>
7378         <indexterm><primary>ANN</primary></indexterm>
7379         
7380         <para>You can annotate types with the <literal>ANN</literal> pragma by using the <literal>type</literal> keyword. For example:</para>
7381         
7382 <programlisting>
7383 {-# ANN type Foo (Just "A `Maybe String' annotation") #-}
7384 data Foo = ...
7385 </programlisting>
7386       </sect3>
7387       
7388       <sect3 id="modann-pragma">
7389         <title>Annotating modules</title>
7390         
7391         <indexterm><primary>ANN module</primary></indexterm>
7392         <indexterm><primary>ANN</primary></indexterm>
7393         
7394         <para>You can annotate modules with the <literal>ANN</literal> pragma by using the <literal>module</literal> keyword. For example:</para>
7395         
7396 <programlisting>
7397 {-# ANN module (Just "A `Maybe String' annotation") #-}
7398 </programlisting>
7399       </sect3>
7400     </sect2>
7401
7402     <sect2 id="line-pragma">
7403       <title>LINE pragma</title>
7404
7405       <indexterm><primary>LINE</primary><secondary>pragma</secondary></indexterm>
7406       <indexterm><primary>pragma</primary><secondary>LINE</secondary></indexterm>
7407       <para>This pragma is similar to C's <literal>&num;line</literal>
7408       pragma, and is mainly for use in automatically generated Haskell
7409       code.  It lets you specify the line number and filename of the
7410       original code; for example</para>
7411
7412 <programlisting>{-# LINE 42 "Foo.vhs" #-}</programlisting>
7413
7414       <para>if you'd generated the current file from something called
7415       <filename>Foo.vhs</filename> and this line corresponds to line
7416       42 in the original.  GHC will adjust its error messages to refer
7417       to the line/file named in the <literal>LINE</literal>
7418       pragma.</para>
7419     </sect2>
7420
7421     <sect2 id="rules">
7422       <title>RULES pragma</title>
7423
7424       <para>The RULES pragma lets you specify rewrite rules.  It is
7425       described in <xref linkend="rewrite-rules"/>.</para>
7426     </sect2>
7427
7428     <sect2 id="specialize-pragma">
7429       <title>SPECIALIZE pragma</title>
7430
7431       <indexterm><primary>SPECIALIZE pragma</primary></indexterm>
7432       <indexterm><primary>pragma, SPECIALIZE</primary></indexterm>
7433       <indexterm><primary>overloading, death to</primary></indexterm>
7434
7435       <para>(UK spelling also accepted.)  For key overloaded
7436       functions, you can create extra versions (NB: more code space)
7437       specialised to particular types.  Thus, if you have an
7438       overloaded function:</para>
7439
7440 <programlisting>
7441   hammeredLookup :: Ord key => [(key, value)] -> key -> value
7442 </programlisting>
7443
7444       <para>If it is heavily used on lists with
7445       <literal>Widget</literal> keys, you could specialise it as
7446       follows:</para>
7447
7448 <programlisting>
7449   {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
7450 </programlisting>
7451
7452       <para>A <literal>SPECIALIZE</literal> pragma for a function can
7453       be put anywhere its type signature could be put.</para>
7454
7455       <para>A <literal>SPECIALIZE</literal> has the effect of generating
7456       (a) a specialised version of the function and (b) a rewrite rule
7457       (see <xref linkend="rewrite-rules"/>) that rewrites a call to the
7458       un-specialised function into a call to the specialised one.</para>
7459
7460       <para>The type in a SPECIALIZE pragma can be any type that is less
7461         polymorphic than the type of the original function.  In concrete terms,
7462         if the original function is <literal>f</literal> then the pragma
7463 <programlisting>
7464   {-# SPECIALIZE f :: &lt;type&gt; #-}
7465 </programlisting>
7466       is valid if and only if the definition
7467 <programlisting>
7468   f_spec :: &lt;type&gt;
7469   f_spec = f
7470 </programlisting>
7471       is valid.  Here are some examples (where we only give the type signature
7472       for the original function, not its code):
7473 <programlisting>
7474   f :: Eq a => a -> b -> b
7475   {-# SPECIALISE f :: Int -> b -> b #-}
7476
7477   g :: (Eq a, Ix b) => a -> b -> b
7478   {-# SPECIALISE g :: (Eq a) => a -> Int -> Int #-}
7479
7480   h :: Eq a => a -> a -> a
7481   {-# SPECIALISE h :: (Eq a) => [a] -> [a] -> [a] #-}
7482 </programlisting>
7483 The last of these examples will generate a 
7484 RULE with a somewhat-complex left-hand side (try it yourself), so it might not fire very
7485 well.  If you use this kind of specialisation, let us know how well it works.
7486 </para>
7487
7488 <para>A <literal>SPECIALIZE</literal> pragma can optionally be followed with a
7489 <literal>INLINE</literal> or <literal>NOINLINE</literal> pragma, optionally 
7490 followed by a phase, as described in <xref linkend="inline-noinline-pragma"/>.
7491 The <literal>INLINE</literal> pragma affects the specialised version of the
7492 function (only), and applies even if the function is recursive.  The motivating
7493 example is this:
7494 <programlisting>
7495 -- A GADT for arrays with type-indexed representation
7496 data Arr e where
7497   ArrInt :: !Int -> ByteArray# -> Arr Int
7498   ArrPair :: !Int -> Arr e1 -> Arr e2 -> Arr (e1, e2)
7499
7500 (!:) :: Arr e -> Int -> e
7501 {-# SPECIALISE INLINE (!:) :: Arr Int -> Int -> Int #-}
7502 {-# SPECIALISE INLINE (!:) :: Arr (a, b) -> Int -> (a, b) #-}
7503 (ArrInt _ ba)     !: (I# i) = I# (indexIntArray# ba i)
7504 (ArrPair _ a1 a2) !: i      = (a1 !: i, a2 !: i)
7505 </programlisting>
7506 Here, <literal>(!:)</literal> is a recursive function that indexes arrays
7507 of type <literal>Arr e</literal>.  Consider a call to  <literal>(!:)</literal>
7508 at type <literal>(Int,Int)</literal>.  The second specialisation will fire, and
7509 the specialised function will be inlined.  It has two calls to
7510 <literal>(!:)</literal>,
7511 both at type <literal>Int</literal>.  Both these calls fire the first
7512 specialisation, whose body is also inlined.  The result is a type-based
7513 unrolling of the indexing function.</para>
7514 <para>Warning: you can make GHC diverge by using <literal>SPECIALISE INLINE</literal>
7515 on an ordinarily-recursive function.</para>
7516
7517       <para>Note: In earlier versions of GHC, it was possible to provide your own
7518       specialised function for a given type:
7519
7520 <programlisting>
7521 {-# SPECIALIZE hammeredLookup :: [(Int, value)] -> Int -> value = intLookup #-}
7522 </programlisting>
7523
7524       This feature has been removed, as it is now subsumed by the
7525       <literal>RULES</literal> pragma (see <xref linkend="rule-spec"/>).</para>
7526
7527     </sect2>
7528
7529 <sect2 id="specialize-instance-pragma">
7530 <title>SPECIALIZE instance pragma
7531 </title>
7532
7533 <para>
7534 <indexterm><primary>SPECIALIZE pragma</primary></indexterm>
7535 <indexterm><primary>overloading, death to</primary></indexterm>
7536 Same idea, except for instance declarations.  For example:
7537
7538 <programlisting>
7539 instance (Eq a) => Eq (Foo a) where { 
7540    {-# SPECIALIZE instance Eq (Foo [(Int, Bar)]) #-}
7541    ... usual stuff ...
7542  }
7543 </programlisting>
7544 The pragma must occur inside the <literal>where</literal> part
7545 of the instance declaration.
7546 </para>
7547 <para>
7548 Compatible with HBC, by the way, except perhaps in the placement
7549 of the pragma.
7550 </para>
7551
7552 </sect2>
7553
7554     <sect2 id="unpack-pragma">
7555       <title>UNPACK pragma</title>
7556
7557       <indexterm><primary>UNPACK</primary></indexterm>
7558       
7559       <para>The <literal>UNPACK</literal> indicates to the compiler
7560       that it should unpack the contents of a constructor field into
7561       the constructor itself, removing a level of indirection.  For
7562       example:</para>
7563
7564 <programlisting>
7565 data T = T {-# UNPACK #-} !Float
7566            {-# UNPACK #-} !Float
7567 </programlisting>
7568
7569       <para>will create a constructor <literal>T</literal> containing
7570       two unboxed floats.  This may not always be an optimisation: if
7571       the <function>T</function> constructor is scrutinised and the
7572       floats passed to a non-strict function for example, they will
7573       have to be reboxed (this is done automatically by the
7574       compiler).</para>
7575
7576       <para>Unpacking constructor fields should only be used in
7577       conjunction with <option>-O</option>, in order to expose
7578       unfoldings to the compiler so the reboxing can be removed as
7579       often as possible.  For example:</para>
7580
7581 <programlisting>
7582 f :: T -&#62; Float
7583 f (T f1 f2) = f1 + f2
7584 </programlisting>
7585
7586       <para>The compiler will avoid reboxing <function>f1</function>
7587       and <function>f2</function> by inlining <function>+</function>
7588       on floats, but only when <option>-O</option> is on.</para>
7589
7590       <para>Any single-constructor data is eligible for unpacking; for
7591       example</para>
7592
7593 <programlisting>
7594 data T = T {-# UNPACK #-} !(Int,Int)
7595 </programlisting>
7596
7597       <para>will store the two <literal>Int</literal>s directly in the
7598       <function>T</function> constructor, by flattening the pair.
7599       Multi-level unpacking is also supported:
7600
7601 <programlisting>
7602 data T = T {-# UNPACK #-} !S
7603 data S = S {-# UNPACK #-} !Int {-# UNPACK #-} !Int
7604 </programlisting>
7605
7606       will store two unboxed <literal>Int&num;</literal>s
7607       directly in the <function>T</function> constructor.  The
7608       unpacker can see through newtypes, too.</para>
7609
7610       <para>If a field cannot be unpacked, you will not get a warning,
7611       so it might be an idea to check the generated code with
7612       <option>-ddump-simpl</option>.</para>
7613
7614       <para>See also the <option>-funbox-strict-fields</option> flag,
7615       which essentially has the effect of adding
7616       <literal>{-#&nbsp;UNPACK&nbsp;#-}</literal> to every strict
7617       constructor field.</para>
7618     </sect2>
7619
7620     <sect2 id="source-pragma">
7621       <title>SOURCE pragma</title>
7622
7623       <indexterm><primary>SOURCE</primary></indexterm>
7624      <para>The <literal>{-# SOURCE #-}</literal> pragma is used only in <literal>import</literal> declarations,
7625      to break a module loop.  It is described in detail in <xref linkend="mutual-recursion"/>.
7626      </para>
7627 </sect2>
7628
7629 </sect1>
7630
7631 <!--  ======================= REWRITE RULES ======================== -->
7632
7633 <sect1 id="rewrite-rules">
7634 <title>Rewrite rules
7635
7636 <indexterm><primary>RULES pragma</primary></indexterm>
7637 <indexterm><primary>pragma, RULES</primary></indexterm>
7638 <indexterm><primary>rewrite rules</primary></indexterm></title>
7639
7640 <para>
7641 The programmer can specify rewrite rules as part of the source program
7642 (in a pragma).  
7643 Here is an example:
7644
7645 <programlisting>
7646   {-# RULES
7647   "map/map"    forall f g xs.  map f (map g xs) = map (f.g) xs
7648     #-}
7649 </programlisting>
7650 </para>
7651 <para>
7652 Use the debug flag <option>-ddump-simpl-stats</option> to see what rules fired.
7653 If you need more information, then <option>-ddump-rule-firings</option> shows you
7654 each individual rule firing in detail.
7655 </para>
7656
7657 <sect2>
7658 <title>Syntax</title>
7659
7660 <para>
7661 From a syntactic point of view:
7662
7663 <itemizedlist>
7664
7665 <listitem>
7666 <para>
7667  There may be zero or more rules in a <literal>RULES</literal> pragma, separated by semicolons (which
7668  may be generated by the layout rule).
7669 </para>
7670 </listitem>
7671
7672 <listitem>
7673 <para>
7674 The layout rule applies in a pragma.
7675 Currently no new indentation level
7676 is set, so if you put several rules in single RULES pragma and wish to use layout to separate them,
7677 you must lay out the starting in the same column as the enclosing definitions.
7678 <programlisting>
7679   {-# RULES
7680   "map/map"    forall f g xs.  map f (map g xs) = map (f.g) xs
7681   "map/append" forall f xs ys. map f (xs ++ ys) = map f xs ++ map f ys
7682     #-}
7683 </programlisting>
7684 Furthermore, the closing <literal>#-}</literal>
7685 should start in a column to the right of the opening <literal>{-#</literal>.
7686 </para>
7687 </listitem>
7688
7689 <listitem>
7690 <para>
7691  Each rule has a name, enclosed in double quotes.  The name itself has
7692 no significance at all.  It is only used when reporting how many times the rule fired.
7693 </para>
7694 </listitem>
7695
7696 <listitem>
7697 <para>
7698 A rule may optionally have a phase-control number (see <xref linkend="phase-control"/>),
7699 immediately after the name of the rule.  Thus:
7700 <programlisting>
7701   {-# RULES
7702         "map/map" [2]  forall f g xs. map f (map g xs) = map (f.g) xs
7703     #-}
7704 </programlisting>
7705 The "[2]" means that the rule is active in Phase 2 and subsequent phases.  The inverse
7706 notation "[~2]" is also accepted, meaning that the rule is active up to, but not including,
7707 Phase 2.
7708 </para>
7709 </listitem>
7710
7711
7712
7713 <listitem>
7714 <para>
7715  Each variable mentioned in a rule must either be in scope (e.g. <function>map</function>),
7716 or bound by the <literal>forall</literal> (e.g. <function>f</function>, <function>g</function>, <function>xs</function>).  The variables bound by
7717 the <literal>forall</literal> are called the <emphasis>pattern</emphasis> variables.  They are separated
7718 by spaces, just like in a type <literal>forall</literal>.
7719 </para>
7720 </listitem>
7721 <listitem>
7722
7723 <para>
7724  A pattern variable may optionally have a type signature.
7725 If the type of the pattern variable is polymorphic, it <emphasis>must</emphasis> have a type signature.
7726 For example, here is the <literal>foldr/build</literal> rule:
7727
7728 <programlisting>
7729 "fold/build"  forall k z (g::forall b. (a->b->b) -> b -> b) .
7730               foldr k z (build g) = g k z
7731 </programlisting>
7732
7733 Since <function>g</function> has a polymorphic type, it must have a type signature.
7734
7735 </para>
7736 </listitem>
7737 <listitem>
7738
7739 <para>
7740 The left hand side of a rule must consist of a top-level variable applied
7741 to arbitrary expressions.  For example, this is <emphasis>not</emphasis> OK:
7742
7743 <programlisting>
7744 "wrong1"   forall e1 e2.  case True of { True -> e1; False -> e2 } = e1
7745 "wrong2"   forall f.      f True = True
7746 </programlisting>
7747
7748 In <literal>"wrong1"</literal>, the LHS is not an application; in <literal>"wrong2"</literal>, the LHS has a pattern variable
7749 in the head.
7750 </para>
7751 </listitem>
7752 <listitem>
7753
7754 <para>
7755  A rule does not need to be in the same module as (any of) the
7756 variables it mentions, though of course they need to be in scope.
7757 </para>
7758 </listitem>
7759 <listitem>
7760
7761 <para>
7762  All rules are implicitly exported from the module, and are therefore
7763 in force in any module that imports the module that defined the rule, directly
7764 or indirectly.  (That is, if A imports B, which imports C, then C's rules are
7765 in force when compiling A.)  The situation is very similar to that for instance
7766 declarations.
7767 </para>
7768 </listitem>
7769
7770 <listitem>
7771
7772 <para>
7773 Inside a RULE "<literal>forall</literal>" is treated as a keyword, regardless of
7774 any other flag settings.  Furthermore, inside a RULE, the language extension
7775 <option>-XScopedTypeVariables</option> is automatically enabled; see 
7776 <xref linkend="scoped-type-variables"/>.
7777 </para>
7778 </listitem>
7779 <listitem>
7780
7781 <para>
7782 Like other pragmas, RULE pragmas are always checked for scope errors, and
7783 are typechecked. Typechecking means that the LHS and RHS of a rule are typechecked, 
7784 and must have the same type.  However, rules are only <emphasis>enabled</emphasis>
7785 if the <option>-fenable-rewrite-rules</option> flag is 
7786 on (see <xref linkend="rule-semantics"/>).
7787 </para>
7788 </listitem>
7789 </itemizedlist>
7790
7791 </para>
7792
7793 </sect2>
7794
7795 <sect2 id="rule-semantics">
7796 <title>Semantics</title>
7797
7798 <para>
7799 From a semantic point of view:
7800
7801 <itemizedlist>
7802 <listitem>
7803 <para>
7804 Rules are enabled (that is, used during optimisation)
7805 by the <option>-fenable-rewrite-rules</option> flag.
7806 This flag is implied by <option>-O</option>, and may be switched
7807 off (as usual) by <option>-fno-enable-rewrite-rules</option>.
7808 (NB: enabling <option>-fenable-rewrite-rules</option> without <option>-O</option> 
7809 may not do what you expect, though, because without <option>-O</option> GHC 
7810 ignores all optimisation information in interface files;
7811 see <option>-fignore-interface-pragmas</option>, <xref linkend="options-f"/>.)
7812 Note that <option>-fenable-rewrite-rules</option> is an <emphasis>optimisation</emphasis> flag, and
7813 has no effect on parsing or typechecking.
7814 </para>
7815 </listitem>
7816
7817 <listitem>
7818 <para>
7819  Rules are regarded as left-to-right rewrite rules.
7820 When GHC finds an expression that is a substitution instance of the LHS
7821 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
7822 By "a substitution instance" we mean that the LHS can be made equal to the
7823 expression by substituting for the pattern variables.
7824
7825 </para>
7826 </listitem>
7827 <listitem>
7828
7829 <para>
7830  GHC makes absolutely no attempt to verify that the LHS and RHS
7831 of a rule have the same meaning.  That is undecidable in general, and
7832 infeasible in most interesting cases.  The responsibility is entirely the programmer's!
7833
7834 </para>
7835 </listitem>
7836 <listitem>
7837
7838 <para>
7839  GHC makes no attempt to make sure that the rules are confluent or
7840 terminating.  For example:
7841
7842 <programlisting>
7843   "loop"        forall x y.  f x y = f y x
7844 </programlisting>
7845
7846 This rule will cause the compiler to go into an infinite loop.
7847
7848 </para>
7849 </listitem>
7850 <listitem>
7851
7852 <para>
7853  If more than one rule matches a call, GHC will choose one arbitrarily to apply.
7854
7855 </para>
7856 </listitem>
7857 <listitem>
7858 <para>
7859  GHC currently uses a very simple, syntactic, matching algorithm
7860 for matching a rule LHS with an expression.  It seeks a substitution
7861 which makes the LHS and expression syntactically equal modulo alpha
7862 conversion.  The pattern (rule), but not the expression, is eta-expanded if
7863 necessary.  (Eta-expanding the expression can lead to laziness bugs.)
7864 But not beta conversion (that's called higher-order matching).
7865 </para>
7866
7867 <para>
7868 Matching is carried out on GHC's intermediate language, which includes
7869 type abstractions and applications.  So a rule only matches if the
7870 types match too.  See <xref linkend="rule-spec"/> below.
7871 </para>
7872 </listitem>
7873 <listitem>
7874
7875 <para>
7876  GHC keeps trying to apply the rules as it optimises the program.
7877 For example, consider:
7878
7879 <programlisting>
7880   let s = map f
7881       t = map g
7882   in
7883   s (t xs)
7884 </programlisting>
7885
7886 The expression <literal>s (t xs)</literal> does not match the rule <literal>"map/map"</literal>, but GHC
7887 will substitute for <varname>s</varname> and <varname>t</varname>, giving an expression which does match.
7888 If <varname>s</varname> or <varname>t</varname> was (a) used more than once, and (b) large or a redex, then it would
7889 not be substituted, and the rule would not fire.
7890
7891 </para>
7892 </listitem>
7893 <listitem>
7894
7895 <para>
7896 Ordinary inlining happens at the same time as rule rewriting, which may lead to unexpected
7897 results.  Consider this (artificial) example
7898 <programlisting>
7899 f x = x
7900 {-# RULES "f" f True = False #-}
7901
7902 g y = f y
7903
7904 h z = g True
7905 </programlisting>
7906 Since <literal>f</literal>'s right-hand side is small, it is inlined into <literal>g</literal>,
7907 to give
7908 <programlisting>
7909 g y = y
7910 </programlisting>
7911 Now <literal>g</literal> is inlined into <literal>h</literal>, but <literal>f</literal>'s RULE has
7912 no chance to fire.  
7913 If instead GHC had first inlined <literal>g</literal> into <literal>h</literal> then there
7914 would have been a better chance that <literal>f</literal>'s RULE might fire.  
7915 </para>
7916 <para>
7917 The way to get predictable behaviour is to use a NOINLINE 
7918 pragma on <literal>f</literal>, to ensure
7919 that it is not inlined until its RULEs have had a chance to fire.
7920 </para>
7921 </listitem>
7922 </itemizedlist>
7923
7924 </para>
7925
7926 </sect2>
7927
7928 <sect2>
7929 <title>List fusion</title>
7930
7931 <para>
7932 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
7933 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
7934 intermediate list should be eliminated entirely.
7935 </para>
7936
7937 <para>
7938 The following are good producers:
7939
7940 <itemizedlist>
7941 <listitem>
7942
7943 <para>
7944  List comprehensions
7945 </para>
7946 </listitem>
7947 <listitem>
7948
7949 <para>
7950  Enumerations of <literal>Int</literal> and <literal>Char</literal> (e.g. <literal>['a'..'z']</literal>).
7951 </para>
7952 </listitem>
7953 <listitem>
7954
7955 <para>
7956  Explicit lists (e.g. <literal>[True, False]</literal>)
7957 </para>
7958 </listitem>
7959 <listitem>
7960
7961 <para>
7962  The cons constructor (e.g <literal>3:4:[]</literal>)
7963 </para>
7964 </listitem>
7965 <listitem>
7966
7967 <para>
7968  <function>++</function>
7969 </para>
7970 </listitem>
7971
7972 <listitem>
7973 <para>
7974  <function>map</function>
7975 </para>
7976 </listitem>
7977
7978 <listitem>
7979 <para>
7980 <function>take</function>, <function>filter</function>
7981 </para>
7982 </listitem>
7983 <listitem>
7984
7985 <para>
7986  <function>iterate</function>, <function>repeat</function>
7987 </para>
7988 </listitem>
7989 <listitem>
7990
7991 <para>
7992  <function>zip</function>, <function>zipWith</function>
7993 </para>
7994 </listitem>
7995
7996 </itemizedlist>
7997
7998 </para>
7999
8000 <para>
8001 The following are good consumers:
8002
8003 <itemizedlist>
8004 <listitem>
8005
8006 <para>
8007  List comprehensions
8008 </para>
8009 </listitem>
8010 <listitem>
8011
8012 <para>
8013  <function>array</function> (on its second argument)
8014 </para>
8015 </listitem>
8016 <listitem>
8017
8018 <para>
8019  <function>++</function> (on its first argument)
8020 </para>
8021 </listitem>
8022
8023 <listitem>
8024 <para>
8025  <function>foldr</function>
8026 </para>
8027 </listitem>
8028
8029 <listitem>
8030 <para>
8031  <function>map</function>
8032 </para>
8033 </listitem>
8034 <listitem>
8035
8036 <para>
8037 <function>take</function>, <function>filter</function>
8038 </para>
8039 </listitem>
8040 <listitem>
8041
8042 <para>
8043  <function>concat</function>
8044 </para>
8045 </listitem>
8046 <listitem>
8047
8048 <para>
8049  <function>unzip</function>, <function>unzip2</function>, <function>unzip3</function>, <function>unzip4</function>
8050 </para>
8051 </listitem>
8052 <listitem>
8053
8054 <para>
8055  <function>zip</function>, <function>zipWith</function> (but on one argument only; if both are good producers, <function>zip</function>
8056 will fuse with one but not the other)
8057 </para>
8058 </listitem>
8059 <listitem>
8060
8061 <para>
8062  <function>partition</function>
8063 </para>
8064 </listitem>
8065 <listitem>
8066
8067 <para>
8068  <function>head</function>
8069 </para>
8070 </listitem>
8071 <listitem>
8072
8073 <para>
8074  <function>and</function>, <function>or</function>, <function>any</function>, <function>all</function>
8075 </para>
8076 </listitem>
8077 <listitem>
8078
8079 <para>
8080  <function>sequence&lowbar;</function>
8081 </para>
8082 </listitem>
8083 <listitem>
8084
8085 <para>
8086  <function>msum</function>
8087 </para>
8088 </listitem>
8089 <listitem>
8090
8091 <para>
8092  <function>sortBy</function>
8093 </para>
8094 </listitem>
8095
8096 </itemizedlist>
8097
8098 </para>
8099
8100  <para>
8101 So, for example, the following should generate no intermediate lists:
8102
8103 <programlisting>
8104 array (1,10) [(i,i*i) | i &#60;- map (+ 1) [0..9]]
8105 </programlisting>
8106
8107 </para>
8108
8109 <para>
8110 This list could readily be extended; if there are Prelude functions that you use
8111 a lot which are not included, please tell us.
8112 </para>
8113
8114 <para>
8115 If you want to write your own good consumers or producers, look at the
8116 Prelude definitions of the above functions to see how to do so.
8117 </para>
8118
8119 </sect2>
8120
8121 <sect2 id="rule-spec">
8122 <title>Specialisation
8123 </title>
8124
8125 <para>
8126 Rewrite rules can be used to get the same effect as a feature
8127 present in earlier versions of GHC.
8128 For example, suppose that:
8129
8130 <programlisting>
8131 genericLookup :: Ord a => Table a b   -> a   -> b
8132 intLookup     ::          Table Int b -> Int -> b
8133 </programlisting>
8134
8135 where <function>intLookup</function> is an implementation of
8136 <function>genericLookup</function> that works very fast for
8137 keys of type <literal>Int</literal>.  You might wish
8138 to tell GHC to use <function>intLookup</function> instead of
8139 <function>genericLookup</function> whenever the latter was called with
8140 type <literal>Table Int b -&gt; Int -&gt; b</literal>.
8141 It used to be possible to write
8142
8143 <programlisting>
8144 {-# SPECIALIZE genericLookup :: Table Int b -> Int -> b = intLookup #-}
8145 </programlisting>
8146
8147 This feature is no longer in GHC, but rewrite rules let you do the same thing:
8148
8149 <programlisting>
8150 {-# RULES "genericLookup/Int" genericLookup = intLookup #-}
8151 </programlisting>
8152
8153 This slightly odd-looking rule instructs GHC to replace
8154 <function>genericLookup</function> by <function>intLookup</function>
8155 <emphasis>whenever the types match</emphasis>.
8156 What is more, this rule does not need to be in the same
8157 file as <function>genericLookup</function>, unlike the
8158 <literal>SPECIALIZE</literal> pragmas which currently do (so that they
8159 have an original definition available to specialise).
8160 </para>
8161
8162 <para>It is <emphasis>Your Responsibility</emphasis> to make sure that
8163 <function>intLookup</function> really behaves as a specialised version
8164 of <function>genericLookup</function>!!!</para>
8165
8166 <para>An example in which using <literal>RULES</literal> for
8167 specialisation will Win Big:
8168
8169 <programlisting>
8170 toDouble :: Real a => a -> Double
8171 toDouble = fromRational . toRational
8172
8173 {-# RULES "toDouble/Int" toDouble = i2d #-}
8174 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
8175 </programlisting>
8176
8177 The <function>i2d</function> function is virtually one machine
8178 instruction; the default conversion&mdash;via an intermediate
8179 <literal>Rational</literal>&mdash;is obscenely expensive by
8180 comparison.
8181 </para>
8182
8183 </sect2>
8184
8185 <sect2>
8186 <title>Controlling what's going on</title>
8187
8188 <para>
8189
8190 <itemizedlist>
8191 <listitem>
8192
8193 <para>
8194  Use <option>-ddump-rules</option> to see what transformation rules GHC is using.
8195 </para>
8196 </listitem>
8197 <listitem>
8198
8199 <para>
8200  Use <option>-ddump-simpl-stats</option> to see what rules are being fired.
8201 If you add <option>-dppr-debug</option> you get a more detailed listing.
8202 </para>
8203 </listitem>
8204 <listitem>
8205
8206 <para>
8207  The definition of (say) <function>build</function> in <filename>GHC/Base.lhs</filename> looks like this:
8208
8209 <programlisting>
8210         build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
8211         {-# INLINE build #-}
8212         build g = g (:) []
8213 </programlisting>
8214
8215 Notice the <literal>INLINE</literal>!  That prevents <literal>(:)</literal> from being inlined when compiling
8216 <literal>PrelBase</literal>, so that an importing module will &ldquo;see&rdquo; the <literal>(:)</literal>, and can
8217 match it on the LHS of a rule.  <literal>INLINE</literal> prevents any inlining happening
8218 in the RHS of the <literal>INLINE</literal> thing.  I regret the delicacy of this.
8219
8220 </para>
8221 </listitem>
8222 <listitem>
8223
8224 <para>
8225  In <filename>libraries/base/GHC/Base.lhs</filename> look at the rules for <function>map</function> to
8226 see how to write rules that will do fusion and yet give an efficient
8227 program even if fusion doesn't happen.  More rules in <filename>GHC/List.lhs</filename>.
8228 </para>
8229 </listitem>
8230
8231 </itemizedlist>
8232
8233 </para>
8234
8235 </sect2>
8236
8237 <sect2 id="core-pragma">
8238   <title>CORE pragma</title>
8239
8240   <indexterm><primary>CORE pragma</primary></indexterm>
8241   <indexterm><primary>pragma, CORE</primary></indexterm>
8242   <indexterm><primary>core, annotation</primary></indexterm>
8243
8244 <para>
8245   The external core format supports <quote>Note</quote> annotations;
8246   the <literal>CORE</literal> pragma gives a way to specify what these
8247   should be in your Haskell source code.  Syntactically, core
8248   annotations are attached to expressions and take a Haskell string
8249   literal as an argument.  The following function definition shows an
8250   example:
8251
8252 <programlisting>
8253 f x = ({-# CORE "foo" #-} show) ({-# CORE "bar" #-} x)
8254 </programlisting>
8255
8256   Semantically, this is equivalent to:
8257
8258 <programlisting>
8259 g x = show x
8260 </programlisting>
8261 </para>
8262
8263 <para>
8264   However, when external core is generated (via
8265   <option>-fext-core</option>), there will be Notes attached to the
8266   expressions <function>show</function> and <varname>x</varname>.
8267   The core function declaration for <function>f</function> is:
8268 </para>
8269
8270 <programlisting>
8271   f :: %forall a . GHCziShow.ZCTShow a ->
8272                    a -> GHCziBase.ZMZN GHCziBase.Char =
8273     \ @ a (zddShow::GHCziShow.ZCTShow a) (eta::a) ->
8274         (%note "foo"
8275          %case zddShow %of (tpl::GHCziShow.ZCTShow a)
8276            {GHCziShow.ZCDShow
8277             (tpl1::GHCziBase.Int ->
8278                    a ->
8279                    GHCziBase.ZMZN GHCziBase.Char -> GHCziBase.ZMZN GHCziBase.Cha
8280 r)
8281             (tpl2::a -> GHCziBase.ZMZN GHCziBase.Char)
8282             (tpl3::GHCziBase.ZMZN a ->
8283                    GHCziBase.ZMZN GHCziBase.Char -> GHCziBase.ZMZN GHCziBase.Cha
8284 r) ->
8285               tpl2})
8286         (%note "bar"
8287          eta);
8288 </programlisting>
8289
8290 <para>
8291   Here, we can see that the function <function>show</function> (which
8292   has been expanded out to a case expression over the Show dictionary)
8293   has a <literal>%note</literal> attached to it, as does the
8294   expression <varname>eta</varname> (which used to be called
8295   <varname>x</varname>).
8296 </para>
8297
8298 </sect2>
8299
8300 </sect1>
8301
8302 <sect1 id="special-ids">
8303 <title>Special built-in functions</title>
8304 <para>GHC has a few built-in functions with special behaviour.  These
8305 are now described in the module <ulink
8306 url="../libraries/ghc-prim/GHC-Prim.html"><literal>GHC.Prim</literal></ulink>
8307 in the library documentation.</para>
8308 </sect1>
8309
8310
8311 <sect1 id="generic-classes">
8312 <title>Generic classes</title>
8313
8314 <para>
8315 The ideas behind this extension are described in detail in "Derivable type classes",
8316 Ralf Hinze and Simon Peyton Jones, Haskell Workshop, Montreal Sept 2000, pp94-105.
8317 An example will give the idea:
8318 </para>
8319
8320 <programlisting>
8321   import Generics
8322
8323   class Bin a where
8324     toBin   :: a -> [Int]
8325     fromBin :: [Int] -> (a, [Int])
8326   
8327     toBin {| Unit |}    Unit      = []
8328     toBin {| a :+: b |} (Inl x)   = 0 : toBin x
8329     toBin {| a :+: b |} (Inr y)   = 1 : toBin y
8330     toBin {| a :*: b |} (x :*: y) = toBin x ++ toBin y
8331   
8332     fromBin {| Unit |}    bs      = (Unit, bs)
8333     fromBin {| a :+: b |} (0:bs)  = (Inl x, bs')    where (x,bs') = fromBin bs
8334     fromBin {| a :+: b |} (1:bs)  = (Inr y, bs')    where (y,bs') = fromBin bs
8335     fromBin {| a :*: b |} bs      = (x :*: y, bs'') where (x,bs' ) = fromBin bs
8336                                                           (y,bs'') = fromBin bs'
8337 </programlisting>
8338 <para>
8339 This class declaration explains how <literal>toBin</literal> and <literal>fromBin</literal>
8340 work for arbitrary data types.  They do so by giving cases for unit, product, and sum,
8341 which are defined thus in the library module <literal>Generics</literal>:
8342 </para>
8343 <programlisting>
8344   data Unit    = Unit
8345   data a :+: b = Inl a | Inr b
8346   data a :*: b = a :*: b
8347 </programlisting>
8348 <para>
8349 Now you can make a data type into an instance of Bin like this:
8350 <programlisting>
8351   instance (Bin a, Bin b) => Bin (a,b)
8352   instance Bin a => Bin [a]
8353 </programlisting>
8354 That is, just leave off the "where" clause.  Of course, you can put in the
8355 where clause and over-ride whichever methods you please.
8356 </para>
8357
8358     <sect2>
8359       <title> Using generics </title>
8360       <para>To use generics you need to</para>
8361       <itemizedlist>
8362         <listitem>
8363           <para>Use the flags <option>-fglasgow-exts</option> (to enable the extra syntax), 
8364                 <option>-XGenerics</option> (to generate extra per-data-type code),
8365                 and <option>-package lang</option> (to make the <literal>Generics</literal> library
8366                 available.  </para>
8367         </listitem>
8368         <listitem>
8369           <para>Import the module <literal>Generics</literal> from the
8370           <literal>lang</literal> package.  This import brings into
8371           scope the data types <literal>Unit</literal>,
8372           <literal>:*:</literal>, and <literal>:+:</literal>.  (You
8373           don't need this import if you don't mention these types
8374           explicitly; for example, if you are simply giving instance
8375           declarations.)</para>
8376         </listitem>
8377       </itemizedlist>
8378     </sect2>
8379
8380 <sect2> <title> Changes wrt the paper </title>
8381 <para>
8382 Note that the type constructors <literal>:+:</literal> and <literal>:*:</literal> 
8383 can be written infix (indeed, you can now use
8384 any operator starting in a colon as an infix type constructor).  Also note that
8385 the type constructors are not exactly as in the paper (Unit instead of 1, etc).
8386 Finally, note that the syntax of the type patterns in the class declaration
8387 uses "<literal>{|</literal>" and "<literal>|}</literal>" brackets; curly braces
8388 alone would ambiguous when they appear on right hand sides (an extension we 
8389 anticipate wanting).
8390 </para>
8391 </sect2>
8392
8393 <sect2> <title>Terminology and restrictions</title>
8394 <para>
8395 Terminology.  A "generic default method" in a class declaration
8396 is one that is defined using type patterns as above.
8397 A "polymorphic default method" is a default method defined as in Haskell 98.
8398 A "generic class declaration" is a class declaration with at least one
8399 generic default method.
8400 </para>
8401
8402 <para>
8403 Restrictions:
8404 <itemizedlist>
8405 <listitem>
8406 <para>
8407 Alas, we do not yet implement the stuff about constructor names and 
8408 field labels.
8409 </para>
8410 </listitem>
8411
8412 <listitem>
8413 <para>
8414 A generic class can have only one parameter; you can't have a generic
8415 multi-parameter class.
8416 </para>
8417 </listitem>
8418
8419 <listitem>
8420 <para>
8421 A default method must be defined entirely using type patterns, or entirely
8422 without.  So this is illegal:
8423 <programlisting>
8424   class Foo a where
8425     op :: a -> (a, Bool)
8426     op {| Unit |} Unit = (Unit, True)
8427     op x               = (x,    False)
8428 </programlisting>
8429 However it is perfectly OK for some methods of a generic class to have 
8430 generic default methods and others to have polymorphic default methods.
8431 </para>
8432 </listitem>
8433
8434 <listitem>
8435 <para>
8436 The type variable(s) in the type pattern for a generic method declaration
8437 scope over the right hand side.  So this is legal (note the use of the type variable ``p'' in a type signature on the right hand side:
8438 <programlisting>
8439   class Foo a where
8440     op :: a -> Bool
8441     op {| p :*: q |} (x :*: y) = op (x :: p)
8442     ...
8443 </programlisting>
8444 </para>
8445 </listitem>
8446
8447 <listitem>
8448 <para>
8449 The type patterns in a generic default method must take one of the forms:
8450 <programlisting>
8451        a :+: b
8452        a :*: b
8453        Unit
8454 </programlisting>
8455 where "a" and "b" are type variables.  Furthermore, all the type patterns for
8456 a single type constructor (<literal>:*:</literal>, say) must be identical; they
8457 must use the same type variables.  So this is illegal:
8458 <programlisting>
8459   class Foo a where
8460     op :: a -> Bool
8461     op {| a :+: b |} (Inl x) = True
8462     op {| p :+: q |} (Inr y) = False
8463 </programlisting>
8464 The type patterns must be identical, even in equations for different methods of the class.
8465 So this too is illegal:
8466 <programlisting>
8467   class Foo a where
8468     op1 :: a -> Bool
8469     op1 {| a :*: b |} (x :*: y) = True
8470
8471     op2 :: a -> Bool
8472     op2 {| p :*: q |} (x :*: y) = False
8473 </programlisting>
8474 (The reason for this restriction is that we gather all the equations for a particular type constructor
8475 into a single generic instance declaration.)
8476 </para>
8477 </listitem>
8478
8479 <listitem>
8480 <para>
8481 A generic method declaration must give a case for each of the three type constructors.
8482 </para>
8483 </listitem>
8484
8485 <listitem>
8486 <para>
8487 The type for a generic method can be built only from:
8488   <itemizedlist>
8489   <listitem> <para> Function arrows </para> </listitem>
8490   <listitem> <para> Type variables </para> </listitem>
8491   <listitem> <para> Tuples </para> </listitem>
8492   <listitem> <para> Arbitrary types not involving type variables </para> </listitem>
8493   </itemizedlist>
8494 Here are some example type signatures for generic methods:
8495 <programlisting>
8496     op1 :: a -> Bool
8497     op2 :: Bool -> (a,Bool)
8498     op3 :: [Int] -> a -> a
8499     op4 :: [a] -> Bool
8500 </programlisting>
8501 Here, op1, op2, op3 are OK, but op4 is rejected, because it has a type variable
8502 inside a list.  
8503 </para>
8504 <para>
8505 This restriction is an implementation restriction: we just haven't got around to
8506 implementing the necessary bidirectional maps over arbitrary type constructors.
8507 It would be relatively easy to add specific type constructors, such as Maybe and list,
8508 to the ones that are allowed.</para>
8509 </listitem>
8510
8511 <listitem>
8512 <para>
8513 In an instance declaration for a generic class, the idea is that the compiler
8514 will fill in the methods for you, based on the generic templates.  However it can only
8515 do so if
8516   <itemizedlist>
8517   <listitem>
8518   <para>
8519   The instance type is simple (a type constructor applied to type variables, as in Haskell 98).
8520   </para>
8521   </listitem>
8522   <listitem>
8523   <para>
8524   No constructor of the instance type has unboxed fields.
8525   </para>
8526   </listitem>
8527   </itemizedlist>
8528 (Of course, these things can only arise if you are already using GHC extensions.)
8529 However, you can still give an instance declarations for types which break these rules,
8530 provided you give explicit code to override any generic default methods.
8531 </para>
8532 </listitem>
8533
8534 </itemizedlist>
8535 </para>
8536
8537 <para>
8538 The option <option>-ddump-deriv</option> dumps incomprehensible stuff giving details of 
8539 what the compiler does with generic declarations.
8540 </para>
8541
8542 </sect2>
8543
8544 <sect2> <title> Another example </title>
8545 <para>
8546 Just to finish with, here's another example I rather like:
8547 <programlisting>
8548   class Tag a where
8549     nCons :: a -> Int
8550     nCons {| Unit |}    _ = 1
8551     nCons {| a :*: b |} _ = 1
8552     nCons {| a :+: b |} _ = nCons (bot::a) + nCons (bot::b)
8553   
8554     tag :: a -> Int
8555     tag {| Unit |}    _       = 1
8556     tag {| a :*: b |} _       = 1   
8557     tag {| a :+: b |} (Inl x) = tag x
8558     tag {| a :+: b |} (Inr y) = nCons (bot::a) + tag y
8559 </programlisting>
8560 </para>
8561 </sect2>
8562 </sect1>
8563
8564 <sect1 id="monomorphism">
8565 <title>Control over monomorphism</title>
8566
8567 <para>GHC supports two flags that control the way in which generalisation is
8568 carried out at let and where bindings.
8569 </para>
8570
8571 <sect2>
8572 <title>Switching off the dreaded Monomorphism Restriction</title>
8573           <indexterm><primary><option>-XNoMonomorphismRestriction</option></primary></indexterm>
8574
8575 <para>Haskell's monomorphism restriction (see 
8576 <ulink url="http://www.haskell.org/onlinereport/decls.html#sect4.5.5">Section
8577 4.5.5</ulink>
8578 of the Haskell Report)
8579 can be completely switched off by
8580 <option>-XNoMonomorphismRestriction</option>.
8581 </para>
8582 </sect2>
8583
8584 <sect2>
8585 <title>Monomorphic pattern bindings</title>
8586           <indexterm><primary><option>-XNoMonoPatBinds</option></primary></indexterm>
8587           <indexterm><primary><option>-XMonoPatBinds</option></primary></indexterm>
8588
8589           <para> As an experimental change, we are exploring the possibility of
8590           making pattern bindings monomorphic; that is, not generalised at all.  
8591             A pattern binding is a binding whose LHS has no function arguments,
8592             and is not a simple variable.  For example:
8593 <programlisting>
8594   f x = x                    -- Not a pattern binding
8595   f = \x -> x                -- Not a pattern binding
8596   f :: Int -> Int = \x -> x  -- Not a pattern binding
8597
8598   (g,h) = e                  -- A pattern binding
8599   (f) = e                    -- A pattern binding
8600   [x] = e                    -- A pattern binding
8601 </programlisting>
8602 Experimentally, GHC now makes pattern bindings monomorphic <emphasis>by
8603 default</emphasis>.  Use <option>-XNoMonoPatBinds</option> to recover the
8604 standard behaviour.
8605 </para>
8606 </sect2>
8607 </sect1>
8608
8609
8610
8611 <!-- Emacs stuff:
8612      ;;; Local Variables: ***
8613      ;;; mode: xml ***
8614      ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") ***
8615      ;;; ispell-local-dictionary: "british" ***
8616      ;;; End: ***
8617  -->
8618