[project @ 2005-04-29 11:08:51 by simonpj]
[ghc-hetmet.git] / ghc / 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>These 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>NB. turning on an option that enables special syntax
46     <emphasis>might</emphasis> cause working Haskell 98 code to fail
47     to compile, perhaps because it uses a variable name which has
48     become a reserved word.  So, together with each option below, we
49     list the special syntax which is enabled by this option.  We use
50     notation and nonterminal names from the Haskell 98 lexical syntax
51     (see the Haskell 98 Report).  There are two classes of special
52     syntax:</para>
53
54     <itemizedlist>
55       <listitem>
56         <para>New reserved words and symbols: character sequences
57         which are no longer available for use as identifiers in the
58         program.</para>
59       </listitem>
60       <listitem>
61         <para>Other special syntax: sequences of characters that have
62         a different meaning when this particular option is turned
63         on.</para>
64       </listitem>
65     </itemizedlist>
66
67     <para>We are only listing syntax changes here that might affect
68     existing working programs (i.e. "stolen" syntax).  Many of these
69     extensions will also enable new context-free syntax, but in all
70     cases programs written to use the new syntax would not be
71     compilable without the option enabled.</para>
72
73     <variablelist>
74
75       <varlistentry>
76         <term>
77           <option>-fglasgow-exts</option>:
78           <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
79         </term>
80         <listitem>
81           <para>This simultaneously enables all of the extensions to
82           Haskell 98 described in <xref
83           linkend="ghc-language-features"/>, except where otherwise
84           noted. </para>
85
86           <para>New reserved words: <literal>forall</literal> (only in
87           types), <literal>mdo</literal>.</para>
88
89           <para>Other syntax stolen:
90               <replaceable>varid</replaceable>{<literal>&num;</literal>},
91               <replaceable>char</replaceable><literal>&num;</literal>,      
92               <replaceable>string</replaceable><literal>&num;</literal>,    
93               <replaceable>integer</replaceable><literal>&num;</literal>,    
94               <replaceable>float</replaceable><literal>&num;</literal>,    
95               <replaceable>float</replaceable><literal>&num;&num;</literal>,    
96               <literal>(&num;</literal>, <literal>&num;)</literal>,         
97               <literal>|)</literal>, <literal>{|</literal>.</para>
98         </listitem>
99       </varlistentry>
100
101       <varlistentry>
102         <term>
103           <option>-ffi</option> and <option>-fffi</option>:
104           <indexterm><primary><option>-ffi</option></primary></indexterm>
105           <indexterm><primary><option>-fffi</option></primary></indexterm>
106         </term>
107         <listitem>
108           <para>This option enables the language extension defined in the
109           Haskell 98 Foreign Function Interface Addendum plus deprecated
110           syntax of previous versions of the FFI for backwards
111           compatibility.</para> 
112
113           <para>New reserved words: <literal>foreign</literal>.</para>
114         </listitem>
115       </varlistentry>
116
117       <varlistentry>
118         <term>
119           <option>-fno-monomorphism-restriction</option>:
120           <indexterm><primary><option>-fno-monomorphism-restriction</option></primary></indexterm>
121         </term>
122         <listitem>
123           <para> Switch off the Haskell 98 monomorphism restriction.
124           Independent of the <option>-fglasgow-exts</option>
125           flag. </para>
126         </listitem>
127       </varlistentry>
128
129       <varlistentry>
130         <term>
131           <option>-fallow-overlapping-instances</option>
132           <indexterm><primary><option>-fallow-overlapping-instances</option></primary></indexterm>
133         </term>
134         <term>
135           <option>-fallow-undecidable-instances</option>
136           <indexterm><primary><option>-fallow-undecidable-instances</option></primary></indexterm>
137         </term>
138         <term>
139           <option>-fallow-incoherent-instances</option>
140           <indexterm><primary><option>-fallow-incoherent-instances</option></primary></indexterm>
141         </term>
142         <term>
143           <option>-fcontext-stack</option>
144           <indexterm><primary><option>-fcontext-stack</option></primary></indexterm>
145         </term>
146         <listitem>
147           <para> See <xref linkend="instance-decls"/>.  Only relevant
148           if you also use <option>-fglasgow-exts</option>.</para>
149         </listitem>
150       </varlistentry>
151
152       <varlistentry>
153         <term>
154           <option>-finline-phase</option>
155           <indexterm><primary><option>-finline-phase</option></primary></indexterm>
156         </term>
157         <listitem>
158           <para>See <xref linkend="rewrite-rules"/>.  Only relevant if
159           you also use <option>-fglasgow-exts</option>.</para>
160         </listitem>
161       </varlistentry>
162
163       <varlistentry>
164         <term>
165           <option>-farrows</option>
166           <indexterm><primary><option>-farrows</option></primary></indexterm>
167         </term>
168         <listitem>
169           <para>See <xref linkend="arrow-notation"/>.  Independent of
170           <option>-fglasgow-exts</option>.</para>
171
172           <para>New reserved words/symbols: <literal>rec</literal>,
173           <literal>proc</literal>, <literal>-&lt;</literal>,
174           <literal>&gt;-</literal>, <literal>-&lt;&lt;</literal>,
175           <literal>&gt;&gt;-</literal>.</para>
176
177           <para>Other syntax stolen: <literal>(|</literal>,
178           <literal>|)</literal>.</para>
179         </listitem>
180       </varlistentry>
181
182       <varlistentry>
183         <term>
184           <option>-fgenerics</option>
185           <indexterm><primary><option>-fgenerics</option></primary></indexterm>
186         </term>
187         <listitem>
188           <para>See <xref linkend="generic-classes"/>.  Independent of
189           <option>-fglasgow-exts</option>.</para>
190         </listitem>
191       </varlistentry>
192
193       <varlistentry>
194         <term><option>-fno-implicit-prelude</option></term>
195         <listitem>
196           <para><indexterm><primary>-fno-implicit-prelude
197           option</primary></indexterm> GHC normally imports
198           <filename>Prelude.hi</filename> files for you.  If you'd
199           rather it didn't, then give it a
200           <option>-fno-implicit-prelude</option> option.  The idea is
201           that you can then import a Prelude of your own.  (But don't
202           call it <literal>Prelude</literal>; the Haskell module
203           namespace is flat, and you must not conflict with any
204           Prelude module.)</para>
205
206           <para>Even though you have not imported the Prelude, most of
207           the built-in syntax still refers to the built-in Haskell
208           Prelude types and values, as specified by the Haskell
209           Report.  For example, the type <literal>[Int]</literal>
210           still means <literal>Prelude.[] Int</literal>; tuples
211           continue to refer to the standard Prelude tuples; the
212           translation for list comprehensions continues to use
213           <literal>Prelude.map</literal> etc.</para>
214
215           <para>However, <option>-fno-implicit-prelude</option> does
216           change the handling of certain built-in syntax: see <xref
217           linkend="rebindable-syntax"/>.</para>
218         </listitem>
219       </varlistentry>
220
221       <varlistentry>
222         <term><option>-fimplicit-params</option></term>
223         <listitem>
224           <para>Enables implicit parameters (see <xref
225           linkend="implicit-parameters"/>).  Currently also implied by 
226           <option>-fglasgow-exts</option>.</para>
227
228           <para>Syntax stolen:
229           <literal>?<replaceable>varid</replaceable></literal>,
230           <literal>%<replaceable>varid</replaceable></literal>.</para>
231         </listitem>
232       </varlistentry>
233
234       <varlistentry>
235         <term><option>-fscoped-type-variables</option></term>
236         <listitem>
237           <para>Enables lexically-scoped type variables (see <xref
238           linkend="scoped-type-variables"/>).  Implied by
239           <option>-fglasgow-exts</option>.</para>
240         </listitem>
241       </varlistentry>
242
243       <varlistentry>
244         <term><option>-fth</option></term>
245         <listitem>
246           <para>Enables Template Haskell (see <xref
247           linkend="template-haskell"/>).  Currently also implied by
248           <option>-fglasgow-exts</option>.</para>
249
250           <para>Syntax stolen: <literal>[|</literal>,
251           <literal>[e|</literal>, <literal>[p|</literal>,
252           <literal>[d|</literal>, <literal>[t|</literal>,
253           <literal>$(</literal>,
254           <literal>$<replaceable>varid</replaceable></literal>.</para>
255         </listitem>
256       </varlistentry>
257
258     </variablelist>
259   </sect1>
260
261 <!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS -->
262 <!--    included from primitives.sgml  -->
263 <!-- &primitives; -->
264 <sect1 id="primitives">
265   <title>Unboxed types and primitive operations</title>
266
267 <para>GHC is built on a raft of primitive data types and operations.
268 While you really can use this stuff to write fast code,
269   we generally find it a lot less painful, and more satisfying in the
270   long run, to use higher-level language features and libraries.  With
271   any luck, the code you write will be optimised to the efficient
272   unboxed version in any case.  And if it isn't, we'd like to know
273   about it.</para>
274
275 <para>We do not currently have good, up-to-date documentation about the
276 primitives, perhaps because they are mainly intended for internal use.
277 There used to be a long section about them here in the User Guide, but it
278 became out of date, and wrong information is worse than none.</para>
279
280 <para>The Real Truth about what primitive types there are, and what operations
281 work over those types, is held in the file
282 <filename>fptools/ghc/compiler/prelude/primops.txt.pp</filename>.
283 This file is used directly to generate GHC's primitive-operation definitions, so
284 it is always correct!  It is also intended for processing into text.</para>
285
286 <para> Indeed,
287 the result of such processing is part of the description of the 
288  <ulink
289       url="http://haskell.cs.yale.edu/ghc/docs/papers/core.ps.gz">External
290          Core language</ulink>.
291 So that document is a good place to look for a type-set version.
292 We would be very happy if someone wanted to volunteer to produce an SGML
293 back end to the program that processes <filename>primops.txt</filename> so that
294 we could include the results here in the User Guide.</para>
295
296 <para>What follows here is a brief summary of some main points.</para>
297   
298 <sect2 id="glasgow-unboxed">
299 <title>Unboxed types
300 </title>
301
302 <para>
303 <indexterm><primary>Unboxed types (Glasgow extension)</primary></indexterm>
304 </para>
305
306 <para>Most types in GHC are <firstterm>boxed</firstterm>, which means
307 that values of that type are represented by a pointer to a heap
308 object.  The representation of a Haskell <literal>Int</literal>, for
309 example, is a two-word heap object.  An <firstterm>unboxed</firstterm>
310 type, however, is represented by the value itself, no pointers or heap
311 allocation are involved.
312 </para>
313
314 <para>
315 Unboxed types correspond to the &ldquo;raw machine&rdquo; types you
316 would use in C: <literal>Int&num;</literal> (long int),
317 <literal>Double&num;</literal> (double), <literal>Addr&num;</literal>
318 (void *), etc.  The <emphasis>primitive operations</emphasis>
319 (PrimOps) on these types are what you might expect; e.g.,
320 <literal>(+&num;)</literal> is addition on
321 <literal>Int&num;</literal>s, and is the machine-addition that we all
322 know and love&mdash;usually one instruction.
323 </para>
324
325 <para>
326 Primitive (unboxed) types cannot be defined in Haskell, and are
327 therefore built into the language and compiler.  Primitive types are
328 always unlifted; that is, a value of a primitive type cannot be
329 bottom.  We use the convention that primitive types, values, and
330 operations have a <literal>&num;</literal> suffix.
331 </para>
332
333 <para>
334 Primitive values are often represented by a simple bit-pattern, such
335 as <literal>Int&num;</literal>, <literal>Float&num;</literal>,
336 <literal>Double&num;</literal>.  But this is not necessarily the case:
337 a primitive value might be represented by a pointer to a
338 heap-allocated object.  Examples include
339 <literal>Array&num;</literal>, the type of primitive arrays.  A
340 primitive array is heap-allocated because it is too big a value to fit
341 in a register, and would be too expensive to copy around; in a sense,
342 it is accidental that it is represented by a pointer.  If a pointer
343 represents a primitive value, then it really does point to that value:
344 no unevaluated thunks, no indirections&hellip;nothing can be at the
345 other end of the pointer than the primitive value.
346 A numerically-intensive program using unboxed types can
347 go a <emphasis>lot</emphasis> faster than its &ldquo;standard&rdquo;
348 counterpart&mdash;we saw a threefold speedup on one example.
349 </para>
350
351 <para>
352 There are some restrictions on the use of primitive types:
353 <itemizedlist>
354 <listitem><para>The main restriction
355 is that you can't pass a primitive value to a polymorphic
356 function or store one in a polymorphic data type.  This rules out
357 things like <literal>[Int&num;]</literal> (i.e. lists of primitive
358 integers).  The reason for this restriction is that polymorphic
359 arguments and constructor fields are assumed to be pointers: if an
360 unboxed integer is stored in one of these, the garbage collector would
361 attempt to follow it, leading to unpredictable space leaks.  Or a
362 <function>seq</function> operation on the polymorphic component may
363 attempt to dereference the pointer, with disastrous results.  Even
364 worse, the unboxed value might be larger than a pointer
365 (<literal>Double&num;</literal> for instance).
366 </para>
367 </listitem>
368 <listitem><para> You cannot bind a variable with an unboxed type
369 in a <emphasis>top-level</emphasis> binding.
370 </para></listitem>
371 <listitem><para> You cannot bind a variable with an unboxed type
372 in a <emphasis>recursive</emphasis> binding.
373 </para></listitem>
374 <listitem><para> You may bind unboxed variables in a (non-recursive,
375 non-top-level) pattern binding, but any such variable causes the entire
376 pattern-match
377 to become strict.  For example:
378 <programlisting>
379   data Foo = Foo Int Int#
380
381   f x = let (Foo a b, w) = ..rhs.. in ..body..
382 </programlisting>
383 Since <literal>b</literal> has type <literal>Int#</literal>, the entire pattern
384 match
385 is strict, and the program behaves as if you had written
386 <programlisting>
387   data Foo = Foo Int Int#
388
389   f x = case ..rhs.. of { (Foo a b, w) -> ..body.. }
390 </programlisting>
391 </para>
392 </listitem>
393 </itemizedlist>
394 </para>
395
396 </sect2>
397
398 <sect2 id="unboxed-tuples">
399 <title>Unboxed Tuples
400 </title>
401
402 <para>
403 Unboxed tuples aren't really exported by <literal>GHC.Exts</literal>,
404 they're available by default with <option>-fglasgow-exts</option>.  An
405 unboxed tuple looks like this:
406 </para>
407
408 <para>
409
410 <programlisting>
411 (# e_1, ..., e_n #)
412 </programlisting>
413
414 </para>
415
416 <para>
417 where <literal>e&lowbar;1..e&lowbar;n</literal> are expressions of any
418 type (primitive or non-primitive).  The type of an unboxed tuple looks
419 the same.
420 </para>
421
422 <para>
423 Unboxed tuples are used for functions that need to return multiple
424 values, but they avoid the heap allocation normally associated with
425 using fully-fledged tuples.  When an unboxed tuple is returned, the
426 components are put directly into registers or on the stack; the
427 unboxed tuple itself does not have a composite representation.  Many
428 of the primitive operations listed in <literal>primops.txt.pp</literal> return unboxed
429 tuples.
430 In particular, the <literal>IO</literal> and <literal>ST</literal> monads use unboxed
431 tuples to avoid unnecessary allocation during sequences of operations.
432 </para>
433
434 <para>
435 There are some pretty stringent restrictions on the use of unboxed tuples:
436 <itemizedlist>
437 <listitem>
438
439 <para>
440 Values of unboxed tuple types are subject to the same restrictions as
441 other unboxed types; i.e. they may not be stored in polymorphic data
442 structures or passed to polymorphic functions.
443
444 </para>
445 </listitem>
446 <listitem>
447
448 <para>
449 No variable can have an unboxed tuple type, nor may a constructor or function
450 argument have an unboxed tuple type.  The following are all illegal:
451
452
453 <programlisting>
454   data Foo = Foo (# Int, Int #)
455
456   f :: (# Int, Int #) -&#62; (# Int, Int #)
457   f x = x
458
459   g :: (# Int, Int #) -&#62; Int
460   g (# a,b #) = a
461
462   h x = let y = (# x,x #) in ...
463 </programlisting>
464 </para>
465 </listitem>
466 </itemizedlist>
467 </para>
468 <para>
469 The typical use of unboxed tuples is simply to return multiple values,
470 binding those multiple results with a <literal>case</literal> expression, thus:
471 <programlisting>
472   f x y = (# x+1, y-1 #)
473   g x = case f x x of { (# a, b #) -&#62; a + b }
474 </programlisting>
475 You can have an unboxed tuple in a pattern binding, thus
476 <programlisting>
477   f x = let (# p,q #) = h x in ..body..
478 </programlisting>
479 If the types of <literal>p</literal> and <literal>q</literal> are not unboxed,
480 the resulting binding is lazy like any other Haskell pattern binding.  The 
481 above example desugars like this:
482 <programlisting>
483   f x = let t = case h x o f{ (# p,q #) -> (p,q)
484             p = fst t
485             q = snd t
486         in ..body..
487 </programlisting>
488 Indeed, the bindings can even be recursive.
489 </para>
490
491 </sect2>
492 </sect1>
493
494
495 <!-- ====================== SYNTACTIC EXTENSIONS =======================  -->
496
497 <sect1 id="syntax-extns">
498 <title>Syntactic extensions</title>
499  
500     <!-- ====================== HIERARCHICAL MODULES =======================  -->
501
502     <sect2 id="hierarchical-modules">
503       <title>Hierarchical Modules</title>
504
505       <para>GHC supports a small extension to the syntax of module
506       names: a module name is allowed to contain a dot
507       <literal>&lsquo;.&rsquo;</literal>.  This is also known as the
508       &ldquo;hierarchical module namespace&rdquo; extension, because
509       it extends the normally flat Haskell module namespace into a
510       more flexible hierarchy of modules.</para>
511
512       <para>This extension has very little impact on the language
513       itself; modules names are <emphasis>always</emphasis> fully
514       qualified, so you can just think of the fully qualified module
515       name as <quote>the module name</quote>.  In particular, this
516       means that the full module name must be given after the
517       <literal>module</literal> keyword at the beginning of the
518       module; for example, the module <literal>A.B.C</literal> must
519       begin</para>
520
521 <programlisting>module A.B.C</programlisting>
522
523
524       <para>It is a common strategy to use the <literal>as</literal>
525       keyword to save some typing when using qualified names with
526       hierarchical modules.  For example:</para>
527
528 <programlisting>
529 import qualified Control.Monad.ST.Strict as ST
530 </programlisting>
531
532       <para>For details on how GHC searches for source and interface
533       files in the presence of hierarchical modules, see <xref
534       linkend="search-path"/>.</para>
535
536       <para>GHC comes with a large collection of libraries arranged
537       hierarchically; see the accompanying library documentation.
538       There is an ongoing project to create and maintain a stable set
539       of <quote>core</quote> libraries used by several Haskell
540       compilers, and the libraries that GHC comes with represent the
541       current status of that project.  For more details, see <ulink
542       url="http://www.haskell.org/~simonmar/libraries/libraries.html">Haskell
543       Libraries</ulink>.</para>
544
545     </sect2>
546
547     <!-- ====================== PATTERN GUARDS =======================  -->
548
549 <sect2 id="pattern-guards">
550 <title>Pattern guards</title>
551
552 <para>
553 <indexterm><primary>Pattern guards (Glasgow extension)</primary></indexterm>
554 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.)
555 </para>
556
557 <para>
558 Suppose we have an abstract data type of finite maps, with a
559 lookup operation:
560
561 <programlisting>
562 lookup :: FiniteMap -> Int -> Maybe Int
563 </programlisting>
564
565 The lookup returns <function>Nothing</function> if the supplied key is not in the domain of the mapping, and <function>(Just v)</function> otherwise,
566 where <varname>v</varname> is the value that the key maps to.  Now consider the following definition:
567 </para>
568
569 <programlisting>
570 clunky env var1 var2 | ok1 &amp;&amp; ok2 = val1 + val2
571 | otherwise  = var1 + var2
572 where
573   m1 = lookup env var1
574   m2 = lookup env var2
575   ok1 = maybeToBool m1
576   ok2 = maybeToBool m2
577   val1 = expectJust m1
578   val2 = expectJust m2
579 </programlisting>
580
581 <para>
582 The auxiliary functions are 
583 </para>
584
585 <programlisting>
586 maybeToBool :: Maybe a -&gt; Bool
587 maybeToBool (Just x) = True
588 maybeToBool Nothing  = False
589
590 expectJust :: Maybe a -&gt; a
591 expectJust (Just x) = x
592 expectJust Nothing  = error "Unexpected Nothing"
593 </programlisting>
594
595 <para>
596 What is <function>clunky</function> doing? The guard <literal>ok1 &amp;&amp;
597 ok2</literal> checks that both lookups succeed, using
598 <function>maybeToBool</function> to convert the <function>Maybe</function>
599 types to booleans. The (lazily evaluated) <function>expectJust</function>
600 calls extract the values from the results of the lookups, and binds the
601 returned values to <varname>val1</varname> and <varname>val2</varname>
602 respectively.  If either lookup fails, then clunky takes the
603 <literal>otherwise</literal> case and returns the sum of its arguments.
604 </para>
605
606 <para>
607 This is certainly legal Haskell, but it is a tremendously verbose and
608 un-obvious way to achieve the desired effect.  Arguably, a more direct way
609 to write clunky would be to use case expressions:
610 </para>
611
612 <programlisting>
613 clunky env var1 var1 = case lookup env var1 of
614   Nothing -&gt; fail
615   Just val1 -&gt; case lookup env var2 of
616     Nothing -&gt; fail
617     Just val2 -&gt; val1 + val2
618 where
619   fail = val1 + val2
620 </programlisting>
621
622 <para>
623 This is a bit shorter, but hardly better.  Of course, we can rewrite any set
624 of pattern-matching, guarded equations as case expressions; that is
625 precisely what the compiler does when compiling equations! The reason that
626 Haskell provides guarded equations is because they allow us to write down
627 the cases we want to consider, one at a time, independently of each other. 
628 This structure is hidden in the case version.  Two of the right-hand sides
629 are really the same (<function>fail</function>), and the whole expression
630 tends to become more and more indented. 
631 </para>
632
633 <para>
634 Here is how I would write clunky:
635 </para>
636
637 <programlisting>
638 clunky env var1 var1
639   | Just val1 &lt;- lookup env var1
640   , Just val2 &lt;- lookup env var2
641   = val1 + val2
642 ...other equations for clunky...
643 </programlisting>
644
645 <para>
646 The semantics should be clear enough.  The qualifiers are matched in order. 
647 For a <literal>&lt;-</literal> qualifier, which I call a pattern guard, the
648 right hand side is evaluated and matched against the pattern on the left. 
649 If the match fails then the whole guard fails and the next equation is
650 tried.  If it succeeds, then the appropriate binding takes place, and the
651 next qualifier is matched, in the augmented environment.  Unlike list
652 comprehensions, however, the type of the expression to the right of the
653 <literal>&lt;-</literal> is the same as the type of the pattern to its
654 left.  The bindings introduced by pattern guards scope over all the
655 remaining guard qualifiers, and over the right hand side of the equation.
656 </para>
657
658 <para>
659 Just as with list comprehensions, boolean expressions can be freely mixed
660 with among the pattern guards.  For example:
661 </para>
662
663 <programlisting>
664 f x | [y] &lt;- x
665     , y > 3
666     , Just z &lt;- h y
667     = ...
668 </programlisting>
669
670 <para>
671 Haskell's current guards therefore emerge as a special case, in which the
672 qualifier list has just one element, a boolean expression.
673 </para>
674 </sect2>
675
676     <!-- ===================== Recursive do-notation ===================  -->
677
678 <sect2 id="mdo-notation">
679 <title>The recursive do-notation
680 </title>
681
682 <para> The recursive do-notation (also known as mdo-notation) is implemented as described in
683 "A recursive do for Haskell",
684 Levent Erkok, John Launchbury",
685 Haskell Workshop 2002, pages: 29-37. Pittsburgh, Pennsylvania. 
686 </para>
687 <para>
688 The do-notation of Haskell does not allow <emphasis>recursive bindings</emphasis>,
689 that is, the variables bound in a do-expression are visible only in the textually following 
690 code block. Compare this to a let-expression, where bound variables are visible in the entire binding
691 group. It turns out that several applications can benefit from recursive bindings in
692 the do-notation, and this extension provides the necessary syntactic support.
693 </para>
694 <para>
695 Here is a simple (yet contrived) example:
696 </para>
697 <programlisting>
698 import Control.Monad.Fix
699
700 justOnes = mdo xs &lt;- Just (1:xs)
701                return xs
702 </programlisting>
703 <para>
704 As you can guess <literal>justOnes</literal> will evaluate to <literal>Just [1,1,1,...</literal>.
705 </para>
706
707 <para>
708 The Control.Monad.Fix library introduces the <literal>MonadFix</literal> class. It's definition is:
709 </para>
710 <programlisting>
711 class Monad m => MonadFix m where
712    mfix :: (a -> m a) -> m a
713 </programlisting>
714 <para>
715 The function <literal>mfix</literal>
716 dictates how the required recursion operation should be performed. If recursive bindings are required for a monad,
717 then that monad must be declared an instance of the <literal>MonadFix</literal> class.
718 For details, see the above mentioned reference.
719 </para>
720 <para>
721 The following instances of <literal>MonadFix</literal> are automatically provided: List, Maybe, IO. 
722 Furthermore, the Control.Monad.ST and Control.Monad.ST.Lazy modules provide the instances of the MonadFix class 
723 for Haskell's internal state monad (strict and lazy, respectively).
724 </para>
725 <para>
726 There are three important points in using the recursive-do notation:
727 <itemizedlist>
728 <listitem><para>
729 The recursive version of the do-notation uses the keyword <literal>mdo</literal> (rather
730 than <literal>do</literal>).
731 </para></listitem>
732
733 <listitem><para>
734 You should <literal>import Control.Monad.Fix</literal>.
735 (Note: Strictly speaking, this import is required only when you need to refer to the name
736 <literal>MonadFix</literal> in your program, but the import is always safe, and the programmers
737 are encouraged to always import this module when using the mdo-notation.)
738 </para></listitem>
739
740 <listitem><para>
741 As with other extensions, ghc should be given the flag <literal>-fglasgow-exts</literal>
742 </para></listitem>
743 </itemizedlist>
744 </para>
745
746 <para>
747 The web page: <ulink url="http://www.cse.ogi.edu/PacSoft/projects/rmb">http://www.cse.ogi.edu/PacSoft/projects/rmb</ulink>
748 contains up to date information on recursive monadic bindings.
749 </para>
750
751 <para>
752 Historical note: The old implementation of the mdo-notation (and most
753 of the existing documents) used the name
754 <literal>MonadRec</literal> for the class and the corresponding library.
755 This name is not supported by GHC.
756 </para>
757
758 </sect2>
759
760
761    <!-- ===================== PARALLEL LIST COMPREHENSIONS ===================  -->
762
763   <sect2 id="parallel-list-comprehensions">
764     <title>Parallel List Comprehensions</title>
765     <indexterm><primary>list comprehensions</primary><secondary>parallel</secondary>
766     </indexterm>
767     <indexterm><primary>parallel list comprehensions</primary>
768     </indexterm>
769
770     <para>Parallel list comprehensions are a natural extension to list
771     comprehensions.  List comprehensions can be thought of as a nice
772     syntax for writing maps and filters.  Parallel comprehensions
773     extend this to include the zipWith family.</para>
774
775     <para>A parallel list comprehension has multiple independent
776     branches of qualifier lists, each separated by a `|' symbol.  For
777     example, the following zips together two lists:</para>
778
779 <programlisting>
780    [ (x, y) | x &lt;- xs | y &lt;- ys ] 
781 </programlisting>
782
783     <para>The behavior of parallel list comprehensions follows that of
784     zip, in that the resulting list will have the same length as the
785     shortest branch.</para>
786
787     <para>We can define parallel list comprehensions by translation to
788     regular comprehensions.  Here's the basic idea:</para>
789
790     <para>Given a parallel comprehension of the form: </para>
791
792 <programlisting>
793    [ e | p1 &lt;- e11, p2 &lt;- e12, ... 
794        | q1 &lt;- e21, q2 &lt;- e22, ... 
795        ... 
796    ] 
797 </programlisting>
798
799     <para>This will be translated to: </para>
800
801 <programlisting>
802    [ e | ((p1,p2), (q1,q2), ...) &lt;- zipN [(p1,p2) | p1 &lt;- e11, p2 &lt;- e12, ...] 
803                                          [(q1,q2) | q1 &lt;- e21, q2 &lt;- e22, ...] 
804                                          ... 
805    ] 
806 </programlisting>
807
808     <para>where `zipN' is the appropriate zip for the given number of
809     branches.</para>
810
811   </sect2>
812
813 <sect2 id="rebindable-syntax">
814 <title>Rebindable syntax</title>
815
816
817       <para>GHC allows most kinds of built-in syntax to be rebound by
818       the user, to facilitate replacing the <literal>Prelude</literal>
819       with a home-grown version, for example.</para>
820
821             <para>You may want to define your own numeric class
822             hierarchy.  It completely defeats that purpose if the
823             literal "1" means "<literal>Prelude.fromInteger
824             1</literal>", which is what the Haskell Report specifies.
825             So the <option>-fno-implicit-prelude</option> flag causes
826             the following pieces of built-in syntax to refer to
827             <emphasis>whatever is in scope</emphasis>, not the Prelude
828             versions:
829
830             <itemizedlist>
831               <listitem>
832                 <para>An integer literal <literal>368</literal> means
833                 "<literal>fromInteger (368::Integer)</literal>", rather than
834                 "<literal>Prelude.fromInteger (368::Integer)</literal>".
835 </para> </listitem>         
836
837       <listitem><para>Fractional literals are handed in just the same way,
838           except that the translation is 
839               <literal>fromRational (3.68::Rational)</literal>.
840 </para> </listitem>         
841
842           <listitem><para>The equality test in an overloaded numeric pattern
843               uses whatever <literal>(==)</literal> is in scope.
844 </para> </listitem>         
845
846           <listitem><para>The subtraction operation, and the
847           greater-than-or-equal test, in <literal>n+k</literal> patterns
848               use whatever <literal>(-)</literal> and <literal>(>=)</literal> are in scope.
849               </para></listitem>
850
851               <listitem>
852                 <para>Negation (e.g. "<literal>- (f x)</literal>")
853                 means "<literal>negate (f x)</literal>", both in numeric
854                 patterns, and expressions.
855               </para></listitem>
856
857               <listitem>
858           <para>"Do" notation is translated using whatever
859               functions <literal>(>>=)</literal>,
860               <literal>(>>)</literal>, and <literal>fail</literal>,
861               are in scope (not the Prelude
862               versions).  List comprehensions, mdo (<xref linkend="mdo-notation"/>), and parallel array
863               comprehensions, are unaffected.  </para></listitem>
864
865               <listitem>
866                 <para>Arrow
867                 notation (see <xref linkend="arrow-notation"/>)
868                 uses whatever <literal>arr</literal>,
869                 <literal>(>>>)</literal>, <literal>first</literal>,
870                 <literal>app</literal>, <literal>(|||)</literal> and
871                 <literal>loop</literal> functions are in scope. But unlike the
872                 other constructs, the types of these functions must match the
873                 Prelude types very closely.  Details are in flux; if you want
874                 to use this, ask!
875               </para></listitem>
876             </itemizedlist>
877 In all cases (apart from arrow notation), the static semantics should be that of the desugared form,
878 even if that is a little unexpected. For emample, the 
879 static semantics of the literal <literal>368</literal>
880 is exactly that of <literal>fromInteger (368::Integer)</literal>; it's fine for
881 <literal>fromInteger</literal> to have any of the types:
882 <programlisting>
883 fromInteger :: Integer -> Integer
884 fromInteger :: forall a. Foo a => Integer -> a
885 fromInteger :: Num a => a -> Integer
886 fromInteger :: Integer -> Bool -> Bool
887 </programlisting>
888 </para>
889                 
890              <para>Be warned: this is an experimental facility, with
891              fewer checks than usual.  Use <literal>-dcore-lint</literal>
892              to typecheck the desugared program.  If Core Lint is happy
893              you should be all right.</para>
894
895 </sect2>
896 </sect1>
897
898
899 <!-- TYPE SYSTEM EXTENSIONS -->
900 <sect1 id="type-extensions">
901 <title>Type system extensions</title>
902
903
904 <sect2>
905 <title>Data types and type synonyms</title>
906
907 <sect3 id="nullary-types">
908 <title>Data types with no constructors</title>
909
910 <para>With the <option>-fglasgow-exts</option> flag, GHC lets you declare
911 a data type with no constructors.  For example:</para>
912
913 <programlisting>
914   data S      -- S :: *
915   data T a    -- T :: * -> *
916 </programlisting>
917
918 <para>Syntactically, the declaration lacks the "= constrs" part.  The 
919 type can be parameterised over types of any kind, but if the kind is
920 not <literal>*</literal> then an explicit kind annotation must be used
921 (see <xref linkend="sec-kinding"/>).</para>
922
923 <para>Such data types have only one value, namely bottom.
924 Nevertheless, they can be useful when defining "phantom types".</para>
925 </sect3>
926
927 <sect3 id="infix-tycons">
928 <title>Infix type constructors, classes, and type variables</title>
929
930 <para>
931 GHC allows type constructors, classes, and type variables to be operators, and
932 to be written infix, very much like expressions.  More specifically:
933 <itemizedlist>
934 <listitem><para>
935   A type constructor or class can be an operator, beginning with a colon; e.g. <literal>:*:</literal>.
936   The lexical syntax is the same as that for data constructors.
937   </para></listitem>
938 <listitem><para>
939   Data type and type-synonym declarations can be written infix, parenthesised
940   if you want further arguments.  E.g.
941 <screen>
942   data a :*: b = Foo a b
943   type a :+: b = Either a b
944   class a :=: b where ...
945
946   data (a :**: b) x = Baz a b x
947   type (a :++: b) y = Either (a,b) y
948 </screen>
949   </para></listitem>
950 <listitem><para>
951   Types, and class constraints, can be written infix.  For example
952   <screen>
953         x :: Int :*: Bool
954         f :: (a :=: b) => a -> b
955   </screen>
956   </para></listitem>
957 <listitem><para>
958   A type variable can be an (unqualified) operator e.g. <literal>+</literal>.
959   The lexical syntax is the same as that for variable operators, excluding "(.)",
960   "(!)", and "(*)".  In a binding position, the operator must be
961   parenthesised.  For example:
962 <programlisting>
963    type T (+) = Int + Int
964    f :: T Either
965    f = Left 3
966  
967    liftA2 :: Arrow (~>)
968           => (a -> b -> c) -> (e ~> a) -> (e ~> b) -> (e ~> c)
969    liftA2 = ...
970 </programlisting>
971   </para></listitem>
972 <listitem><para>
973   Back-quotes work
974   as for expressions, both for type constructors and type variables;  e.g. <literal>Int `Either` Bool</literal>, or
975   <literal>Int `a` Bool</literal>.  Similarly, parentheses work the same; e.g.  <literal>(:*:) Int Bool</literal>.
976   </para></listitem>
977 <listitem><para>
978   Fixities may be declared for type constructors, or classes, just as for data constructors.  However,
979   one cannot distinguish between the two in a fixity declaration; a fixity declaration
980   sets the fixity for a data constructor and the corresponding type constructor.  For example:
981 <screen>
982   infixl 7 T, :*:
983 </screen>
984   sets the fixity for both type constructor <literal>T</literal> and data constructor <literal>T</literal>,
985   and similarly for <literal>:*:</literal>.
986   <literal>Int `a` Bool</literal>.
987   </para></listitem>
988 <listitem><para>
989   Function arrow is <literal>infixr</literal> with fixity 0.  (This might change; I'm not sure what it should be.)
990   </para></listitem>
991
992 </itemizedlist>
993 </para>
994 </sect3>
995
996 <sect3 id="type-synonyms">
997 <title>Liberalised type synonyms</title>
998
999 <para>
1000 Type synonyms are like macros at the type level, and
1001 GHC does validity checking on types <emphasis>only after expanding type synonyms</emphasis>.
1002 That means that GHC can be very much more liberal about type synonyms than Haskell 98:
1003 <itemizedlist>
1004 <listitem> <para>You can write a <literal>forall</literal> (including overloading)
1005 in a type synonym, thus:
1006 <programlisting>
1007   type Discard a = forall b. Show b => a -> b -> (a, String)
1008
1009   f :: Discard a
1010   f x y = (x, show y)
1011
1012   g :: Discard Int -> (Int,Bool)    -- A rank-2 type
1013   g f = f Int True
1014 </programlisting>
1015 </para>
1016 </listitem>
1017
1018 <listitem><para>
1019 You can write an unboxed tuple in a type synonym:
1020 <programlisting>
1021   type Pr = (# Int, Int #)
1022
1023   h :: Int -> Pr
1024   h x = (# x, x #)
1025 </programlisting>
1026 </para></listitem>
1027
1028 <listitem><para>
1029 You can apply a type synonym to a forall type:
1030 <programlisting>
1031   type Foo a = a -> a -> Bool
1032  
1033   f :: Foo (forall b. b->b)
1034 </programlisting>
1035 After expanding the synonym, <literal>f</literal> has the legal (in GHC) type:
1036 <programlisting>
1037   f :: (forall b. b->b) -> (forall b. b->b) -> Bool
1038 </programlisting>
1039 </para></listitem>
1040
1041 <listitem><para>
1042 You can apply a type synonym to a partially applied type synonym:
1043 <programlisting>
1044   type Generic i o = forall x. i x -> o x
1045   type Id x = x
1046   
1047   foo :: Generic Id []
1048 </programlisting>
1049 After expanding the synonym, <literal>foo</literal> has the legal (in GHC) type:
1050 <programlisting>
1051   foo :: forall x. x -> [x]
1052 </programlisting>
1053 </para></listitem>
1054
1055 </itemizedlist>
1056 </para>
1057
1058 <para>
1059 GHC currently does kind checking before expanding synonyms (though even that
1060 could be changed.)
1061 </para>
1062 <para>
1063 After expanding type synonyms, GHC does validity checking on types, looking for
1064 the following mal-formedness which isn't detected simply by kind checking:
1065 <itemizedlist>
1066 <listitem><para>
1067 Type constructor applied to a type involving for-alls.
1068 </para></listitem>
1069 <listitem><para>
1070 Unboxed tuple on left of an arrow.
1071 </para></listitem>
1072 <listitem><para>
1073 Partially-applied type synonym.
1074 </para></listitem>
1075 </itemizedlist>
1076 So, for example,
1077 this will be rejected:
1078 <programlisting>
1079   type Pr = (# Int, Int #)
1080
1081   h :: Pr -> Int
1082   h x = ...
1083 </programlisting>
1084 because GHC does not allow  unboxed tuples on the left of a function arrow.
1085 </para>
1086 </sect3>
1087
1088
1089 <sect3 id="existential-quantification">
1090 <title>Existentially quantified data constructors
1091 </title>
1092
1093 <para>
1094 The idea of using existential quantification in data type declarations
1095 was suggested by Laufer (I believe, thought doubtless someone will
1096 correct me), and implemented in Hope+. It's been in Lennart
1097 Augustsson's <command>hbc</command> Haskell compiler for several years, and
1098 proved very useful.  Here's the idea.  Consider the declaration:
1099 </para>
1100
1101 <para>
1102
1103 <programlisting>
1104   data Foo = forall a. MkFoo a (a -> Bool)
1105            | Nil
1106 </programlisting>
1107
1108 </para>
1109
1110 <para>
1111 The data type <literal>Foo</literal> has two constructors with types:
1112 </para>
1113
1114 <para>
1115
1116 <programlisting>
1117   MkFoo :: forall a. a -> (a -> Bool) -> Foo
1118   Nil   :: Foo
1119 </programlisting>
1120
1121 </para>
1122
1123 <para>
1124 Notice that the type variable <literal>a</literal> in the type of <function>MkFoo</function>
1125 does not appear in the data type itself, which is plain <literal>Foo</literal>.
1126 For example, the following expression is fine:
1127 </para>
1128
1129 <para>
1130
1131 <programlisting>
1132   [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
1133 </programlisting>
1134
1135 </para>
1136
1137 <para>
1138 Here, <literal>(MkFoo 3 even)</literal> packages an integer with a function
1139 <function>even</function> that maps an integer to <literal>Bool</literal>; and <function>MkFoo 'c'
1140 isUpper</function> packages a character with a compatible function.  These
1141 two things are each of type <literal>Foo</literal> and can be put in a list.
1142 </para>
1143
1144 <para>
1145 What can we do with a value of type <literal>Foo</literal>?.  In particular,
1146 what happens when we pattern-match on <function>MkFoo</function>?
1147 </para>
1148
1149 <para>
1150
1151 <programlisting>
1152   f (MkFoo val fn) = ???
1153 </programlisting>
1154
1155 </para>
1156
1157 <para>
1158 Since all we know about <literal>val</literal> and <function>fn</function> is that they
1159 are compatible, the only (useful) thing we can do with them is to
1160 apply <function>fn</function> to <literal>val</literal> to get a boolean.  For example:
1161 </para>
1162
1163 <para>
1164
1165 <programlisting>
1166   f :: Foo -> Bool
1167   f (MkFoo val fn) = fn val
1168 </programlisting>
1169
1170 </para>
1171
1172 <para>
1173 What this allows us to do is to package heterogenous values
1174 together with a bunch of functions that manipulate them, and then treat
1175 that collection of packages in a uniform manner.  You can express
1176 quite a bit of object-oriented-like programming this way.
1177 </para>
1178
1179 <sect4 id="existential">
1180 <title>Why existential?
1181 </title>
1182
1183 <para>
1184 What has this to do with <emphasis>existential</emphasis> quantification?
1185 Simply that <function>MkFoo</function> has the (nearly) isomorphic type
1186 </para>
1187
1188 <para>
1189
1190 <programlisting>
1191   MkFoo :: (exists a . (a, a -> Bool)) -> Foo
1192 </programlisting>
1193
1194 </para>
1195
1196 <para>
1197 But Haskell programmers can safely think of the ordinary
1198 <emphasis>universally</emphasis> quantified type given above, thereby avoiding
1199 adding a new existential quantification construct.
1200 </para>
1201
1202 </sect4>
1203
1204 <sect4>
1205 <title>Type classes</title>
1206
1207 <para>
1208 An easy extension (implemented in <command>hbc</command>) is to allow
1209 arbitrary contexts before the constructor.  For example:
1210 </para>
1211
1212 <para>
1213
1214 <programlisting>
1215 data Baz = forall a. Eq a => Baz1 a a
1216          | forall b. Show b => Baz2 b (b -> b)
1217 </programlisting>
1218
1219 </para>
1220
1221 <para>
1222 The two constructors have the types you'd expect:
1223 </para>
1224
1225 <para>
1226
1227 <programlisting>
1228 Baz1 :: forall a. Eq a => a -> a -> Baz
1229 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
1230 </programlisting>
1231
1232 </para>
1233
1234 <para>
1235 But when pattern matching on <function>Baz1</function> the matched values can be compared
1236 for equality, and when pattern matching on <function>Baz2</function> the first matched
1237 value can be converted to a string (as well as applying the function to it).
1238 So this program is legal:
1239 </para>
1240
1241 <para>
1242
1243 <programlisting>
1244   f :: Baz -> String
1245   f (Baz1 p q) | p == q    = "Yes"
1246                | otherwise = "No"
1247   f (Baz2 v fn)            = show (fn v)
1248 </programlisting>
1249
1250 </para>
1251
1252 <para>
1253 Operationally, in a dictionary-passing implementation, the
1254 constructors <function>Baz1</function> and <function>Baz2</function> must store the
1255 dictionaries for <literal>Eq</literal> and <literal>Show</literal> respectively, and
1256 extract it on pattern matching.
1257 </para>
1258
1259 <para>
1260 Notice the way that the syntax fits smoothly with that used for
1261 universal quantification earlier.
1262 </para>
1263
1264 </sect4>
1265
1266 <sect4>
1267 <title>Restrictions</title>
1268
1269 <para>
1270 There are several restrictions on the ways in which existentially-quantified
1271 constructors can be use.
1272 </para>
1273
1274 <para>
1275
1276 <itemizedlist>
1277 <listitem>
1278
1279 <para>
1280  When pattern matching, each pattern match introduces a new,
1281 distinct, type for each existential type variable.  These types cannot
1282 be unified with any other type, nor can they escape from the scope of
1283 the pattern match.  For example, these fragments are incorrect:
1284
1285
1286 <programlisting>
1287 f1 (MkFoo a f) = a
1288 </programlisting>
1289
1290
1291 Here, the type bound by <function>MkFoo</function> "escapes", because <literal>a</literal>
1292 is the result of <function>f1</function>.  One way to see why this is wrong is to
1293 ask what type <function>f1</function> has:
1294
1295
1296 <programlisting>
1297   f1 :: Foo -> a             -- Weird!
1298 </programlisting>
1299
1300
1301 What is this "<literal>a</literal>" in the result type? Clearly we don't mean
1302 this:
1303
1304
1305 <programlisting>
1306   f1 :: forall a. Foo -> a   -- Wrong!
1307 </programlisting>
1308
1309
1310 The original program is just plain wrong.  Here's another sort of error
1311
1312
1313 <programlisting>
1314   f2 (Baz1 a b) (Baz1 p q) = a==q
1315 </programlisting>
1316
1317
1318 It's ok to say <literal>a==b</literal> or <literal>p==q</literal>, but
1319 <literal>a==q</literal> is wrong because it equates the two distinct types arising
1320 from the two <function>Baz1</function> constructors.
1321
1322
1323 </para>
1324 </listitem>
1325 <listitem>
1326
1327 <para>
1328 You can't pattern-match on an existentially quantified
1329 constructor in a <literal>let</literal> or <literal>where</literal> group of
1330 bindings. So this is illegal:
1331
1332
1333 <programlisting>
1334   f3 x = a==b where { Baz1 a b = x }
1335 </programlisting>
1336
1337 Instead, use a <literal>case</literal> expression:
1338
1339 <programlisting>
1340   f3 x = case x of Baz1 a b -> a==b
1341 </programlisting>
1342
1343 In general, you can only pattern-match
1344 on an existentially-quantified constructor in a <literal>case</literal> expression or
1345 in the patterns of a function definition.
1346
1347 The reason for this restriction is really an implementation one.
1348 Type-checking binding groups is already a nightmare without
1349 existentials complicating the picture.  Also an existential pattern
1350 binding at the top level of a module doesn't make sense, because it's
1351 not clear how to prevent the existentially-quantified type "escaping".
1352 So for now, there's a simple-to-state restriction.  We'll see how
1353 annoying it is.
1354
1355 </para>
1356 </listitem>
1357 <listitem>
1358
1359 <para>
1360 You can't use existential quantification for <literal>newtype</literal>
1361 declarations.  So this is illegal:
1362
1363
1364 <programlisting>
1365   newtype T = forall a. Ord a => MkT a
1366 </programlisting>
1367
1368
1369 Reason: a value of type <literal>T</literal> must be represented as a
1370 pair of a dictionary for <literal>Ord t</literal> and a value of type
1371 <literal>t</literal>.  That contradicts the idea that
1372 <literal>newtype</literal> should have no concrete representation.
1373 You can get just the same efficiency and effect by using
1374 <literal>data</literal> instead of <literal>newtype</literal>.  If
1375 there is no overloading involved, then there is more of a case for
1376 allowing an existentially-quantified <literal>newtype</literal>,
1377 because the <literal>data</literal> version does carry an
1378 implementation cost, but single-field existentially quantified
1379 constructors aren't much use.  So the simple restriction (no
1380 existential stuff on <literal>newtype</literal>) stands, unless there
1381 are convincing reasons to change it.
1382
1383
1384 </para>
1385 </listitem>
1386 <listitem>
1387
1388 <para>
1389  You can't use <literal>deriving</literal> to define instances of a
1390 data type with existentially quantified data constructors.
1391
1392 Reason: in most cases it would not make sense. For example:&num;
1393
1394 <programlisting>
1395 data T = forall a. MkT [a] deriving( Eq )
1396 </programlisting>
1397
1398 To derive <literal>Eq</literal> in the standard way we would need to have equality
1399 between the single component of two <function>MkT</function> constructors:
1400
1401 <programlisting>
1402 instance Eq T where
1403   (MkT a) == (MkT b) = ???
1404 </programlisting>
1405
1406 But <varname>a</varname> and <varname>b</varname> have distinct types, and so can't be compared.
1407 It's just about possible to imagine examples in which the derived instance
1408 would make sense, but it seems altogether simpler simply to prohibit such
1409 declarations.  Define your own instances!
1410 </para>
1411 </listitem>
1412
1413 </itemizedlist>
1414
1415 </para>
1416
1417 </sect4>
1418 </sect3>
1419
1420 </sect2>
1421
1422
1423
1424 <sect2 id="multi-param-type-classes">
1425 <title>Class declarations</title>
1426
1427 <para>
1428 This section documents GHC's implementation of multi-parameter type
1429 classes.  There's lots of background in the paper <ulink
1430 url="http://research.microsoft.com/~simonpj/multi.ps.gz" >Type
1431 classes: exploring the design space</ulink > (Simon Peyton Jones, Mark
1432 Jones, Erik Meijer).
1433 </para>
1434 <para>
1435 There are the following constraints on class declarations:
1436 <orderedlist>
1437 <listitem>
1438
1439 <para>
1440  <emphasis>Multi-parameter type classes are permitted</emphasis>. For example:
1441
1442
1443 <programlisting>
1444   class Collection c a where
1445     union :: c a -> c a -> c a
1446     ...etc.
1447 </programlisting>
1448
1449
1450
1451 </para>
1452 </listitem>
1453 <listitem>
1454
1455 <para>
1456  <emphasis>The class hierarchy must be acyclic</emphasis>.  However, the definition
1457 of "acyclic" involves only the superclass relationships.  For example,
1458 this is OK:
1459
1460
1461 <programlisting>
1462   class C a where {
1463     op :: D b => a -> b -> b
1464   }
1465
1466   class C a => D a where { ... }
1467 </programlisting>
1468
1469
1470 Here, <literal>C</literal> is a superclass of <literal>D</literal>, but it's OK for a
1471 class operation <literal>op</literal> of <literal>C</literal> to mention <literal>D</literal>.  (It
1472 would not be OK for <literal>D</literal> to be a superclass of <literal>C</literal>.)
1473
1474 </para>
1475 </listitem>
1476 <listitem>
1477
1478 <para>
1479  <emphasis>There are no restrictions on the context in a class declaration
1480 (which introduces superclasses), except that the class hierarchy must
1481 be acyclic</emphasis>.  So these class declarations are OK:
1482
1483
1484 <programlisting>
1485   class Functor (m k) => FiniteMap m k where
1486     ...
1487
1488   class (Monad m, Monad (t m)) => Transform t m where
1489     lift :: m a -> (t m) a
1490 </programlisting>
1491
1492
1493 </para>
1494 </listitem>
1495
1496 <listitem>
1497
1498 <para>
1499  <emphasis>All of the class type variables must be reachable (in the sense 
1500 mentioned in <xref linkend="type-restrictions"/>)
1501 from the free variables of each method type
1502 </emphasis>.  For example:
1503
1504
1505 <programlisting>
1506   class Coll s a where
1507     empty  :: s
1508     insert :: s -> a -> s
1509 </programlisting>
1510
1511
1512 is not OK, because the type of <literal>empty</literal> doesn't mention
1513 <literal>a</literal>.  This rule is a consequence of Rule 1(a), above, for
1514 types, and has the same motivation.
1515
1516 Sometimes, offending class declarations exhibit misunderstandings.  For
1517 example, <literal>Coll</literal> might be rewritten
1518
1519
1520 <programlisting>
1521   class Coll s a where
1522     empty  :: s a
1523     insert :: s a -> a -> s a
1524 </programlisting>
1525
1526
1527 which makes the connection between the type of a collection of
1528 <literal>a</literal>'s (namely <literal>(s a)</literal>) and the element type <literal>a</literal>.
1529 Occasionally this really doesn't work, in which case you can split the
1530 class like this:
1531
1532
1533 <programlisting>
1534   class CollE s where
1535     empty  :: s
1536
1537   class CollE s => Coll s a where
1538     insert :: s -> a -> s
1539 </programlisting>
1540
1541
1542 </para>
1543 </listitem>
1544
1545 </orderedlist>
1546 </para>
1547
1548 <sect3 id="class-method-types">
1549 <title>Class method types</title>
1550 <para>
1551 Haskell 98 prohibits class method types to mention constraints on the
1552 class type variable, thus:
1553 <programlisting>
1554   class Seq s a where
1555     fromList :: [a] -> s a
1556     elem     :: Eq a => a -> s a -> Bool
1557 </programlisting>
1558 The type of <literal>elem</literal> is illegal in Haskell 98, because it
1559 contains the constraint <literal>Eq a</literal>, constrains only the 
1560 class type variable (in this case <literal>a</literal>).
1561 </para>
1562 <para>
1563 With the <option>-fglasgow-exts</option> GHC lifts this restriction.
1564 </para>
1565
1566 </sect3>
1567
1568 </sect2>
1569
1570 <sect2 id="type-restrictions">
1571 <title>Type signatures</title>
1572
1573 <sect3><title>The context of a type signature</title>
1574 <para>
1575 Unlike Haskell 98, constraints in types do <emphasis>not</emphasis> have to be of
1576 the form <emphasis>(class type-variable)</emphasis> or
1577 <emphasis>(class (type-variable type-variable ...))</emphasis>.  Thus,
1578 these type signatures are perfectly OK
1579 <programlisting>
1580   g :: Eq [a] => ...
1581   g :: Ord (T a ()) => ...
1582 </programlisting>
1583 </para>
1584 <para>
1585 GHC imposes the following restrictions on the constraints in a type signature.
1586 Consider the type:
1587
1588 <programlisting>
1589   forall tv1..tvn (c1, ...,cn) => type
1590 </programlisting>
1591
1592 (Here, we write the "foralls" explicitly, although the Haskell source
1593 language omits them; in Haskell 98, all the free type variables of an
1594 explicit source-language type signature are universally quantified,
1595 except for the class type variables in a class declaration.  However,
1596 in GHC, you can give the foralls if you want.  See <xref linkend="universal-quantification"/>).
1597 </para>
1598
1599 <para>
1600
1601 <orderedlist>
1602 <listitem>
1603
1604 <para>
1605  <emphasis>Each universally quantified type variable
1606 <literal>tvi</literal> must be reachable from <literal>type</literal></emphasis>.
1607
1608 A type variable <literal>a</literal> is "reachable" if it it appears
1609 in the same constraint as either a type variable free in in
1610 <literal>type</literal>, or another reachable type variable.  
1611 A value with a type that does not obey 
1612 this reachability restriction cannot be used without introducing
1613 ambiguity; that is why the type is rejected.
1614 Here, for example, is an illegal type:
1615
1616
1617 <programlisting>
1618   forall a. Eq a => Int
1619 </programlisting>
1620
1621
1622 When a value with this type was used, the constraint <literal>Eq tv</literal>
1623 would be introduced where <literal>tv</literal> is a fresh type variable, and
1624 (in the dictionary-translation implementation) the value would be
1625 applied to a dictionary for <literal>Eq tv</literal>.  The difficulty is that we
1626 can never know which instance of <literal>Eq</literal> to use because we never
1627 get any more information about <literal>tv</literal>.
1628 </para>
1629 <para>
1630 Note
1631 that the reachability condition is weaker than saying that <literal>a</literal> is
1632 functionally dependent on a type variable free in
1633 <literal>type</literal> (see <xref
1634 linkend="functional-dependencies"/>).  The reason for this is there
1635 might be a "hidden" dependency, in a superclass perhaps.  So
1636 "reachable" is a conservative approximation to "functionally dependent".
1637 For example, consider:
1638 <programlisting>
1639   class C a b | a -> b where ...
1640   class C a b => D a b where ...
1641   f :: forall a b. D a b => a -> a
1642 </programlisting>
1643 This is fine, because in fact <literal>a</literal> does functionally determine <literal>b</literal>
1644 but that is not immediately apparent from <literal>f</literal>'s type.
1645 </para>
1646 </listitem>
1647 <listitem>
1648
1649 <para>
1650  <emphasis>Every constraint <literal>ci</literal> must mention at least one of the
1651 universally quantified type variables <literal>tvi</literal></emphasis>.
1652
1653 For example, this type is OK because <literal>C a b</literal> mentions the
1654 universally quantified type variable <literal>b</literal>:
1655
1656
1657 <programlisting>
1658   forall a. C a b => burble
1659 </programlisting>
1660
1661
1662 The next type is illegal because the constraint <literal>Eq b</literal> does not
1663 mention <literal>a</literal>:
1664
1665
1666 <programlisting>
1667   forall a. Eq b => burble
1668 </programlisting>
1669
1670
1671 The reason for this restriction is milder than the other one.  The
1672 excluded types are never useful or necessary (because the offending
1673 context doesn't need to be witnessed at this point; it can be floated
1674 out).  Furthermore, floating them out increases sharing. Lastly,
1675 excluding them is a conservative choice; it leaves a patch of
1676 territory free in case we need it later.
1677
1678 </para>
1679 </listitem>
1680
1681 </orderedlist>
1682
1683 </para>
1684 </sect3>
1685
1686 <sect3 id="hoist">
1687 <title>For-all hoisting</title>
1688 <para>
1689 It is often convenient to use generalised type synonyms (see <xref linkend="type-synonyms"/>) at the right hand
1690 end of an arrow, thus:
1691 <programlisting>
1692   type Discard a = forall b. a -> b -> a
1693
1694   g :: Int -> Discard Int
1695   g x y z = x+y
1696 </programlisting>
1697 Simply expanding the type synonym would give
1698 <programlisting>
1699   g :: Int -> (forall b. Int -> b -> Int)
1700 </programlisting>
1701 but GHC "hoists" the <literal>forall</literal> to give the isomorphic type
1702 <programlisting>
1703   g :: forall b. Int -> Int -> b -> Int
1704 </programlisting>
1705 In general, the rule is this: <emphasis>to determine the type specified by any explicit
1706 user-written type (e.g. in a type signature), GHC expands type synonyms and then repeatedly
1707 performs the transformation:</emphasis>
1708 <programlisting>
1709   <emphasis>type1</emphasis> -> forall a1..an. <emphasis>context2</emphasis> => <emphasis>type2</emphasis>
1710 ==>
1711   forall a1..an. <emphasis>context2</emphasis> => <emphasis>type1</emphasis> -> <emphasis>type2</emphasis>
1712 </programlisting>
1713 (In fact, GHC tries to retain as much synonym information as possible for use in
1714 error messages, but that is a usability issue.)  This rule applies, of course, whether
1715 or not the <literal>forall</literal> comes from a synonym. For example, here is another
1716 valid way to write <literal>g</literal>'s type signature:
1717 <programlisting>
1718   g :: Int -> Int -> forall b. b -> Int
1719 </programlisting>
1720 </para>
1721 <para>
1722 When doing this hoisting operation, GHC eliminates duplicate constraints.  For
1723 example:
1724 <programlisting>
1725   type Foo a = (?x::Int) => Bool -> a
1726   g :: Foo (Foo Int)
1727 </programlisting>
1728 means
1729 <programlisting>
1730   g :: (?x::Int) => Bool -> Bool -> Int
1731 </programlisting>
1732 </para>
1733 </sect3>
1734
1735
1736 </sect2>
1737
1738 <sect2 id="instance-decls">
1739 <title>Instance declarations</title>
1740
1741 <sect3 id="instance-overlap">
1742 <title>Overlapping instances</title>
1743 <para>
1744 In general, <emphasis>GHC requires that that it be unambiguous which instance
1745 declaration
1746 should be used to resolve a type-class constraint</emphasis>. This behaviour
1747 can be modified by two flags: <option>-fallow-overlapping-instances</option>
1748 <indexterm><primary>-fallow-overlapping-instances
1749 </primary></indexterm> 
1750 and <option>-fallow-incoherent-instances</option>
1751 <indexterm><primary>-fallow-incoherent-instances
1752 </primary></indexterm>, as this section discusses.</para>
1753 <para>
1754 When GHC tries to resolve, say, the constraint <literal>C Int Bool</literal>,
1755 it tries to match every instance declaration against the
1756 constraint,
1757 by instantiating the head of the instance declaration.  For example, consider
1758 these declarations:
1759 <programlisting>
1760   instance context1 => C Int a     where ...  -- (A)
1761   instance context2 => C a   Bool  where ...  -- (B)
1762   instance context3 => C Int [a]   where ...  -- (C)
1763   instance context4 => C Int [Int] where ...  -- (D)
1764 </programlisting>
1765 The instances (A) and (B) match the constraint <literal>C Int Bool</literal>, 
1766 but (C) and (D) do not.  When matching, GHC takes
1767 no account of the context of the instance declaration
1768 (<literal>context1</literal> etc).
1769 GHC's default behaviour is that <emphasis>exactly one instance must match the
1770 constraint it is trying to resolve</emphasis>.  
1771 It is fine for there to be a <emphasis>potential</emphasis> of overlap (by
1772 including both declarations (A) and (B), say); an error is only reported if a 
1773 particular constraint matches more than one.
1774 </para>
1775
1776 <para>
1777 The <option>-fallow-overlapping-instances</option> flag instructs GHC to allow
1778 more than one instance to match, provided there is a most specific one.  For
1779 example, the constraint <literal>C Int [Int]</literal> matches instances (A),
1780 (C) and (D), but the last is more specific, and hence is chosen.  If there is no
1781 most-specific match, the program is rejected.
1782 </para>
1783 <para>
1784 However, GHC is conservative about committing to an overlapping instance.  For example:
1785 <programlisting>
1786   f :: [b] -> [b]
1787   f x = ...
1788 </programlisting>
1789 Suppose that from the RHS of <literal>f</literal> we get the constraint
1790 <literal>C Int [b]</literal>.  But
1791 GHC does not commit to instance (C), because in a particular
1792 call of <literal>f</literal>, <literal>b</literal> might be instantiate 
1793 to <literal>Int</literal>, in which case instance (D) would be more specific still.
1794 So GHC rejects the program.  If you add the flag <option>-fallow-incoherent-instances</option>,
1795 GHC will instead pick (C), without complaining about 
1796 the problem of subsequent instantiations.
1797 </para>
1798 <para>
1799 The willingness to be overlapped or incoherent is a property of 
1800 the <emphasis>instance declaration</emphasis> itself, controlled by the
1801 presence or otherwise of the <option>-fallow-overlapping-instances</option> 
1802 and <option>-fallow-incoherent-instances</option> flags when that mdodule is
1803 being defined.  Neither flag is required in a module that imports and uses the
1804 instance declaration.  Specifically, during the lookup process:
1805 <itemizedlist>
1806 <listitem><para>
1807 An instance declaration is ignored during the lookup process if (a) a more specific
1808 match is found, and (b) the instance declaration was compiled with 
1809 <option>-fallow-overlapping-instances</option>.  The flag setting for the
1810 more-specific instance does not matter.
1811 </para></listitem>
1812 <listitem><para>
1813 Suppose an instance declaration does not matche the constraint being looked up, but
1814 does unify with it, so that it might match when the constraint is further 
1815 instantiated.  Usually GHC will regard this as a reason for not committing to
1816 some other constraint.  But if the instance declaration was compiled with
1817 <option>-fallow-incoherent-instances</option>, GHC will skip the "does-it-unify?" 
1818 check for that declaration.
1819 </para></listitem>
1820 </itemizedlist>
1821 All this makes it possible for a library author to design a library that relies on 
1822 overlapping instances without the library client having to know.
1823 </para>
1824 <para>The <option>-fallow-incoherent-instances</option> flag implies the
1825 <option>-fallow-overlapping-instances</option> flag, but not vice versa.
1826 </sect3>
1827
1828 <sect3>
1829 <title>Type synonyms in the instance head</title>
1830
1831 <para>
1832 <emphasis>Unlike Haskell 98, instance heads may use type
1833 synonyms</emphasis>.  (The instance "head" is the bit after the "=>" in an instance decl.)
1834 As always, using a type synonym is just shorthand for
1835 writing the RHS of the type synonym definition.  For example:
1836
1837
1838 <programlisting>
1839   type Point = (Int,Int)
1840   instance C Point   where ...
1841   instance C [Point] where ...
1842 </programlisting>
1843
1844
1845 is legal.  However, if you added
1846
1847
1848 <programlisting>
1849   instance C (Int,Int) where ...
1850 </programlisting>
1851
1852
1853 as well, then the compiler will complain about the overlapping
1854 (actually, identical) instance declarations.  As always, type synonyms
1855 must be fully applied.  You cannot, for example, write:
1856
1857
1858 <programlisting>
1859   type P a = [[a]]
1860   instance Monad P where ...
1861 </programlisting>
1862
1863
1864 This design decision is independent of all the others, and easily
1865 reversed, but it makes sense to me.
1866
1867 </para>
1868 </sect3>
1869
1870 <sect3 id="undecidable-instances">
1871 <title>Undecidable instances</title>
1872
1873 <para>An instance declaration must normally obey the following rules:
1874 <orderedlist>
1875 <listitem><para>At least one of the types in the <emphasis>head</emphasis> of
1876 an instance declaration <emphasis>must not</emphasis> be a type variable.
1877 For example, these are OK:
1878
1879 <programlisting>
1880   instance C Int a where ...
1881
1882   instance D (Int, Int) where ...
1883
1884   instance E [[a]] where ...
1885 </programlisting>
1886 but this is not:
1887 <programlisting>
1888   instance F a where ...
1889 </programlisting>
1890 Note that instance heads <emphasis>may</emphasis> contain repeated type variables.
1891 For example, this is OK:
1892 <programlisting>
1893   instance Stateful (ST s) (MutVar s) where ...
1894 </programlisting>
1895 </para>
1896 </listitem>
1897
1898
1899 <listitem>
1900 <para>All of the types in the <emphasis>context</emphasis> of
1901 an instance declaration <emphasis>must</emphasis> be type variables.
1902 Thus
1903 <programlisting>
1904 instance C a b => Eq (a,b) where ...
1905 </programlisting>
1906 is OK, but
1907 <programlisting>
1908 instance C Int b => Foo b where ...
1909 </programlisting>
1910 is not OK.
1911 </para>
1912 </listitem>
1913 </orderedlist>
1914 These restrictions ensure that 
1915 context reduction terminates: each reduction step removes one type
1916 constructor.  For example, the following would make the type checker
1917 loop if it wasn't excluded:
1918 <programlisting>
1919   instance C a => C a where ...
1920 </programlisting>
1921 There are two situations in which the rule is a bit of a pain. First,
1922 if one allows overlapping instance declarations then it's quite
1923 convenient to have a "default instance" declaration that applies if
1924 something more specific does not:
1925
1926
1927 <programlisting>
1928   instance C a where
1929     op = ... -- Default
1930 </programlisting>
1931
1932
1933 Second, sometimes you might want to use the following to get the
1934 effect of a "class synonym":
1935
1936
1937 <programlisting>
1938   class (C1 a, C2 a, C3 a) => C a where { }
1939
1940   instance (C1 a, C2 a, C3 a) => C a where { }
1941 </programlisting>
1942
1943
1944 This allows you to write shorter signatures:
1945
1946
1947 <programlisting>
1948   f :: C a => ...
1949 </programlisting>
1950
1951
1952 instead of
1953
1954
1955 <programlisting>
1956   f :: (C1 a, C2 a, C3 a) => ...
1957 </programlisting>
1958
1959
1960 Voluminous correspondence on the Haskell mailing list has convinced me
1961 that it's worth experimenting with more liberal rules.  If you use
1962 the experimental flag <option>-fallow-undecidable-instances</option>
1963 <indexterm><primary>-fallow-undecidable-instances
1964 option</primary></indexterm>, you can use arbitrary
1965 types in both an instance context and instance head.  Termination is ensured by having a
1966 fixed-depth recursion stack.  If you exceed the stack depth you get a
1967 sort of backtrace, and the opportunity to increase the stack depth
1968 with <option>-fcontext-stack</option><emphasis>N</emphasis>.
1969 </para>
1970 <para>
1971 I'm on the lookout for a less brutal solution: a simple rule that preserves decidability while
1972 allowing these idioms interesting idioms.  
1973 </para>
1974 </sect3>
1975
1976
1977 </sect2>
1978
1979 <sect2 id="implicit-parameters">
1980 <title>Implicit parameters</title>
1981
1982 <para> Implicit parameters are implemented as described in 
1983 "Implicit parameters: dynamic scoping with static types", 
1984 J Lewis, MB Shields, E Meijer, J Launchbury,
1985 27th ACM Symposium on Principles of Programming Languages (POPL'00),
1986 Boston, Jan 2000.
1987 </para>
1988
1989 <para>(Most of the following, stil rather incomplete, documentation is
1990 due to Jeff Lewis.)</para>
1991
1992 <para>Implicit parameter support is enabled with the option
1993 <option>-fimplicit-params</option>.</para>
1994
1995 <para>
1996 A variable is called <emphasis>dynamically bound</emphasis> when it is bound by the calling
1997 context of a function and <emphasis>statically bound</emphasis> when bound by the callee's
1998 context. In Haskell, all variables are statically bound. Dynamic
1999 binding of variables is a notion that goes back to Lisp, but was later
2000 discarded in more modern incarnations, such as Scheme. Dynamic binding
2001 can be very confusing in an untyped language, and unfortunately, typed
2002 languages, in particular Hindley-Milner typed languages like Haskell,
2003 only support static scoping of variables.
2004 </para>
2005 <para>
2006 However, by a simple extension to the type class system of Haskell, we
2007 can support dynamic binding. Basically, we express the use of a
2008 dynamically bound variable as a constraint on the type. These
2009 constraints lead to types of the form <literal>(?x::t') => t</literal>, which says "this
2010 function uses a dynamically-bound variable <literal>?x</literal> 
2011 of type <literal>t'</literal>". For
2012 example, the following expresses the type of a sort function,
2013 implicitly parameterized by a comparison function named <literal>cmp</literal>.
2014 <programlisting>
2015   sort :: (?cmp :: a -> a -> Bool) => [a] -> [a]
2016 </programlisting>
2017 The dynamic binding constraints are just a new form of predicate in the type class system.
2018 </para>
2019 <para>
2020 An implicit parameter occurs in an expression using the special form <literal>?x</literal>, 
2021 where <literal>x</literal> is
2022 any valid identifier (e.g. <literal>ord ?x</literal> is a valid expression). 
2023 Use of this construct also introduces a new
2024 dynamic-binding constraint in the type of the expression. 
2025 For example, the following definition
2026 shows how we can define an implicitly parameterized sort function in
2027 terms of an explicitly parameterized <literal>sortBy</literal> function:
2028 <programlisting>
2029   sortBy :: (a -> a -> Bool) -> [a] -> [a]
2030
2031   sort   :: (?cmp :: a -> a -> Bool) => [a] -> [a]
2032   sort    = sortBy ?cmp
2033 </programlisting>
2034 </para>
2035
2036 <sect3>
2037 <title>Implicit-parameter type constraints</title>
2038 <para>
2039 Dynamic binding constraints behave just like other type class
2040 constraints in that they are automatically propagated. Thus, when a
2041 function is used, its implicit parameters are inherited by the
2042 function that called it. For example, our <literal>sort</literal> function might be used
2043 to pick out the least value in a list:
2044 <programlisting>
2045   least   :: (?cmp :: a -> a -> Bool) => [a] -> a
2046   least xs = fst (sort xs)
2047 </programlisting>
2048 Without lifting a finger, the <literal>?cmp</literal> parameter is
2049 propagated to become a parameter of <literal>least</literal> as well. With explicit
2050 parameters, the default is that parameters must always be explicit
2051 propagated. With implicit parameters, the default is to always
2052 propagate them.
2053 </para>
2054 <para>
2055 An implicit-parameter type constraint differs from other type class constraints in the
2056 following way: All uses of a particular implicit parameter must have
2057 the same type. This means that the type of <literal>(?x, ?x)</literal> 
2058 is <literal>(?x::a) => (a,a)</literal>, and not 
2059 <literal>(?x::a, ?x::b) => (a, b)</literal>, as would be the case for type
2060 class constraints.
2061 </para>
2062
2063 <para> You can't have an implicit parameter in the context of a class or instance
2064 declaration.  For example, both these declarations are illegal:
2065 <programlisting>
2066   class (?x::Int) => C a where ...
2067   instance (?x::a) => Foo [a] where ...
2068 </programlisting>
2069 Reason: exactly which implicit parameter you pick up depends on exactly where
2070 you invoke a function. But the ``invocation'' of instance declarations is done
2071 behind the scenes by the compiler, so it's hard to figure out exactly where it is done.
2072 Easiest thing is to outlaw the offending types.</para>
2073 <para>
2074 Implicit-parameter constraints do not cause ambiguity.  For example, consider:
2075 <programlisting>
2076    f :: (?x :: [a]) => Int -> Int
2077    f n = n + length ?x
2078
2079    g :: (Read a, Show a) => String -> String
2080    g s = show (read s)
2081 </programlisting>
2082 Here, <literal>g</literal> has an ambiguous type, and is rejected, but <literal>f</literal>
2083 is fine.  The binding for <literal>?x</literal> at <literal>f</literal>'s call site is 
2084 quite unambiguous, and fixes the type <literal>a</literal>.
2085 </para>
2086 </sect3>
2087
2088 <sect3>
2089 <title>Implicit-parameter bindings</title>
2090
2091 <para>
2092 An implicit parameter is <emphasis>bound</emphasis> using the standard
2093 <literal>let</literal> or <literal>where</literal> binding forms.
2094 For example, we define the <literal>min</literal> function by binding
2095 <literal>cmp</literal>.
2096 <programlisting>
2097   min :: [a] -> a
2098   min  = let ?cmp = (&lt;=) in least
2099 </programlisting>
2100 </para>
2101 <para>
2102 A group of implicit-parameter bindings may occur anywhere a normal group of Haskell
2103 bindings can occur, except at top level.  That is, they can occur in a <literal>let</literal> 
2104 (including in a list comprehension, or do-notation, or pattern guards), 
2105 or a <literal>where</literal> clause.
2106 Note the following points:
2107 <itemizedlist>
2108 <listitem><para>
2109 An implicit-parameter binding group must be a
2110 collection of simple bindings to implicit-style variables (no
2111 function-style bindings, and no type signatures); these bindings are
2112 neither polymorphic or recursive.  
2113 </para></listitem>
2114 <listitem><para>
2115 You may not mix implicit-parameter bindings with ordinary bindings in a 
2116 single <literal>let</literal>
2117 expression; use two nested <literal>let</literal>s instead.
2118 (In the case of <literal>where</literal> you are stuck, since you can't nest <literal>where</literal> clauses.)
2119 </para></listitem>
2120
2121 <listitem><para>
2122 You may put multiple implicit-parameter bindings in a
2123 single binding group; but they are <emphasis>not</emphasis> treated
2124 as a mutually recursive group (as ordinary <literal>let</literal> bindings are).
2125 Instead they are treated as a non-recursive group, simultaneously binding all the implicit
2126 parameter.  The bindings are not nested, and may be re-ordered without changing
2127 the meaning of the program.
2128 For example, consider:
2129 <programlisting>
2130   f t = let { ?x = t; ?y = ?x+(1::Int) } in ?x + ?y
2131 </programlisting>
2132 The use of <literal>?x</literal> in the binding for <literal>?y</literal> does not "see"
2133 the binding for <literal>?x</literal>, so the type of <literal>f</literal> is
2134 <programlisting>
2135   f :: (?x::Int) => Int -> Int
2136 </programlisting>
2137 </para></listitem>
2138 </itemizedlist>
2139 </para>
2140
2141 </sect3>
2142
2143 <sect3><title>Implicit parameters and polymorphic recursion</title>
2144
2145 <para>
2146 Consider these two definitions:
2147 <programlisting>
2148   len1 :: [a] -> Int
2149   len1 xs = let ?acc = 0 in len_acc1 xs
2150
2151   len_acc1 [] = ?acc
2152   len_acc1 (x:xs) = let ?acc = ?acc + (1::Int) in len_acc1 xs
2153
2154   ------------
2155
2156   len2 :: [a] -> Int
2157   len2 xs = let ?acc = 0 in len_acc2 xs
2158
2159   len_acc2 :: (?acc :: Int) => [a] -> Int
2160   len_acc2 [] = ?acc
2161   len_acc2 (x:xs) = let ?acc = ?acc + (1::Int) in len_acc2 xs
2162 </programlisting>
2163 The only difference between the two groups is that in the second group
2164 <literal>len_acc</literal> is given a type signature.
2165 In the former case, <literal>len_acc1</literal> is monomorphic in its own
2166 right-hand side, so the implicit parameter <literal>?acc</literal> is not
2167 passed to the recursive call.  In the latter case, because <literal>len_acc2</literal>
2168 has a type signature, the recursive call is made to the
2169 <emphasis>polymoprhic</emphasis> version, which takes <literal>?acc</literal>
2170 as an implicit parameter.  So we get the following results in GHCi:
2171 <programlisting>
2172   Prog> len1 "hello"
2173   0
2174   Prog> len2 "hello"
2175   5
2176 </programlisting>
2177 Adding a type signature dramatically changes the result!  This is a rather
2178 counter-intuitive phenomenon, worth watching out for.
2179 </para>
2180 </sect3>
2181
2182 <sect3><title>Implicit parameters and monomorphism</title>
2183
2184 <para>GHC applies the dreaded Monomorphism Restriction (section 4.5.5 of the
2185 Haskell Report) to implicit parameters.  For example, consider:
2186 <programlisting>
2187  f :: Int -> Int
2188   f v = let ?x = 0     in
2189         let y = ?x + v in
2190         let ?x = 5     in
2191         y
2192 </programlisting>
2193 Since the binding for <literal>y</literal> falls under the Monomorphism
2194 Restriction it is not generalised, so the type of <literal>y</literal> is
2195 simply <literal>Int</literal>, not <literal>(?x::Int) => Int</literal>.
2196 Hence, <literal>(f 9)</literal> returns result <literal>9</literal>.
2197 If you add a type signature for <literal>y</literal>, then <literal>y</literal>
2198 will get type <literal>(?x::Int) => Int</literal>, so the occurrence of
2199 <literal>y</literal> in the body of the <literal>let</literal> will see the
2200 inner binding of <literal>?x</literal>, so <literal>(f 9)</literal> will return
2201 <literal>14</literal>.
2202 </para>
2203 </sect3>
2204 </sect2>
2205
2206 <sect2 id="linear-implicit-parameters">
2207 <title>Linear implicit parameters</title>
2208 <para>
2209 Linear implicit parameters are an idea developed by Koen Claessen,
2210 Mark Shields, and Simon PJ.  They address the long-standing
2211 problem that monads seem over-kill for certain sorts of problem, notably:
2212 </para>
2213 <itemizedlist>
2214 <listitem> <para> distributing a supply of unique names </para> </listitem>
2215 <listitem> <para> distributing a supply of random numbers </para> </listitem>
2216 <listitem> <para> distributing an oracle (as in QuickCheck) </para> </listitem>
2217 </itemizedlist>
2218
2219 <para>
2220 Linear implicit parameters are just like ordinary implicit parameters,
2221 except that they are "linear" -- that is, they cannot be copied, and
2222 must be explicitly "split" instead.  Linear implicit parameters are
2223 written '<literal>%x</literal>' instead of '<literal>?x</literal>'.  
2224 (The '/' in the '%' suggests the split!)
2225 </para>
2226 <para>
2227 For example:
2228 <programlisting>
2229     import GHC.Exts( Splittable )
2230
2231     data NameSupply = ...
2232     
2233     splitNS :: NameSupply -> (NameSupply, NameSupply)
2234     newName :: NameSupply -> Name
2235
2236     instance Splittable NameSupply where
2237         split = splitNS
2238
2239
2240     f :: (%ns :: NameSupply) => Env -> Expr -> Expr
2241     f env (Lam x e) = Lam x' (f env e)
2242                     where
2243                       x'   = newName %ns
2244                       env' = extend env x x'
2245     ...more equations for f...
2246 </programlisting>
2247 Notice that the implicit parameter %ns is consumed 
2248 <itemizedlist>
2249 <listitem> <para> once by the call to <literal>newName</literal> </para> </listitem>
2250 <listitem> <para> once by the recursive call to <literal>f</literal> </para></listitem>
2251 </itemizedlist>
2252 </para>
2253 <para>
2254 So the translation done by the type checker makes
2255 the parameter explicit:
2256 <programlisting>
2257     f :: NameSupply -> Env -> Expr -> Expr
2258     f ns env (Lam x e) = Lam x' (f ns1 env e)
2259                        where
2260                          (ns1,ns2) = splitNS ns
2261                          x' = newName ns2
2262                          env = extend env x x'
2263 </programlisting>
2264 Notice the call to 'split' introduced by the type checker.
2265 How did it know to use 'splitNS'?  Because what it really did
2266 was to introduce a call to the overloaded function 'split',
2267 defined by the class <literal>Splittable</literal>:
2268 <programlisting>
2269         class Splittable a where
2270           split :: a -> (a,a)
2271 </programlisting>
2272 The instance for <literal>Splittable NameSupply</literal> tells GHC how to implement
2273 split for name supplies.  But we can simply write
2274 <programlisting>
2275         g x = (x, %ns, %ns)
2276 </programlisting>
2277 and GHC will infer
2278 <programlisting>
2279         g :: (Splittable a, %ns :: a) => b -> (b,a,a)
2280 </programlisting>
2281 The <literal>Splittable</literal> class is built into GHC.  It's exported by module 
2282 <literal>GHC.Exts</literal>.
2283 </para>
2284 <para>
2285 Other points:
2286 <itemizedlist>
2287 <listitem> <para> '<literal>?x</literal>' and '<literal>%x</literal>' 
2288 are entirely distinct implicit parameters: you 
2289   can use them together and they won't intefere with each other. </para>
2290 </listitem>
2291
2292 <listitem> <para> You can bind linear implicit parameters in 'with' clauses. </para> </listitem>
2293
2294 <listitem> <para>You cannot have implicit parameters (whether linear or not)
2295   in the context of a class or instance declaration. </para></listitem>
2296 </itemizedlist>
2297 </para>
2298
2299 <sect3><title>Warnings</title>
2300
2301 <para>
2302 The monomorphism restriction is even more important than usual.
2303 Consider the example above:
2304 <programlisting>
2305     f :: (%ns :: NameSupply) => Env -> Expr -> Expr
2306     f env (Lam x e) = Lam x' (f env e)
2307                     where
2308                       x'   = newName %ns
2309                       env' = extend env x x'
2310 </programlisting>
2311 If we replaced the two occurrences of x' by (newName %ns), which is
2312 usually a harmless thing to do, we get:
2313 <programlisting>
2314     f :: (%ns :: NameSupply) => Env -> Expr -> Expr
2315     f env (Lam x e) = Lam (newName %ns) (f env e)
2316                     where
2317                       env' = extend env x (newName %ns)
2318 </programlisting>
2319 But now the name supply is consumed in <emphasis>three</emphasis> places
2320 (the two calls to newName,and the recursive call to f), so
2321 the result is utterly different.  Urk!  We don't even have 
2322 the beta rule.
2323 </para>
2324 <para>
2325 Well, this is an experimental change.  With implicit
2326 parameters we have already lost beta reduction anyway, and
2327 (as John Launchbury puts it) we can't sensibly reason about
2328 Haskell programs without knowing their typing.
2329 </para>
2330
2331 </sect3>
2332
2333 <sect3><title>Recursive functions</title>
2334 <para>Linear implicit parameters can be particularly tricky when you have a recursive function
2335 Consider
2336 <programlisting>
2337         foo :: %x::T => Int -> [Int]
2338         foo 0 = []
2339         foo n = %x : foo (n-1)
2340 </programlisting>
2341 where T is some type in class Splittable.</para>
2342 <para>
2343 Do you get a list of all the same T's or all different T's
2344 (assuming that split gives two distinct T's back)?
2345 </para><para>
2346 If you supply the type signature, taking advantage of polymorphic
2347 recursion, you get what you'd probably expect.  Here's the
2348 translated term, where the implicit param is made explicit:
2349 <programlisting>
2350         foo x 0 = []
2351         foo x n = let (x1,x2) = split x
2352                   in x1 : foo x2 (n-1)
2353 </programlisting>
2354 But if you don't supply a type signature, GHC uses the Hindley
2355 Milner trick of using a single monomorphic instance of the function
2356 for the recursive calls. That is what makes Hindley Milner type inference
2357 work.  So the translation becomes
2358 <programlisting>
2359         foo x = let
2360                   foom 0 = []
2361                   foom n = x : foom (n-1)
2362                 in
2363                 foom
2364 </programlisting>
2365 Result: 'x' is not split, and you get a list of identical T's.  So the
2366 semantics of the program depends on whether or not foo has a type signature.
2367 Yikes!
2368 </para><para>
2369 You may say that this is a good reason to dislike linear implicit parameters
2370 and you'd be right.  That is why they are an experimental feature. 
2371 </para>
2372 </sect3>
2373
2374 </sect2>
2375
2376 <sect2 id="functional-dependencies">
2377 <title>Functional dependencies
2378 </title>
2379
2380 <para> Functional dependencies are implemented as described by Mark Jones
2381 in &ldquo;<ulink url="http://www.cse.ogi.edu/~mpj/pubs/fundeps.html">Type Classes with Functional Dependencies</ulink>&rdquo;, Mark P. Jones, 
2382 In Proceedings of the 9th European Symposium on Programming, 
2383 ESOP 2000, Berlin, Germany, March 2000, Springer-Verlag LNCS 1782,
2384 .
2385 </para>
2386 <para>
2387 Functional dependencies are introduced by a vertical bar in the syntax of a 
2388 class declaration;  e.g. 
2389 <programlisting>
2390   class (Monad m) => MonadState s m | m -> s where ...
2391
2392   class Foo a b c | a b -> c where ...
2393 </programlisting>
2394 There should be more documentation, but there isn't (yet).  Yell if you need it.
2395 </para>
2396 </sect2>
2397
2398
2399
2400 <sect2 id="sec-kinding">
2401 <title>Explicitly-kinded quantification</title>
2402
2403 <para>
2404 Haskell infers the kind of each type variable.  Sometimes it is nice to be able
2405 to give the kind explicitly as (machine-checked) documentation, 
2406 just as it is nice to give a type signature for a function.  On some occasions,
2407 it is essential to do so.  For example, in his paper "Restricted Data Types in Haskell" (Haskell Workshop 1999)
2408 John Hughes had to define the data type:
2409 <screen>
2410      data Set cxt a = Set [a]
2411                     | Unused (cxt a -> ())
2412 </screen>
2413 The only use for the <literal>Unused</literal> constructor was to force the correct
2414 kind for the type variable <literal>cxt</literal>.
2415 </para>
2416 <para>
2417 GHC now instead allows you to specify the kind of a type variable directly, wherever
2418 a type variable is explicitly bound.  Namely:
2419 <itemizedlist>
2420 <listitem><para><literal>data</literal> declarations:
2421 <screen>
2422   data Set (cxt :: * -> *) a = Set [a]
2423 </screen></para></listitem>
2424 <listitem><para><literal>type</literal> declarations:
2425 <screen>
2426   type T (f :: * -> *) = f Int
2427 </screen></para></listitem>
2428 <listitem><para><literal>class</literal> declarations:
2429 <screen>
2430   class (Eq a) => C (f :: * -> *) a where ...
2431 </screen></para></listitem>
2432 <listitem><para><literal>forall</literal>'s in type signatures:
2433 <screen>
2434   f :: forall (cxt :: * -> *). Set cxt Int
2435 </screen></para></listitem>
2436 </itemizedlist>
2437 </para>
2438
2439 <para>
2440 The parentheses are required.  Some of the spaces are required too, to
2441 separate the lexemes.  If you write <literal>(f::*->*)</literal> you
2442 will get a parse error, because "<literal>::*->*</literal>" is a
2443 single lexeme in Haskell.
2444 </para>
2445
2446 <para>
2447 As part of the same extension, you can put kind annotations in types
2448 as well.  Thus:
2449 <screen>
2450    f :: (Int :: *) -> Int
2451    g :: forall a. a -> (a :: *)
2452 </screen>
2453 The syntax is
2454 <screen>
2455    atype ::= '(' ctype '::' kind ')
2456 </screen>
2457 The parentheses are required.
2458 </para>
2459 </sect2>
2460
2461
2462 <sect2 id="universal-quantification">
2463 <title>Arbitrary-rank polymorphism
2464 </title>
2465
2466 <para>
2467 Haskell type signatures are implicitly quantified.  The new keyword <literal>forall</literal>
2468 allows us to say exactly what this means.  For example:
2469 </para>
2470 <para>
2471 <programlisting>
2472         g :: b -> b
2473 </programlisting>
2474 means this:
2475 <programlisting>
2476         g :: forall b. (b -> b)
2477 </programlisting>
2478 The two are treated identically.
2479 </para>
2480
2481 <para>
2482 However, GHC's type system supports <emphasis>arbitrary-rank</emphasis> 
2483 explicit universal quantification in
2484 types. 
2485 For example, all the following types are legal:
2486 <programlisting>
2487     f1 :: forall a b. a -> b -> a
2488     g1 :: forall a b. (Ord a, Eq  b) => a -> b -> a
2489
2490     f2 :: (forall a. a->a) -> Int -> Int
2491     g2 :: (forall a. Eq a => [a] -> a -> Bool) -> Int -> Int
2492
2493     f3 :: ((forall a. a->a) -> Int) -> Bool -> Bool
2494 </programlisting>
2495 Here, <literal>f1</literal> and <literal>g1</literal> are rank-1 types, and
2496 can be written in standard Haskell (e.g. <literal>f1 :: a->b->a</literal>).
2497 The <literal>forall</literal> makes explicit the universal quantification that
2498 is implicitly added by Haskell.
2499 </para>
2500 <para>
2501 The functions <literal>f2</literal> and <literal>g2</literal> have rank-2 types;
2502 the <literal>forall</literal> is on the left of a function arrow.  As <literal>g2</literal>
2503 shows, the polymorphic type on the left of the function arrow can be overloaded.
2504 </para>
2505 <para>
2506 The function <literal>f3</literal> has a rank-3 type;
2507 it has rank-2 types on the left of a function arrow.
2508 </para>
2509 <para>
2510 GHC allows types of arbitrary rank; you can nest <literal>forall</literal>s
2511 arbitrarily deep in function arrows.   (GHC used to be restricted to rank 2, but
2512 that restriction has now been lifted.)
2513 In particular, a forall-type (also called a "type scheme"),
2514 including an operational type class context, is legal:
2515 <itemizedlist>
2516 <listitem> <para> On the left of a function arrow </para> </listitem>
2517 <listitem> <para> On the right of a function arrow (see <xref linkend="hoist"/>) </para> </listitem>
2518 <listitem> <para> As the argument of a constructor, or type of a field, in a data type declaration. For
2519 example, any of the <literal>f1,f2,f3,g1,g2</literal> above would be valid
2520 field type signatures.</para> </listitem>
2521 <listitem> <para> As the type of an implicit parameter </para> </listitem>
2522 <listitem> <para> In a pattern type signature (see <xref linkend="scoped-type-variables"/>) </para> </listitem>
2523 </itemizedlist>
2524 There is one place you cannot put a <literal>forall</literal>:
2525 you cannot instantiate a type variable with a forall-type.  So you cannot 
2526 make a forall-type the argument of a type constructor.  So these types are illegal:
2527 <programlisting>
2528     x1 :: [forall a. a->a]
2529     x2 :: (forall a. a->a, Int)
2530     x3 :: Maybe (forall a. a->a)
2531 </programlisting>
2532 Of course <literal>forall</literal> becomes a keyword; you can't use <literal>forall</literal> as
2533 a type variable any more!
2534 </para>
2535
2536
2537 <sect3 id="univ">
2538 <title>Examples
2539 </title>
2540
2541 <para>
2542 In a <literal>data</literal> or <literal>newtype</literal> declaration one can quantify
2543 the types of the constructor arguments.  Here are several examples:
2544 </para>
2545
2546 <para>
2547
2548 <programlisting>
2549 data T a = T1 (forall b. b -> b -> b) a
2550
2551 data MonadT m = MkMonad { return :: forall a. a -> m a,
2552                           bind   :: forall a b. m a -> (a -> m b) -> m b
2553                         }
2554
2555 newtype Swizzle = MkSwizzle (Ord a => [a] -> [a])
2556 </programlisting>
2557
2558 </para>
2559
2560 <para>
2561 The constructors have rank-2 types:
2562 </para>
2563
2564 <para>
2565
2566 <programlisting>
2567 T1 :: forall a. (forall b. b -> b -> b) -> a -> T a
2568 MkMonad :: forall m. (forall a. a -> m a)
2569                   -> (forall a b. m a -> (a -> m b) -> m b)
2570                   -> MonadT m
2571 MkSwizzle :: (Ord a => [a] -> [a]) -> Swizzle
2572 </programlisting>
2573
2574 </para>
2575
2576 <para>
2577 Notice that you don't need to use a <literal>forall</literal> if there's an
2578 explicit context.  For example in the first argument of the
2579 constructor <function>MkSwizzle</function>, an implicit "<literal>forall a.</literal>" is
2580 prefixed to the argument type.  The implicit <literal>forall</literal>
2581 quantifies all type variables that are not already in scope, and are
2582 mentioned in the type quantified over.
2583 </para>
2584
2585 <para>
2586 As for type signatures, implicit quantification happens for non-overloaded
2587 types too.  So if you write this:
2588
2589 <programlisting>
2590   data T a = MkT (Either a b) (b -> b)
2591 </programlisting>
2592
2593 it's just as if you had written this:
2594
2595 <programlisting>
2596   data T a = MkT (forall b. Either a b) (forall b. b -> b)
2597 </programlisting>
2598
2599 That is, since the type variable <literal>b</literal> isn't in scope, it's
2600 implicitly universally quantified.  (Arguably, it would be better
2601 to <emphasis>require</emphasis> explicit quantification on constructor arguments
2602 where that is what is wanted.  Feedback welcomed.)
2603 </para>
2604
2605 <para>
2606 You construct values of types <literal>T1, MonadT, Swizzle</literal> by applying
2607 the constructor to suitable values, just as usual.  For example,
2608 </para>
2609
2610 <para>
2611
2612 <programlisting>
2613     a1 :: T Int
2614     a1 = T1 (\xy->x) 3
2615     
2616     a2, a3 :: Swizzle
2617     a2 = MkSwizzle sort
2618     a3 = MkSwizzle reverse
2619     
2620     a4 :: MonadT Maybe
2621     a4 = let r x = Just x
2622              b m k = case m of
2623                        Just y -> k y
2624                        Nothing -> Nothing
2625          in
2626          MkMonad r b
2627
2628     mkTs :: (forall b. b -> b -> b) -> a -> [T a]
2629     mkTs f x y = [T1 f x, T1 f y]
2630 </programlisting>
2631
2632 </para>
2633
2634 <para>
2635 The type of the argument can, as usual, be more general than the type
2636 required, as <literal>(MkSwizzle reverse)</literal> shows.  (<function>reverse</function>
2637 does not need the <literal>Ord</literal> constraint.)
2638 </para>
2639
2640 <para>
2641 When you use pattern matching, the bound variables may now have
2642 polymorphic types.  For example:
2643 </para>
2644
2645 <para>
2646
2647 <programlisting>
2648     f :: T a -> a -> (a, Char)
2649     f (T1 w k) x = (w k x, w 'c' 'd')
2650
2651     g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b]
2652     g (MkSwizzle s) xs f = s (map f (s xs))
2653
2654     h :: MonadT m -> [m a] -> m [a]
2655     h m [] = return m []
2656     h m (x:xs) = bind m x          $ \y ->
2657                  bind m (h m xs)   $ \ys ->
2658                  return m (y:ys)
2659 </programlisting>
2660
2661 </para>
2662
2663 <para>
2664 In the function <function>h</function> we use the record selectors <literal>return</literal>
2665 and <literal>bind</literal> to extract the polymorphic bind and return functions
2666 from the <literal>MonadT</literal> data structure, rather than using pattern
2667 matching.
2668 </para>
2669 </sect3>
2670
2671 <sect3>
2672 <title>Type inference</title>
2673
2674 <para>
2675 In general, type inference for arbitrary-rank types is undecidable.
2676 GHC uses an algorithm proposed by Odersky and Laufer ("Putting type annotations to work", POPL'96)
2677 to get a decidable algorithm by requiring some help from the programmer.
2678 We do not yet have a formal specification of "some help" but the rule is this:
2679 </para>
2680 <para>
2681 <emphasis>For a lambda-bound or case-bound variable, x, either the programmer
2682 provides an explicit polymorphic type for x, or GHC's type inference will assume
2683 that x's type has no foralls in it</emphasis>.
2684 </para>
2685 <para>
2686 What does it mean to "provide" an explicit type for x?  You can do that by 
2687 giving a type signature for x directly, using a pattern type signature
2688 (<xref linkend="scoped-type-variables"/>), thus:
2689 <programlisting>
2690      \ f :: (forall a. a->a) -> (f True, f 'c')
2691 </programlisting>
2692 Alternatively, you can give a type signature to the enclosing
2693 context, which GHC can "push down" to find the type for the variable:
2694 <programlisting>
2695      (\ f -> (f True, f 'c')) :: (forall a. a->a) -> (Bool,Char)
2696 </programlisting>
2697 Here the type signature on the expression can be pushed inwards
2698 to give a type signature for f.  Similarly, and more commonly,
2699 one can give a type signature for the function itself:
2700 <programlisting>
2701      h :: (forall a. a->a) -> (Bool,Char)
2702      h f = (f True, f 'c')
2703 </programlisting>
2704 You don't need to give a type signature if the lambda bound variable
2705 is a constructor argument.  Here is an example we saw earlier:
2706 <programlisting>
2707     f :: T a -> a -> (a, Char)
2708     f (T1 w k) x = (w k x, w 'c' 'd')
2709 </programlisting>
2710 Here we do not need to give a type signature to <literal>w</literal>, because
2711 it is an argument of constructor <literal>T1</literal> and that tells GHC all
2712 it needs to know.
2713 </para>
2714
2715 </sect3>
2716
2717
2718 <sect3 id="implicit-quant">
2719 <title>Implicit quantification</title>
2720
2721 <para>
2722 GHC performs implicit quantification as follows.  <emphasis>At the top level (only) of 
2723 user-written types, if and only if there is no explicit <literal>forall</literal>,
2724 GHC finds all the type variables mentioned in the type that are not already
2725 in scope, and universally quantifies them.</emphasis>  For example, the following pairs are 
2726 equivalent:
2727 <programlisting>
2728   f :: a -> a
2729   f :: forall a. a -> a
2730
2731   g (x::a) = let
2732                 h :: a -> b -> b
2733                 h x y = y
2734              in ...
2735   g (x::a) = let
2736                 h :: forall b. a -> b -> b
2737                 h x y = y
2738              in ...
2739 </programlisting>
2740 </para>
2741 <para>
2742 Notice that GHC does <emphasis>not</emphasis> find the innermost possible quantification
2743 point.  For example:
2744 <programlisting>
2745   f :: (a -> a) -> Int
2746            -- MEANS
2747   f :: forall a. (a -> a) -> Int
2748            -- NOT
2749   f :: (forall a. a -> a) -> Int
2750
2751
2752   g :: (Ord a => a -> a) -> Int
2753            -- MEANS the illegal type
2754   g :: forall a. (Ord a => a -> a) -> Int
2755            -- NOT
2756   g :: (forall a. Ord a => a -> a) -> Int
2757 </programlisting>
2758 The latter produces an illegal type, which you might think is silly,
2759 but at least the rule is simple.  If you want the latter type, you
2760 can write your for-alls explicitly.  Indeed, doing so is strongly advised
2761 for rank-2 types.
2762 </para>
2763 </sect3>
2764 </sect2>
2765
2766
2767
2768
2769 <sect2 id="scoped-type-variables">
2770 <title>Scoped type variables
2771 </title>
2772
2773 <para>
2774 A <emphasis>lexically scoped type variable</emphasis> can be bound by:
2775 <itemizedlist>
2776 <listitem><para>A declaration type signature (<xref linkend="decl-type-sigs"/>)</para></listitem>
2777 <listitem><para>A pattern type signature (<xref linkend="pattern-type-sigs"/>)</para></listitem>
2778 <listitem><para>A result type signature (<xref linkend="result-type-sigs"/>)</para></listitem>
2779 </itemizedlist>
2780 For example:
2781 <programlisting>
2782 f (xs::[a]) = ys ++ ys
2783            where
2784               ys :: [a]
2785               ys = reverse xs
2786 </programlisting>
2787 The pattern <literal>(xs::[a])</literal> includes a type signature for <varname>xs</varname>.
2788 This brings the type variable <literal>a</literal> into scope; it scopes over
2789 all the patterns and right hand sides for this equation for <function>f</function>.
2790 In particular, it is in scope at the type signature for <varname>y</varname>.
2791 </para>
2792
2793 <para>
2794 At ordinary type signatures, such as that for <varname>ys</varname>, any type variables
2795 mentioned in the type signature <emphasis>that are not in scope</emphasis> are
2796 implicitly universally quantified.  (If there are no type variables in
2797 scope, all type variables mentioned in the signature are universally
2798 quantified, which is just as in Haskell 98.)  In this case, since <varname>a</varname>
2799 is in scope, it is not universally quantified, so the type of <varname>ys</varname> is
2800 the same as that of <varname>xs</varname>.  In Haskell 98 it is not possible to declare
2801 a type for <varname>ys</varname>; a major benefit of scoped type variables is that
2802 it becomes possible to do so.
2803 </para>
2804
2805 <para>
2806 Scoped type variables are implemented in both GHC and Hugs.  Where the
2807 implementations differ from the specification below, those differences
2808 are noted.
2809 </para>
2810
2811 <para>
2812 So much for the basic idea.  Here are the details.
2813 </para>
2814
2815 <sect3>
2816 <title>What a scoped type variable means</title>
2817 <para>
2818 A lexically-scoped type variable is simply
2819 the name for a type.   The restriction it expresses is that all occurrences
2820 of the same name mean the same type.  For example:
2821 <programlisting>
2822   f :: [Int] -> Int -> Int
2823   f (xs::[a]) (y::a) = (head xs + y) :: a
2824 </programlisting>
2825 The pattern type signatures on the left hand side of
2826 <literal>f</literal> express the fact that <literal>xs</literal>
2827 must be a list of things of some type <literal>a</literal>; and that <literal>y</literal>
2828 must have this same type.  The type signature on the expression <literal>(head xs)</literal>
2829 specifies that this expression must have the same type <literal>a</literal>.
2830 <emphasis>There is no requirement that the type named by "<literal>a</literal>" is
2831 in fact a type variable</emphasis>.  Indeed, in this case, the type named by "<literal>a</literal>" is
2832 <literal>Int</literal>.  (This is a slight liberalisation from the original rather complex
2833 rules, which specified that a pattern-bound type variable should be universally quantified.)
2834 For example, all of these are legal:</para>
2835
2836 <programlisting>
2837   t (x::a) (y::a) = x+y*2
2838
2839   f (x::a) (y::b) = [x,y]       -- a unifies with b
2840
2841   g (x::a) = x + 1::Int         -- a unifies with Int
2842
2843   h x = let k (y::a) = [x,y]    -- a is free in the
2844         in k x                  -- environment
2845
2846   k (x::a) True    = ...        -- a unifies with Int
2847   k (x::Int) False = ...
2848
2849   w :: [b] -> [b]
2850   w (x::a) = x                  -- a unifies with [b]
2851 </programlisting>
2852
2853 </sect3>
2854
2855 <sect3>
2856 <title>Scope and implicit quantification</title>
2857
2858 <para>
2859
2860 <itemizedlist>
2861 <listitem>
2862
2863 <para>
2864 All the type variables mentioned in a pattern,
2865 that are not already in scope,
2866 are brought into scope by the pattern.  We describe this set as
2867 the <emphasis>type variables bound by the pattern</emphasis>.
2868 For example:
2869 <programlisting>
2870   f (x::a) = let g (y::(a,b)) = fst y
2871              in
2872              g (x,True)
2873 </programlisting>
2874 The pattern <literal>(x::a)</literal> brings the type variable
2875 <literal>a</literal> into scope, as well as the term 
2876 variable <literal>x</literal>.  The pattern <literal>(y::(a,b))</literal>
2877 contains an occurrence of the already-in-scope type variable <literal>a</literal>,
2878 and brings into scope the type variable <literal>b</literal>.
2879 </para>
2880 </listitem>
2881
2882 <listitem>
2883 <para>
2884 The type variable(s) bound by the pattern have the same scope
2885 as the term variable(s) bound by the pattern.  For example:
2886 <programlisting>
2887   let
2888     f (x::a) = &lt;...rhs of f...>
2889     (p::b, q::b) = (1,2)
2890   in &lt;...body of let...>
2891 </programlisting>
2892 Here, the type variable <literal>a</literal> scopes over the right hand side of <literal>f</literal>,
2893 just like <literal>x</literal> does; while the type variable <literal>b</literal> scopes over the
2894 body of the <literal>let</literal>, and all the other definitions in the <literal>let</literal>,
2895 just like <literal>p</literal> and <literal>q</literal> do.
2896 Indeed, the newly bound type variables also scope over any ordinary, separate
2897 type signatures in the <literal>let</literal> group.
2898 </para>
2899 </listitem>
2900
2901
2902 <listitem>
2903 <para>
2904 The type variables bound by the pattern may be 
2905 mentioned in ordinary type signatures or pattern 
2906 type signatures anywhere within their scope.
2907
2908 </para>
2909 </listitem>
2910
2911 <listitem>
2912 <para>
2913  In ordinary type signatures, any type variable mentioned in the
2914 signature that is in scope is <emphasis>not</emphasis> universally quantified.
2915
2916 </para>
2917 </listitem>
2918
2919 <listitem>
2920
2921 <para>
2922  Ordinary type signatures do not bring any new type variables
2923 into scope (except in the type signature itself!). So this is illegal:
2924
2925 <programlisting>
2926   f :: a -> a
2927   f x = x::a
2928 </programlisting>
2929
2930 It's illegal because <varname>a</varname> is not in scope in the body of <function>f</function>,
2931 so the ordinary signature <literal>x::a</literal> is equivalent to <literal>x::forall a.a</literal>;
2932 and that is an incorrect typing.
2933
2934 </para>
2935 </listitem>
2936
2937 <listitem>
2938 <para>
2939 The pattern type signature is a monotype:
2940 </para>
2941
2942 <itemizedlist>
2943 <listitem> <para> 
2944 A pattern type signature cannot contain any explicit <literal>forall</literal> quantification.
2945 </para> </listitem>
2946
2947 <listitem>  <para> 
2948 The type variables bound by a pattern type signature can only be instantiated to monotypes,
2949 not to type schemes.
2950 </para> </listitem>
2951
2952 <listitem>  <para> 
2953 There is no implicit universal quantification on pattern type signatures (in contrast to
2954 ordinary type signatures).
2955 </para> </listitem>
2956
2957 </itemizedlist>
2958
2959 </listitem>
2960
2961 <listitem>
2962 <para>
2963
2964 The type variables in the head of a <literal>class</literal> or <literal>instance</literal> declaration
2965 scope over the methods defined in the <literal>where</literal> part.  For example:
2966
2967
2968 <programlisting>
2969   class C a where
2970     op :: [a] -> a
2971
2972     op xs = let ys::[a]
2973                 ys = reverse xs
2974             in
2975             head ys
2976 </programlisting>
2977
2978
2979 (Not implemented in Hugs yet, Dec 98).
2980 </para>
2981 </listitem>
2982
2983 </itemizedlist>
2984
2985 </para>
2986
2987 </sect3>
2988
2989 <sect3 id="decl-type-sigs">
2990 <title>Declaration type signatures</title>
2991 <para>A declaration type signature that has <emphasis>explicit</emphasis>
2992 quantification (using <literal>forall</literal>) brings into scope the
2993 explicitly-quantified
2994 type variables, in the definition of the named function(s).  For example:
2995 <programlisting>
2996   f :: forall a. [a] -> [a]
2997   f (x:xs) = xs ++ [ x :: a ]
2998 </programlisting>
2999 The "<literal>forall a</literal>" brings "<literal>a</literal>" into scope in
3000 the definition of "<literal>f</literal>".
3001 </para>
3002 <para>This only happens if the quantification in <literal>f</literal>'s type
3003 signature is explicit.  For example:
3004 <programlisting>
3005   g :: [a] -> [a]
3006   g (x:xs) = xs ++ [ x :: a ]
3007 </programlisting>
3008 This program will be rejected, because "<literal>a</literal>" does not scope
3009 over the definition of "<literal>f</literal>", so "<literal>x::a</literal>"
3010 means "<literal>x::forall a. a</literal>" by Haskell's usual implicit
3011 quantification rules.
3012 </para>
3013 </sect3>
3014
3015 <sect3 id="pattern-type-sigs">
3016 <title>Where a pattern type signature can occur</title>
3017
3018 <para>
3019 A pattern type signature can occur in any pattern.  For example:
3020 <itemizedlist>
3021
3022 <listitem>
3023 <para>
3024 A pattern type signature can be on an arbitrary sub-pattern, not
3025 just on a variable:
3026
3027
3028 <programlisting>
3029   f ((x,y)::(a,b)) = (y,x) :: (b,a)
3030 </programlisting>
3031
3032
3033 </para>
3034 </listitem>
3035 <listitem>
3036
3037 <para>
3038  Pattern type signatures, including the result part, can be used
3039 in lambda abstractions:
3040
3041 <programlisting>
3042   (\ (x::a, y) :: a -> x)
3043 </programlisting>
3044 </para>
3045 </listitem>
3046 <listitem>
3047
3048 <para>
3049  Pattern type signatures, including the result part, can be used
3050 in <literal>case</literal> expressions:
3051
3052 <programlisting>
3053   case e of { ((x::a, y) :: (a,b)) -> x }
3054 </programlisting>
3055
3056 Note that the <literal>-&gt;</literal> symbol in a case alternative
3057 leads to difficulties when parsing a type signature in the pattern: in
3058 the absence of the extra parentheses in the example above, the parser
3059 would try to interpret the <literal>-&gt;</literal> as a function
3060 arrow and give a parse error later.
3061
3062 </para>
3063
3064 </listitem>
3065
3066 <listitem>
3067 <para>
3068 To avoid ambiguity, the type after the &ldquo;<literal>::</literal>&rdquo; in a result
3069 pattern signature on a lambda or <literal>case</literal> must be atomic (i.e. a single
3070 token or a parenthesised type of some sort).  To see why,
3071 consider how one would parse this:
3072
3073
3074 <programlisting>
3075   \ x :: a -> b -> x
3076 </programlisting>
3077
3078
3079 </para>
3080 </listitem>
3081
3082 <listitem>
3083
3084 <para>
3085  Pattern type signatures can bind existential type variables.
3086 For example:
3087
3088
3089 <programlisting>
3090   data T = forall a. MkT [a]
3091
3092   f :: T -> T
3093   f (MkT [t::a]) = MkT t3
3094                  where
3095                    t3::[a] = [t,t,t]
3096 </programlisting>
3097
3098
3099 </para>
3100 </listitem>
3101
3102
3103 <listitem>
3104
3105 <para>
3106 Pattern type signatures 
3107 can be used in pattern bindings:
3108
3109 <programlisting>
3110   f x = let (y, z::a) = x in ...
3111   f1 x                = let (y, z::Int) = x in ...
3112   f2 (x::(Int,a))     = let (y, z::a)   = x in ...
3113   f3 :: (b->b)        = \x -> x
3114 </programlisting>
3115
3116 In all such cases, the binding is not generalised over the pattern-bound
3117 type variables.  Thus <literal>f3</literal> is monomorphic; <literal>f3</literal>
3118 has type <literal>b -&gt; b</literal> for some type <literal>b</literal>, 
3119 and <emphasis>not</emphasis> <literal>forall b. b -&gt; b</literal>.
3120 In contrast, the binding
3121 <programlisting>
3122   f4 :: b->b
3123   f4 = \x -> x
3124 </programlisting>
3125 makes a polymorphic function, but <literal>b</literal> is not in scope anywhere
3126 in <literal>f4</literal>'s scope.
3127
3128 </para>
3129 </listitem>
3130 </itemizedlist>
3131 </para>
3132 <para>Pattern type signatures are completely orthogonal to ordinary, separate
3133 type signatures.  The two can be used independently or together.</para>
3134
3135 </sect3>
3136
3137 <sect3 id="result-type-sigs">
3138 <title>Result type signatures</title>
3139
3140 <para>
3141 The result type of a function can be given a signature, thus:
3142
3143
3144 <programlisting>
3145   f (x::a) :: [a] = [x,x,x]
3146 </programlisting>
3147
3148
3149 The final <literal>:: [a]</literal> after all the patterns gives a signature to the
3150 result type.  Sometimes this is the only way of naming the type variable
3151 you want:
3152
3153
3154 <programlisting>
3155   f :: Int -> [a] -> [a]
3156   f n :: ([a] -> [a]) = let g (x::a, y::a) = (y,x)
3157                         in \xs -> map g (reverse xs `zip` xs)
3158 </programlisting>
3159
3160 </para>
3161 <para>
3162 The type variables bound in a result type signature scope over the right hand side
3163 of the definition. However, consider this corner-case:
3164 <programlisting>
3165   rev1 :: [a] -> [a] = \xs -> reverse xs
3166
3167   foo ys = rev (ys::[a])
3168 </programlisting>
3169 The signature on <literal>rev1</literal> is considered a pattern type signature, not a result
3170 type signature, and the type variables it binds have the same scope as <literal>rev1</literal>
3171 itself (i.e. the right-hand side of <literal>rev1</literal> and the rest of the module too).
3172 In particular, the expression <literal>(ys::[a])</literal> is OK, because the type variable <literal>a</literal>
3173 is in scope (otherwise it would mean <literal>(ys::forall a.[a])</literal>, which would be rejected).  
3174 </para>
3175 <para>
3176 As mentioned above, <literal>rev1</literal> is made monomorphic by this scoping rule.
3177 For example, the following program would be rejected, because it claims that <literal>rev1</literal>
3178 is polymorphic:
3179 <programlisting>
3180   rev1 :: [b] -> [b]
3181   rev1 :: [a] -> [a] = \xs -> reverse xs
3182 </programlisting>
3183 </para>
3184
3185 <para>
3186 Result type signatures are not yet implemented in Hugs.
3187 </para>
3188
3189 </sect3>
3190
3191 </sect2>
3192
3193 <sect2 id="deriving-typeable">
3194 <title>Deriving clause for classes <literal>Typeable</literal> and <literal>Data</literal></title>
3195
3196 <para>
3197 Haskell 98 allows the programmer to add "<literal>deriving( Eq, Ord )</literal>" to a data type 
3198 declaration, to generate a standard instance declaration for classes specified in the <literal>deriving</literal> clause.  
3199 In Haskell 98, the only classes that may appear in the <literal>deriving</literal> clause are the standard
3200 classes <literal>Eq</literal>, <literal>Ord</literal>, 
3201 <literal>Enum</literal>, <literal>Ix</literal>, <literal>Bounded</literal>, <literal>Read</literal>, and <literal>Show</literal>.
3202 </para>
3203 <para>
3204 GHC extends this list with two more classes that may be automatically derived 
3205 (provided the <option>-fglasgow-exts</option> flag is specified):
3206 <literal>Typeable</literal>, and <literal>Data</literal>.  These classes are defined in the library
3207 modules <literal>Data.Typeable</literal> and <literal>Data.Generics</literal> respectively, and the
3208 appropriate class must be in scope before it can be mentioned in the <literal>deriving</literal> clause.
3209 </para>
3210 </sect2>
3211
3212 <sect2 id="newtype-deriving">
3213 <title>Generalised derived instances for newtypes</title>
3214
3215 <para>
3216 When you define an abstract type using <literal>newtype</literal>, you may want
3217 the new type to inherit some instances from its representation. In
3218 Haskell 98, you can inherit instances of <literal>Eq</literal>, <literal>Ord</literal>,
3219 <literal>Enum</literal> and <literal>Bounded</literal> by deriving them, but for any
3220 other classes you have to write an explicit instance declaration. For
3221 example, if you define
3222
3223 <programlisting> 
3224   newtype Dollars = Dollars Int 
3225 </programlisting> 
3226
3227 and you want to use arithmetic on <literal>Dollars</literal>, you have to
3228 explicitly define an instance of <literal>Num</literal>:
3229
3230 <programlisting> 
3231   instance Num Dollars where
3232     Dollars a + Dollars b = Dollars (a+b)
3233     ...
3234 </programlisting>
3235 All the instance does is apply and remove the <literal>newtype</literal>
3236 constructor. It is particularly galling that, since the constructor
3237 doesn't appear at run-time, this instance declaration defines a
3238 dictionary which is <emphasis>wholly equivalent</emphasis> to the <literal>Int</literal>
3239 dictionary, only slower!
3240 </para>
3241
3242
3243 <sect3> <title> Generalising the deriving clause </title>
3244 <para>
3245 GHC now permits such instances to be derived instead, so one can write 
3246 <programlisting> 
3247   newtype Dollars = Dollars Int deriving (Eq,Show,Num)
3248 </programlisting> 
3249
3250 and the implementation uses the <emphasis>same</emphasis> <literal>Num</literal> dictionary
3251 for <literal>Dollars</literal> as for <literal>Int</literal>. Notionally, the compiler
3252 derives an instance declaration of the form
3253
3254 <programlisting> 
3255   instance Num Int => Num Dollars
3256 </programlisting> 
3257
3258 which just adds or removes the <literal>newtype</literal> constructor according to the type.
3259 </para>
3260 <para>
3261
3262 We can also derive instances of constructor classes in a similar
3263 way. For example, suppose we have implemented state and failure monad
3264 transformers, such that
3265
3266 <programlisting> 
3267   instance Monad m => Monad (State s m) 
3268   instance Monad m => Monad (Failure m)
3269 </programlisting> 
3270 In Haskell 98, we can define a parsing monad by 
3271 <programlisting> 
3272   type Parser tok m a = State [tok] (Failure m) a
3273 </programlisting> 
3274
3275 which is automatically a monad thanks to the instance declarations
3276 above. With the extension, we can make the parser type abstract,
3277 without needing to write an instance of class <literal>Monad</literal>, via
3278
3279 <programlisting> 
3280   newtype Parser tok m a = Parser (State [tok] (Failure m) a)
3281                          deriving Monad
3282 </programlisting>
3283 In this case the derived instance declaration is of the form 
3284 <programlisting> 
3285   instance Monad (State [tok] (Failure m)) => Monad (Parser tok m) 
3286 </programlisting> 
3287
3288 Notice that, since <literal>Monad</literal> is a constructor class, the
3289 instance is a <emphasis>partial application</emphasis> of the new type, not the
3290 entire left hand side. We can imagine that the type declaration is
3291 ``eta-converted'' to generate the context of the instance
3292 declaration.
3293 </para>
3294 <para>
3295
3296 We can even derive instances of multi-parameter classes, provided the
3297 newtype is the last class parameter. In this case, a ``partial
3298 application'' of the class appears in the <literal>deriving</literal>
3299 clause. For example, given the class
3300
3301 <programlisting> 
3302   class StateMonad s m | m -> s where ... 
3303   instance Monad m => StateMonad s (State s m) where ... 
3304 </programlisting> 
3305 then we can derive an instance of <literal>StateMonad</literal> for <literal>Parser</literal>s by 
3306 <programlisting> 
3307   newtype Parser tok m a = Parser (State [tok] (Failure m) a)
3308                          deriving (Monad, StateMonad [tok])
3309 </programlisting>
3310
3311 The derived instance is obtained by completing the application of the
3312 class to the new type:
3313
3314 <programlisting> 
3315   instance StateMonad [tok] (State [tok] (Failure m)) =>
3316            StateMonad [tok] (Parser tok m)
3317 </programlisting>
3318 </para>
3319 <para>
3320
3321 As a result of this extension, all derived instances in newtype
3322  declarations are treated uniformly (and implemented just by reusing
3323 the dictionary for the representation type), <emphasis>except</emphasis>
3324 <literal>Show</literal> and <literal>Read</literal>, which really behave differently for
3325 the newtype and its representation.
3326 </para>
3327 </sect3>
3328
3329 <sect3> <title> A more precise specification </title>
3330 <para>
3331 Derived instance declarations are constructed as follows. Consider the
3332 declaration (after expansion of any type synonyms)
3333
3334 <programlisting> 
3335   newtype T v1...vn = T' (S t1...tk vk+1...vn) deriving (c1...cm) 
3336 </programlisting> 
3337
3338 where 
3339  <itemizedlist>
3340 <listitem><para>
3341   <literal>S</literal> is a type constructor, 
3342 </para></listitem>
3343 <listitem><para>
3344   The <literal>t1...tk</literal> are types,
3345 </para></listitem>
3346 <listitem><para>
3347   The <literal>vk+1...vn</literal> are type variables which do not occur in any of
3348   the <literal>ti</literal>, and
3349 </para></listitem>
3350 <listitem><para>
3351   The <literal>ci</literal> are partial applications of
3352   classes of the form <literal>C t1'...tj'</literal>, where the arity of <literal>C</literal>
3353   is exactly <literal>j+1</literal>.  That is, <literal>C</literal> lacks exactly one type argument.
3354 </para></listitem>
3355 <listitem><para>
3356   None of the <literal>ci</literal> is <literal>Read</literal>, <literal>Show</literal>, 
3357                 <literal>Typeable</literal>, or <literal>Data</literal>.  These classes
3358                 should not "look through" the type or its constructor.  You can still
3359                 derive these classes for a newtype, but it happens in the usual way, not 
3360                 via this new mechanism.  
3361 </para></listitem>
3362 </itemizedlist>
3363 Then, for each <literal>ci</literal>, the derived instance
3364 declaration is:
3365 <programlisting> 
3366   instance ci (S t1...tk vk+1...v) => ci (T v1...vp)
3367 </programlisting>
3368 where <literal>p</literal> is chosen so that <literal>T v1...vp</literal> is of the 
3369 right <emphasis>kind</emphasis> for the last parameter of class <literal>Ci</literal>.
3370 </para>
3371 <para>
3372
3373 As an example which does <emphasis>not</emphasis> work, consider 
3374 <programlisting> 
3375   newtype NonMonad m s = NonMonad (State s m s) deriving Monad 
3376 </programlisting> 
3377 Here we cannot derive the instance 
3378 <programlisting> 
3379   instance Monad (State s m) => Monad (NonMonad m) 
3380 </programlisting> 
3381
3382 because the type variable <literal>s</literal> occurs in <literal>State s m</literal>,
3383 and so cannot be "eta-converted" away. It is a good thing that this
3384 <literal>deriving</literal> clause is rejected, because <literal>NonMonad m</literal> is
3385 not, in fact, a monad --- for the same reason. Try defining
3386 <literal>>>=</literal> with the correct type: you won't be able to.
3387 </para>
3388 <para>
3389
3390 Notice also that the <emphasis>order</emphasis> of class parameters becomes
3391 important, since we can only derive instances for the last one. If the
3392 <literal>StateMonad</literal> class above were instead defined as
3393
3394 <programlisting> 
3395   class StateMonad m s | m -> s where ... 
3396 </programlisting>
3397
3398 then we would not have been able to derive an instance for the
3399 <literal>Parser</literal> type above. We hypothesise that multi-parameter
3400 classes usually have one "main" parameter for which deriving new
3401 instances is most interesting.
3402 </para>
3403 <para>Lastly, all of this applies only for classes other than
3404 <literal>Read</literal>, <literal>Show</literal>, <literal>Typeable</literal>, 
3405 and <literal>Data</literal>, for which the built-in derivation applies (section
3406 4.3.3. of the Haskell Report).
3407 (For the standard classes <literal>Eq</literal>, <literal>Ord</literal>,
3408 <literal>Ix</literal>, and <literal>Bounded</literal> it is immaterial whether
3409 the standard method is used or the one described here.)
3410 </para>
3411 </sect3>
3412
3413 </sect2>
3414
3415
3416 </sect1>
3417 <!-- ==================== End of type system extensions =================  -->
3418   
3419 <!-- ====================== Generalised algebraic data types =======================  -->
3420
3421 <sect1 id="gadt">
3422 <title>Generalised Algebraic Data Types</title>
3423
3424 <para>Generalised Algebraic Data Types (GADTs) generalise ordinary algebraic data types by allowing you
3425 to give the type signatures of constructors explicitly.  For example:
3426 <programlisting>
3427   data Term a where
3428       Lit    :: Int -> Term Int
3429       Succ   :: Term Int -> Term Int
3430       IsZero :: Term Int -> Term Bool   
3431       If     :: Term Bool -> Term a -> Term a -> Term a
3432       Pair   :: Term a -> Term b -> Term (a,b)
3433 </programlisting>
3434 Notice that the return type of the constructors is not always <literal>Term a</literal>, as is the
3435 case with ordinary vanilla data types.  Now we can write a well-typed <literal>eval</literal> function
3436 for these <literal>Terms</literal>:
3437 <programlisting>
3438   eval :: Term a -> a
3439   eval (Lit i)      = i
3440   eval (Succ t)     = 1 + eval t
3441   eval (IsZero i)   = eval i == 0
3442   eval (If b e1 e2) = if eval b then eval e1 else eval e2
3443   eval (Pair e1 e2) = (eval e2, eval e2)
3444 </programlisting>
3445 These and many other examples are given in papers by Hongwei Xi, and Tim Sheard.
3446 </para>
3447 <para> The extensions to GHC are these:
3448 <itemizedlist>
3449 <listitem><para>
3450   Data type declarations have a 'where' form, as exemplified above.  The type signature of
3451 each constructor is independent, and is implicitly universally quantified as usual. Unlike a normal
3452 Haskell data type declaration, the type variable(s) in the "<literal>data Term a where</literal>" header 
3453 have no scope.  Indeed, one can write a kind signature instead:
3454 <programlisting>
3455   data Term :: * -> * where ...
3456 </programlisting>
3457 or even a mixture of the two:
3458 <programlisting>
3459   data Foo a :: (* -> *) -> * where ...
3460 </programlisting>
3461 The type variables (if given) may be explicitly kinded, so we could also write the header for <literal>Foo</literal>
3462 like this:
3463 <programlisting>
3464   data Foo a (b :: * -> *) where ...
3465 </programlisting>
3466 </para></listitem>
3467
3468 <listitem><para>
3469 There are no restrictions on the type of the data constructor, except that the result
3470 type must begin with the type constructor being defined.  For example, in the <literal>Term</literal> data
3471 type above, the type of each constructor must end with <literal> ... -> Term ...</literal>.
3472 </para></listitem>
3473
3474 <listitem><para>
3475 You cannot use a <literal>deriving</literal> clause on a GADT-style data type declaration,
3476 nor can you use record syntax.  (It's not clear what these constructs would mean.  For example,
3477 the record selectors might ill-typed.)  However, you can use strictness annotations, in the obvious places
3478 in the constructor type:
3479 <programlisting>
3480   data Term a where
3481       Lit    :: !Int -> Term Int
3482       If     :: Term Bool -> !(Term a) -> !(Term a) -> Term a
3483       Pair   :: Term a -> Term b -> Term (a,b)
3484 </programlisting>
3485 </para></listitem>
3486
3487 <listitem><para>
3488 Pattern matching causes type refinement.  For example, in the right hand side of the equation
3489 <programlisting>
3490   eval :: Term a -> a
3491   eval (Lit i) =  ...
3492 </programlisting>
3493 the type <literal>a</literal> is refined to <literal>Int</literal>.  (That's the whole point!)
3494 A precise specification of the type rules is beyond what this user manual aspires to, but there is a paper
3495 about the ideas: "Wobbly types: practical type inference for generalised algebraic data types", on Simon PJ's home page.</para>
3496
3497 <para> The general principle is this: <emphasis>type refinement is only carried out based on user-supplied type annotations</emphasis>.
3498 So if no type signature is supplied for <literal>eval</literal>, no type refinement happens, and lots of obscure error messages will
3499 occur.  However, the refinement is quite general.  For example, if we had:
3500 <programlisting>
3501   eval :: Term a -> a -> a
3502   eval (Lit i) j =  i+j
3503 </programlisting>
3504 the pattern match causes the type <literal>a</literal> to be refined to <literal>Int</literal> (because of the type
3505 of the constructor <literal>Lit</literal>, and that refinement also applies to the type of <literal>j</literal>, and
3506 the result type of the <literal>case</literal> expression.  Hence the addition <literal>i+j</literal> is legal.
3507 </para>
3508 </listitem>
3509 </itemizedlist>
3510 </para>
3511
3512 <para>Notice that GADTs generalise existential types.  For example, these two declarations are equivalent:
3513 <programlisting>
3514   data T a = forall b. MkT b (b->a)
3515   data T' a where { MKT :: b -> (b->a) -> T' a }
3516 </programlisting>
3517 </para>
3518 </sect1>
3519
3520 <!-- ====================== End of Generalised algebraic data types =======================  -->
3521
3522 <!-- ====================== TEMPLATE HASKELL =======================  -->
3523
3524 <sect1 id="template-haskell">
3525 <title>Template Haskell</title>
3526
3527 <para>Template Haskell allows you to do compile-time meta-programming in Haskell.  There is a "home page" for
3528 Template Haskell at <ulink url="http://www.haskell.org/th/">
3529 http://www.haskell.org/th/</ulink>, while
3530 the background to
3531 the main technical innovations is discussed in "<ulink
3532 url="http://research.microsoft.com/~simonpj/papers/meta-haskell">
3533 Template Meta-programming for Haskell</ulink>" (Proc Haskell Workshop 2002).
3534 The details of the Template Haskell design are still in flux.  Make sure you
3535 consult the <ulink url="http://www.haskell.org/ghc/docs/latest/html/libraries/index.html">online library reference material</ulink> 
3536 (search for the type ExpQ).
3537 [Temporary: many changes to the original design are described in 
3538       <ulink url="http://research.microsoft.com/~simonpj/tmp/notes2.ps">"http://research.microsoft.com/~simonpj/tmp/notes2.ps"</ulink>.
3539 Not all of these changes are in GHC 6.2.]
3540 </para>
3541
3542 <para> The first example from that paper is set out below as a worked example to help get you started. 
3543 </para>
3544
3545 <para>
3546 The documentation here describes the realisation in GHC.  (It's rather sketchy just now;
3547 Tim Sheard is going to expand it.)
3548 </para>
3549
3550     <sect2>
3551       <title>Syntax</title>
3552
3553       <para> Template Haskell has the following new syntactic
3554       constructions.  You need to use the flag
3555       <option>-fth</option><indexterm><primary><option>-fth</option></primary>
3556       </indexterm>to switch these syntactic extensions on
3557       (<option>-fth</option> is currently implied by
3558       <option>-fglasgow-exts</option>, but you are encouraged to
3559       specify it explicitly).</para>
3560
3561         <itemizedlist>
3562               <listitem><para>
3563                   A splice is written <literal>$x</literal>, where <literal>x</literal> is an
3564                   identifier, or <literal>$(...)</literal>, where the "..." is an arbitrary expression.
3565                   There must be no space between the "$" and the identifier or parenthesis.  This use
3566                   of "$" overrides its meaning as an infix operator, just as "M.x" overrides the meaning
3567                   of "." as an infix operator.  If you want the infix operator, put spaces around it.
3568                   </para>
3569               <para> A splice can occur in place of 
3570                   <itemizedlist>
3571                     <listitem><para> an expression; the spliced expression must have type <literal>Expr</literal></para></listitem>
3572                     <listitem><para> a list of top-level declarations; ; the spliced expression must have type <literal>Q [Dec]</literal></para></listitem>
3573                     <listitem><para> a type; the spliced expression must have type <literal>Type</literal>.</para></listitem>
3574                     </itemizedlist>
3575            (Note that the syntax for a declaration splice uses "<literal>$</literal>" not "<literal>splice</literal>" as in
3576         the paper. Also the type of the enclosed expression must be  <literal>Q [Dec]</literal>, not  <literal>[Q Dec]</literal>
3577         as in the paper.)
3578                 </para></listitem>
3579
3580
3581               <listitem><para>
3582                   A expression quotation is written in Oxford brackets, thus:
3583                   <itemizedlist>
3584                     <listitem><para> <literal>[| ... |]</literal>, where the "..." is an expression; 
3585                              the quotation has type <literal>Expr</literal>.</para></listitem>
3586                     <listitem><para> <literal>[d| ... |]</literal>, where the "..." is a list of top-level declarations;
3587                              the quotation has type <literal>Q [Dec]</literal>.</para></listitem>
3588                     <listitem><para> <literal>[t| ... |]</literal>, where the "..." is a type; 
3589                              the quotation has type <literal>Type</literal>.</para></listitem>
3590                   </itemizedlist></para></listitem>
3591
3592               <listitem><para>
3593                   Reification is written thus:
3594                   <itemizedlist>
3595                     <listitem><para> <literal>reifyDecl T</literal>, where <literal>T</literal> is a type constructor; this expression
3596                       has type <literal>Dec</literal>. </para></listitem>
3597                     <listitem><para> <literal>reifyDecl C</literal>, where <literal>C</literal> is a class; has type <literal>Dec</literal>.</para></listitem>
3598                     <listitem><para> <literal>reifyType f</literal>, where <literal>f</literal> is an identifier; has type <literal>Typ</literal>.</para></listitem>
3599                     <listitem><para> Still to come: fixities </para></listitem>
3600                     
3601                   </itemizedlist></para>
3602                 </listitem>
3603
3604                   
3605         </itemizedlist>
3606 </sect2>
3607
3608 <sect2>  <title> Using Template Haskell </title>
3609 <para>
3610 <itemizedlist>
3611     <listitem><para>
3612     The data types and monadic constructor functions for Template Haskell are in the library
3613     <literal>Language.Haskell.THSyntax</literal>.
3614     </para></listitem>
3615
3616     <listitem><para>
3617     You can only run a function at compile time if it is imported from another module.  That is,
3618             you can't define a function in a module, and call it from within a splice in the same module.
3619             (It would make sense to do so, but it's hard to implement.)
3620    </para></listitem>
3621
3622     <listitem><para>
3623             The flag <literal>-ddump-splices</literal> shows the expansion of all top-level splices as they happen.
3624    </para></listitem>
3625     <listitem><para>
3626             If you are building GHC from source, you need at least a stage-2 bootstrap compiler to
3627               run Template Haskell.  A stage-1 compiler will reject the TH constructs.  Reason: TH
3628               compiles and runs a program, and then looks at the result.  So it's important that
3629               the program it compiles produces results whose representations are identical to
3630               those of the compiler itself.
3631    </para></listitem>
3632 </itemizedlist>
3633 </para>
3634 <para> Template Haskell works in any mode (<literal>--make</literal>, <literal>--interactive</literal>,
3635         or file-at-a-time).  There used to be a restriction to the former two, but that restriction 
3636         has been lifted.
3637 </para>
3638 </sect2>
3639  
3640 <sect2>  <title> A Template Haskell Worked Example </title>
3641 <para>To help you get over the confidence barrier, try out this skeletal worked example.
3642   First cut and paste the two modules below into "Main.hs" and "Printf.hs":</para>
3643
3644 <programlisting>
3645
3646 {- Main.hs -}
3647 module Main where
3648
3649 -- Import our template "pr"
3650 import Printf ( pr )
3651
3652 -- The splice operator $ takes the Haskell source code
3653 -- generated at compile time by "pr" and splices it into
3654 -- the argument of "putStrLn".
3655 main = putStrLn ( $(pr "Hello") )
3656
3657
3658 {- Printf.hs -}
3659 module Printf where
3660
3661 -- Skeletal printf from the paper.
3662 -- It needs to be in a separate module to the one where
3663 -- you intend to use it.
3664
3665 -- Import some Template Haskell syntax
3666 import Language.Haskell.TH
3667
3668 -- Describe a format string
3669 data Format = D | S | L String
3670
3671 -- Parse a format string.  This is left largely to you
3672 -- as we are here interested in building our first ever
3673 -- Template Haskell program and not in building printf.
3674 parse :: String -> [Format]
3675 parse s   = [ L s ]
3676
3677 -- Generate Haskell source code from a parsed representation
3678 -- of the format string.  This code will be spliced into
3679 -- the module which calls "pr", at compile time.
3680 gen :: [Format] -> ExpQ
3681 gen [D]   = [| \n -> show n |]
3682 gen [S]   = [| \s -> s |]
3683 gen [L s] = stringE s
3684
3685 -- Here we generate the Haskell code for the splice
3686 -- from an input format string.
3687 pr :: String -> ExpQ
3688 pr s      = gen (parse s)
3689 </programlisting>
3690
3691 <para>Now run the compiler (here we are a Cygwin prompt on Windows):
3692 </para>
3693 <programlisting>
3694 $ ghc --make -fth main.hs -o main.exe
3695 </programlisting>
3696
3697 <para>Run "main.exe" and here is your output:</para>
3698
3699 <programlisting>
3700 $ ./main
3701 Hello
3702 </programlisting>
3703
3704 </sect2>
3705  
3706 </sect1>
3707
3708 <!-- ===================== Arrow notation ===================  -->
3709
3710 <sect1 id="arrow-notation">
3711 <title>Arrow notation
3712 </title>
3713
3714 <para>Arrows are a generalization of monads introduced by John Hughes.
3715 For more details, see
3716 <itemizedlist>
3717
3718 <listitem>
3719 <para>
3720 &ldquo;Generalising Monads to Arrows&rdquo;,
3721 John Hughes, in <citetitle>Science of Computer Programming</citetitle> 37,
3722 pp67&ndash;111, May 2000.
3723 </para>
3724 </listitem>
3725
3726 <listitem>
3727 <para>
3728 &ldquo;<ulink url="http://www.soi.city.ac.uk/~ross/papers/notation.html">A New Notation for Arrows</ulink>&rdquo;,
3729 Ross Paterson, in <citetitle>ICFP</citetitle>, Sep 2001.
3730 </para>
3731 </listitem>
3732
3733 <listitem>
3734 <para>
3735 &ldquo;<ulink url="http://www.soi.city.ac.uk/~ross/papers/fop.html">Arrows and Computation</ulink>&rdquo;,
3736 Ross Paterson, in <citetitle>The Fun of Programming</citetitle>,
3737 Palgrave, 2003.
3738 </para>
3739 </listitem>
3740
3741 </itemizedlist>
3742 and the arrows web page at
3743 <ulink url="http://www.haskell.org/arrows/"><literal>http://www.haskell.org/arrows/</literal></ulink>.
3744 With the <option>-farrows</option> flag, GHC supports the arrow
3745 notation described in the second of these papers.
3746 What follows is a brief introduction to the notation;
3747 it won't make much sense unless you've read Hughes's paper.
3748 This notation is translated to ordinary Haskell,
3749 using combinators from the
3750 <ulink url="../libraries/base/Control.Arrow.html"><literal>Control.Arrow</literal></ulink>
3751 module.
3752 </para>
3753
3754 <para>The extension adds a new kind of expression for defining arrows:
3755 <screen>
3756 <replaceable>exp</replaceable><superscript>10</superscript> ::= ...
3757        |  proc <replaceable>apat</replaceable> -> <replaceable>cmd</replaceable>
3758 </screen>
3759 where <literal>proc</literal> is a new keyword.
3760 The variables of the pattern are bound in the body of the 
3761 <literal>proc</literal>-expression,
3762 which is a new sort of thing called a <firstterm>command</firstterm>.
3763 The syntax of commands is as follows:
3764 <screen>
3765 <replaceable>cmd</replaceable>   ::= <replaceable>exp</replaceable><superscript>10</superscript> -&lt;  <replaceable>exp</replaceable>
3766        |  <replaceable>exp</replaceable><superscript>10</superscript> -&lt;&lt; <replaceable>exp</replaceable>
3767        |  <replaceable>cmd</replaceable><superscript>0</superscript>
3768 </screen>
3769 with <replaceable>cmd</replaceable><superscript>0</superscript> up to
3770 <replaceable>cmd</replaceable><superscript>9</superscript> defined using
3771 infix operators as for expressions, and
3772 <screen>
3773 <replaceable>cmd</replaceable><superscript>10</superscript> ::= \ <replaceable>apat</replaceable> ... <replaceable>apat</replaceable> -> <replaceable>cmd</replaceable>
3774        |  let <replaceable>decls</replaceable> in <replaceable>cmd</replaceable>
3775        |  if <replaceable>exp</replaceable> then <replaceable>cmd</replaceable> else <replaceable>cmd</replaceable>
3776        |  case <replaceable>exp</replaceable> of { <replaceable>calts</replaceable> }
3777        |  do { <replaceable>cstmt</replaceable> ; ... <replaceable>cstmt</replaceable> ; <replaceable>cmd</replaceable> }
3778        |  <replaceable>fcmd</replaceable>
3779
3780 <replaceable>fcmd</replaceable>  ::= <replaceable>fcmd</replaceable> <replaceable>aexp</replaceable>
3781        |  ( <replaceable>cmd</replaceable> )
3782        |  (| <replaceable>aexp</replaceable> <replaceable>cmd</replaceable> ... <replaceable>cmd</replaceable> |)
3783
3784 <replaceable>cstmt</replaceable> ::= let <replaceable>decls</replaceable>
3785        |  <replaceable>pat</replaceable> &lt;- <replaceable>cmd</replaceable>
3786        |  rec { <replaceable>cstmt</replaceable> ; ... <replaceable>cstmt</replaceable> [;] }
3787        |  <replaceable>cmd</replaceable>
3788 </screen>
3789 where <replaceable>calts</replaceable> are like <replaceable>alts</replaceable>
3790 except that the bodies are commands instead of expressions.
3791 </para>
3792
3793 <para>
3794 Commands produce values, but (like monadic computations)
3795 may yield more than one value,
3796 or none, and may do other things as well.
3797 For the most part, familiarity with monadic notation is a good guide to
3798 using commands.
3799 However the values of expressions, even monadic ones,
3800 are determined by the values of the variables they contain;
3801 this is not necessarily the case for commands.
3802 </para>
3803
3804 <para>
3805 A simple example of the new notation is the expression
3806 <screen>
3807 proc x -> f -&lt; x+1
3808 </screen>
3809 We call this a <firstterm>procedure</firstterm> or
3810 <firstterm>arrow abstraction</firstterm>.
3811 As with a lambda expression, the variable <literal>x</literal>
3812 is a new variable bound within the <literal>proc</literal>-expression.
3813 It refers to the input to the arrow.
3814 In the above example, <literal>-&lt;</literal> is not an identifier but an
3815 new reserved symbol used for building commands from an expression of arrow
3816 type and an expression to be fed as input to that arrow.
3817 (The weird look will make more sense later.)
3818 It may be read as analogue of application for arrows.
3819 The above example is equivalent to the Haskell expression
3820 <screen>
3821 arr (\ x -> x+1) >>> f
3822 </screen>
3823 That would make no sense if the expression to the left of
3824 <literal>-&lt;</literal> involves the bound variable <literal>x</literal>.
3825 More generally, the expression to the left of <literal>-&lt;</literal>
3826 may not involve any <firstterm>local variable</firstterm>,
3827 i.e. a variable bound in the current arrow abstraction.
3828 For such a situation there is a variant <literal>-&lt;&lt;</literal>, as in
3829 <screen>
3830 proc x -> f x -&lt;&lt; x+1
3831 </screen>
3832 which is equivalent to
3833 <screen>
3834 arr (\ x -> (f x, x+1)) >>> app
3835 </screen>
3836 so in this case the arrow must belong to the <literal>ArrowApply</literal>
3837 class.
3838 Such an arrow is equivalent to a monad, so if you're using this form
3839 you may find a monadic formulation more convenient.
3840 </para>
3841
3842 <sect2>
3843 <title>do-notation for commands</title>
3844
3845 <para>
3846 Another form of command is a form of <literal>do</literal>-notation.
3847 For example, you can write
3848 <screen>
3849 proc x -> do
3850         y &lt;- f -&lt; x+1
3851         g -&lt; 2*y
3852         let z = x+y
3853         t &lt;- h -&lt; x*z
3854         returnA -&lt; t+z
3855 </screen>
3856 You can read this much like ordinary <literal>do</literal>-notation,
3857 but with commands in place of monadic expressions.
3858 The first line sends the value of <literal>x+1</literal> as an input to
3859 the arrow <literal>f</literal>, and matches its output against
3860 <literal>y</literal>.
3861 In the next line, the output is discarded.
3862 The arrow <function>returnA</function> is defined in the
3863 <ulink url="../libraries/base/Control.Arrow.html"><literal>Control.Arrow</literal></ulink>
3864 module as <literal>arr id</literal>.
3865 The above example is treated as an abbreviation for
3866 <screen>
3867 arr (\ x -> (x, x)) >>>
3868         first (arr (\ x -> x+1) >>> f) >>>
3869         arr (\ (y, x) -> (y, (x, y))) >>>
3870         first (arr (\ y -> 2*y) >>> g) >>>
3871         arr snd >>>
3872         arr (\ (x, y) -> let z = x+y in ((x, z), z)) >>>
3873         first (arr (\ (x, z) -> x*z) >>> h) >>>
3874         arr (\ (t, z) -> t+z) >>>
3875         returnA
3876 </screen>
3877 Note that variables not used later in the composition are projected out.
3878 After simplification using rewrite rules (see <xref linkend="rewrite-rules"/>)
3879 defined in the
3880 <ulink url="../libraries/base/Control.Arrow.html"><literal>Control.Arrow</literal></ulink>
3881 module, this reduces to
3882 <screen>
3883 arr (\ x -> (x+1, x)) >>>
3884         first f >>>
3885         arr (\ (y, x) -> (2*y, (x, y))) >>>
3886         first g >>>
3887         arr (\ (_, (x, y)) -> let z = x+y in (x*z, z)) >>>
3888         first h >>>
3889         arr (\ (t, z) -> t+z)
3890 </screen>
3891 which is what you might have written by hand.
3892 With arrow notation, GHC keeps track of all those tuples of variables for you.
3893 </para>
3894
3895 <para>
3896 Note that although the above translation suggests that
3897 <literal>let</literal>-bound variables like <literal>z</literal> must be
3898 monomorphic, the actual translation produces Core,
3899 so polymorphic variables are allowed.
3900 </para>
3901
3902 <para>
3903 It's also possible to have mutually recursive bindings,
3904 using the new <literal>rec</literal> keyword, as in the following example:
3905 <programlisting>
3906 counter :: ArrowCircuit a => a Bool Int
3907 counter = proc reset -> do
3908         rec     output &lt;- returnA -&lt; if reset then 0 else next
3909                 next &lt;- delay 0 -&lt; output+1
3910         returnA -&lt; output
3911 </programlisting>
3912 The translation of such forms uses the <function>loop</function> combinator,
3913 so the arrow concerned must belong to the <literal>ArrowLoop</literal> class.
3914 </para>
3915
3916 </sect2>
3917
3918 <sect2>
3919 <title>Conditional commands</title>
3920
3921 <para>
3922 In the previous example, we used a conditional expression to construct the
3923 input for an arrow.
3924 Sometimes we want to conditionally execute different commands, as in
3925 <screen>
3926 proc (x,y) ->
3927         if f x y
3928         then g -&lt; x+1
3929         else h -&lt; y+2
3930 </screen>
3931 which is translated to
3932 <screen>
3933 arr (\ (x,y) -> if f x y then Left x else Right y) >>>
3934         (arr (\x -> x+1) >>> f) ||| (arr (\y -> y+2) >>> g)
3935 </screen>
3936 Since the translation uses <function>|||</function>,
3937 the arrow concerned must belong to the <literal>ArrowChoice</literal> class.
3938 </para>
3939
3940 <para>
3941 There are also <literal>case</literal> commands, like
3942 <screen>
3943 case input of
3944     [] -> f -&lt; ()
3945     [x] -> g -&lt; x+1
3946     x1:x2:xs -> do
3947         y &lt;- h -&lt; (x1, x2)
3948         ys &lt;- k -&lt; xs
3949         returnA -&lt; y:ys
3950 </screen>
3951 The syntax is the same as for <literal>case</literal> expressions,
3952 except that the bodies of the alternatives are commands rather than expressions.
3953 The translation is similar to that of <literal>if</literal> commands.
3954 </para>
3955
3956 </sect2>
3957
3958 <sect2>
3959 <title>Defining your own control structures</title>
3960
3961 <para>
3962 As we're seen, arrow notation provides constructs,
3963 modelled on those for expressions,
3964 for sequencing, value recursion and conditionals.
3965 But suitable combinators,
3966 which you can define in ordinary Haskell,
3967 may also be used to build new commands out of existing ones.
3968 The basic idea is that a command defines an arrow from environments to values.
3969 These environments assign values to the free local variables of the command.
3970 Thus combinators that produce arrows from arrows
3971 may also be used to build commands from commands.
3972 For example, the <literal>ArrowChoice</literal> class includes a combinator
3973 <programlisting>
3974 ArrowChoice a => (&lt;+>) :: a e c -> a e c -> a e c
3975 </programlisting>
3976 so we can use it to build commands:
3977 <programlisting>
3978 expr' = proc x -> do
3979                 returnA -&lt; x
3980         &lt;+> do
3981                 symbol Plus -&lt; ()
3982                 y &lt;- term -&lt; ()
3983                 expr' -&lt; x + y
3984         &lt;+> do
3985                 symbol Minus -&lt; ()
3986                 y &lt;- term -&lt; ()
3987                 expr' -&lt; x - y
3988 </programlisting>
3989 (The <literal>do</literal> on the first line is needed to prevent the first
3990 <literal>&lt;+> ...</literal> from being interpreted as part of the
3991 expression on the previous line.)
3992 This is equivalent to
3993 <programlisting>
3994 expr' = (proc x -> returnA -&lt; x)
3995         &lt;+> (proc x -> do
3996                 symbol Plus -&lt; ()
3997                 y &lt;- term -&lt; ()
3998                 expr' -&lt; x + y)
3999         &lt;+> (proc x -> do
4000                 symbol Minus -&lt; ()
4001                 y &lt;- term -&lt; ()
4002                 expr' -&lt; x - y)
4003 </programlisting>
4004 It is essential that this operator be polymorphic in <literal>e</literal>
4005 (representing the environment input to the command
4006 and thence to its subcommands)
4007 and satisfy the corresponding naturality property
4008 <screen>
4009 arr k >>> (f &lt;+> g) = (arr k >>> f) &lt;+> (arr k >>> g)
4010 </screen>
4011 at least for strict <literal>k</literal>.
4012 (This should be automatic if you're not using <function>seq</function>.)
4013 This ensures that environments seen by the subcommands are environments
4014 of the whole command,
4015 and also allows the translation to safely trim these environments.
4016 The operator must also not use any variable defined within the current
4017 arrow abstraction.
4018 </para>
4019
4020 <para>
4021 We could define our own operator
4022 <programlisting>
4023 untilA :: ArrowChoice a => a e () -> a e Bool -> a e ()
4024 untilA body cond = proc x ->
4025         if cond x then returnA -&lt; ()
4026         else do
4027                 body -&lt; x
4028                 untilA body cond -&lt; x
4029 </programlisting>
4030 and use it in the same way.
4031 Of course this infix syntax only makes sense for binary operators;
4032 there is also a more general syntax involving special brackets:
4033 <screen>
4034 proc x -> do
4035         y &lt;- f -&lt; x+1
4036         (|untilA (increment -&lt; x+y) (within 0.5 -&lt; x)|)
4037 </screen>
4038 </para>
4039
4040 </sect2>
4041
4042 <sect2>
4043 <title>Primitive constructs</title>
4044
4045 <para>
4046 Some operators will need to pass additional inputs to their subcommands.
4047 For example, in an arrow type supporting exceptions,
4048 the operator that attaches an exception handler will wish to pass the
4049 exception that occurred to the handler.
4050 Such an operator might have a type
4051 <screen>
4052 handleA :: ... => a e c -> a (e,Ex) c -> a e c
4053 </screen>
4054 where <literal>Ex</literal> is the type of exceptions handled.
4055 You could then use this with arrow notation by writing a command
4056 <screen>
4057 body `handleA` \ ex -> handler
4058 </screen>
4059 so that if an exception is raised in the command <literal>body</literal>,
4060 the variable <literal>ex</literal> is bound to the value of the exception
4061 and the command <literal>handler</literal>,
4062 which typically refers to <literal>ex</literal>, is entered.
4063 Though the syntax here looks like a functional lambda,
4064 we are talking about commands, and something different is going on.
4065 The input to the arrow represented by a command consists of values for
4066 the free local variables in the command, plus a stack of anonymous values.
4067 In all the prior examples, this stack was empty.
4068 In the second argument to <function>handleA</function>,
4069 this stack consists of one value, the value of the exception.
4070 The command form of lambda merely gives this value a name.
4071 </para>
4072
4073 <para>
4074 More concretely,
4075 the values on the stack are paired to the right of the environment.
4076 So operators like <function>handleA</function> that pass
4077 extra inputs to their subcommands can be designed for use with the notation
4078 by pairing the values with the environment in this way.
4079 More precisely, the type of each argument of the operator (and its result)
4080 should have the form
4081 <screen>
4082 a (...(e,t1), ... tn) t
4083 </screen>
4084 where <replaceable>e</replaceable> is a polymorphic variable
4085 (representing the environment)
4086 and <replaceable>ti</replaceable> are the types of the values on the stack,
4087 with <replaceable>t1</replaceable> being the <quote>top</quote>.
4088 The polymorphic variable <replaceable>e</replaceable> must not occur in
4089 <replaceable>a</replaceable>, <replaceable>ti</replaceable> or
4090 <replaceable>t</replaceable>.
4091 However the arrows involved need not be the same.
4092 Here are some more examples of suitable operators:
4093 <screen>
4094 bracketA :: ... => a e b -> a (e,b) c -> a (e,c) d -> a e d
4095 runReader :: ... => a e c -> a' (e,State) c
4096 runState :: ... => a e c -> a' (e,State) (c,State)
4097 </screen>
4098 We can supply the extra input required by commands built with the last two
4099 by applying them to ordinary expressions, as in
4100 <screen>
4101 proc x -> do
4102         s &lt;- ...
4103         (|runReader (do { ... })|) s
4104 </screen>
4105 which adds <literal>s</literal> to the stack of inputs to the command
4106 built using <function>runReader</function>.
4107 </para>
4108
4109 <para>
4110 The command versions of lambda abstraction and application are analogous to
4111 the expression versions.
4112 In particular, the beta and eta rules describe equivalences of commands.
4113 These three features (operators, lambda abstraction and application)
4114 are the core of the notation; everything else can be built using them,
4115 though the results would be somewhat clumsy.
4116 For example, we could simulate <literal>do</literal>-notation by defining
4117 <programlisting>
4118 bind :: Arrow a => a e b -> a (e,b) c -> a e c
4119 u `bind` f = returnA &amp;&amp;&amp; u >>> f
4120
4121 bind_ :: Arrow a => a e b -> a e c -> a e c
4122 u `bind_` f = u `bind` (arr fst >>> f)
4123 </programlisting>
4124 We could simulate <literal>if</literal> by defining
4125 <programlisting>
4126 cond :: ArrowChoice a => a e b -> a e b -> a (e,Bool) b
4127 cond f g = arr (\ (e,b) -> if b then Left e else Right e) >>> f ||| g
4128 </programlisting>
4129 </para>
4130
4131 </sect2>
4132
4133 <sect2>
4134 <title>Differences with the paper</title>
4135
4136 <itemizedlist>
4137
4138 <listitem>
4139 <para>Instead of a single form of arrow application (arrow tail) with two
4140 translations, the implementation provides two forms
4141 <quote><literal>-&lt;</literal></quote> (first-order)
4142 and <quote><literal>-&lt;&lt;</literal></quote> (higher-order).
4143 </para>
4144 </listitem>
4145
4146 <listitem>
4147 <para>User-defined operators are flagged with banana brackets instead of
4148 a new <literal>form</literal> keyword.
4149 </para>
4150 </listitem>
4151
4152 </itemizedlist>
4153
4154 </sect2>
4155
4156 <sect2>
4157 <title>Portability</title>
4158
4159 <para>
4160 Although only GHC implements arrow notation directly,
4161 there is also a preprocessor
4162 (available from the 
4163 <ulink url="http://www.haskell.org/arrows/">arrows web page</ulink>)
4164 that translates arrow notation into Haskell 98
4165 for use with other Haskell systems.
4166 You would still want to check arrow programs with GHC;
4167 tracing type errors in the preprocessor output is not easy.
4168 Modules intended for both GHC and the preprocessor must observe some
4169 additional restrictions:
4170 <itemizedlist>
4171
4172 <listitem>
4173 <para>
4174 The module must import
4175 <ulink url="../libraries/base/Control.Arrow.html"><literal>Control.Arrow</literal></ulink>.
4176 </para>
4177 </listitem>
4178
4179 <listitem>
4180 <para>
4181 The preprocessor cannot cope with other Haskell extensions.
4182 These would have to go in separate modules.
4183 </para>
4184 </listitem>
4185
4186 <listitem>
4187 <para>
4188 Because the preprocessor targets Haskell (rather than Core),
4189 <literal>let</literal>-bound variables are monomorphic.
4190 </para>
4191 </listitem>
4192
4193 </itemizedlist>
4194 </para>
4195
4196 </sect2>
4197
4198 </sect1>
4199
4200 <!-- ==================== ASSERTIONS =================  -->
4201
4202 <sect1 id="sec-assertions">
4203 <title>Assertions
4204 <indexterm><primary>Assertions</primary></indexterm>
4205 </title>
4206
4207 <para>
4208 If you want to make use of assertions in your standard Haskell code, you
4209 could define a function like the following:
4210 </para>
4211
4212 <para>
4213
4214 <programlisting>
4215 assert :: Bool -> a -> a
4216 assert False x = error "assertion failed!"
4217 assert _     x = x
4218 </programlisting>
4219
4220 </para>
4221
4222 <para>
4223 which works, but gives you back a less than useful error message --
4224 an assertion failed, but which and where?
4225 </para>
4226
4227 <para>
4228 One way out is to define an extended <function>assert</function> function which also
4229 takes a descriptive string to include in the error message and
4230 perhaps combine this with the use of a pre-processor which inserts
4231 the source location where <function>assert</function> was used.
4232 </para>
4233
4234 <para>
4235 Ghc offers a helping hand here, doing all of this for you. For every
4236 use of <function>assert</function> in the user's source:
4237 </para>
4238
4239 <para>
4240
4241 <programlisting>
4242 kelvinToC :: Double -> Double
4243 kelvinToC k = assert (k &gt;= 0.0) (k+273.15)
4244 </programlisting>
4245
4246 </para>
4247
4248 <para>
4249 Ghc will rewrite this to also include the source location where the
4250 assertion was made,
4251 </para>
4252
4253 <para>
4254
4255 <programlisting>
4256 assert pred val ==> assertError "Main.hs|15" pred val
4257 </programlisting>
4258
4259 </para>
4260
4261 <para>
4262 The rewrite is only performed by the compiler when it spots
4263 applications of <function>Control.Exception.assert</function>, so you
4264 can still define and use your own versions of
4265 <function>assert</function>, should you so wish. If not, import
4266 <literal>Control.Exception</literal> to make use
4267 <function>assert</function> in your code.
4268 </para>
4269
4270 <para>
4271 To have the compiler ignore uses of assert, use the compiler option
4272 <option>-fignore-asserts</option>. <indexterm><primary>-fignore-asserts
4273 option</primary></indexterm> That is, expressions of the form
4274 <literal>assert pred e</literal> will be rewritten to
4275 <literal>e</literal>.
4276 </para>
4277
4278 <para>
4279 Assertion failures can be caught, see the documentation for the
4280 <literal>Control.Exception</literal> library for the details.
4281 </para>
4282
4283 </sect1>
4284
4285
4286 <!-- =============================== PRAGMAS ===========================  -->
4287
4288   <sect1 id="pragmas">
4289     <title>Pragmas</title>
4290
4291     <indexterm><primary>pragma</primary></indexterm>
4292
4293     <para>GHC supports several pragmas, or instructions to the
4294     compiler placed in the source code.  Pragmas don't normally affect
4295     the meaning of the program, but they might affect the efficiency
4296     of the generated code.</para>
4297
4298     <para>Pragmas all take the form
4299
4300 <literal>{-# <replaceable>word</replaceable> ... #-}</literal>  
4301
4302     where <replaceable>word</replaceable> indicates the type of
4303     pragma, and is followed optionally by information specific to that
4304     type of pragma.  Case is ignored in
4305     <replaceable>word</replaceable>.  The various values for
4306     <replaceable>word</replaceable> that GHC understands are described
4307     in the following sections; any pragma encountered with an
4308     unrecognised <replaceable>word</replaceable> is (silently)
4309     ignored.</para>
4310
4311     <sect2 id="deprecated-pragma">
4312       <title>DEPRECATED pragma</title>
4313       <indexterm><primary>DEPRECATED</primary>
4314       </indexterm>
4315
4316       <para>The DEPRECATED pragma lets you specify that a particular
4317       function, class, or type, is deprecated.  There are two
4318       forms.
4319
4320       <itemizedlist>
4321         <listitem>
4322           <para>You can deprecate an entire module thus:</para>
4323 <programlisting>
4324    module Wibble {-# DEPRECATED "Use Wobble instead" #-} where
4325      ...
4326 </programlisting>
4327           <para>When you compile any module that import
4328           <literal>Wibble</literal>, GHC will print the specified
4329           message.</para>
4330         </listitem>
4331
4332         <listitem>
4333           <para>You can deprecate a function, class, or type, with the
4334           following top-level declaration:</para>
4335 <programlisting>
4336    {-# DEPRECATED f, C, T "Don't use these" #-}
4337 </programlisting>
4338           <para>When you compile any module that imports and uses any
4339           of the specified entities, GHC will print the specified
4340           message.</para>
4341         </listitem>
4342       </itemizedlist>
4343       Any use of the deprecated item, or of anything from a deprecated
4344       module, will be flagged with an appropriate message.  However,
4345       deprecations are not reported for
4346       (a) uses of a deprecated function within its defining module, and
4347       (b) uses of a deprecated function in an export list.
4348       The latter reduces spurious complaints within a library
4349       in which one module gathers together and re-exports 
4350       the exports of several others.
4351       </para>
4352       <para>You can suppress the warnings with the flag
4353       <option>-fno-warn-deprecations</option>.</para>
4354     </sect2>
4355
4356     <sect2 id="include-pragma">
4357       <title>INCLUDE pragma</title>
4358
4359       <para>The <literal>INCLUDE</literal> pragma is for specifying the names
4360         of C header files that should be <literal>#include</literal>'d into
4361         the C source code generated by the compiler for the current module (if
4362         compiling via C).  For example:</para>
4363
4364 <programlisting>
4365 {-# INCLUDE "foo.h" #-}
4366 {-# INCLUDE &lt;stdio.h&gt; #-}</programlisting>
4367
4368       <para>The <literal>INCLUDE</literal> pragma(s) must appear at the top of
4369         your source file with any <literal>OPTIONS_GHC</literal>
4370         pragma(s).</para>
4371
4372       <para>An <literal>INCLUDE</literal> pragma is  the preferred alternative
4373         to the <option>-#include</option> option (<xref
4374           linkend="options-C-compiler" />), because the
4375         <literal>INCLUDE</literal> pragma is understood by other
4376         compilers.  Yet another alternative is to add the include file to each
4377         <literal>foreign import</literal> declaration in your code, but we
4378         don't recommend using this approach with GHC.</para>
4379     </sect2>
4380
4381     <sect2 id="inline-noinline-pragma">
4382       <title>INLINE and NOINLINE pragmas</title>
4383
4384       <para>These pragmas control the inlining of function
4385       definitions.</para>
4386
4387       <sect3 id="inline-pragma">
4388         <title>INLINE pragma</title>
4389         <indexterm><primary>INLINE</primary></indexterm>
4390
4391         <para>GHC (with <option>-O</option>, as always) tries to
4392         inline (or &ldquo;unfold&rdquo;) functions/values that are
4393         &ldquo;small enough,&rdquo; thus avoiding the call overhead
4394         and possibly exposing other more-wonderful optimisations.
4395         Normally, if GHC decides a function is &ldquo;too
4396         expensive&rdquo; to inline, it will not do so, nor will it
4397         export that unfolding for other modules to use.</para>
4398
4399         <para>The sledgehammer you can bring to bear is the
4400         <literal>INLINE</literal><indexterm><primary>INLINE
4401         pragma</primary></indexterm> pragma, used thusly:</para>
4402
4403 <programlisting>
4404 key_function :: Int -> String -> (Bool, Double)
4405
4406 #ifdef __GLASGOW_HASKELL__
4407 {-# INLINE key_function #-}
4408 #endif
4409 </programlisting>
4410
4411         <para>(You don't need to do the C pre-processor carry-on
4412         unless you're going to stick the code through HBC&mdash;it
4413         doesn't like <literal>INLINE</literal> pragmas.)</para>
4414
4415         <para>The major effect of an <literal>INLINE</literal> pragma
4416         is to declare a function's &ldquo;cost&rdquo; to be very low.
4417         The normal unfolding machinery will then be very keen to
4418         inline it.</para>
4419
4420         <para>Syntactically, an <literal>INLINE</literal> pragma for a
4421         function can be put anywhere its type signature could be
4422         put.</para>
4423
4424         <para><literal>INLINE</literal> pragmas are a particularly
4425         good idea for the
4426         <literal>then</literal>/<literal>return</literal> (or
4427         <literal>bind</literal>/<literal>unit</literal>) functions in
4428         a monad.  For example, in GHC's own
4429         <literal>UniqueSupply</literal> monad code, we have:</para>
4430
4431 <programlisting>
4432 #ifdef __GLASGOW_HASKELL__
4433 {-# INLINE thenUs #-}
4434 {-# INLINE returnUs #-}
4435 #endif
4436 </programlisting>
4437
4438         <para>See also the <literal>NOINLINE</literal> pragma (<xref
4439         linkend="noinline-pragma"/>).</para>
4440       </sect3>
4441
4442       <sect3 id="noinline-pragma">
4443         <title>NOINLINE pragma</title>
4444         
4445         <indexterm><primary>NOINLINE</primary></indexterm>
4446         <indexterm><primary>NOTINLINE</primary></indexterm>
4447
4448         <para>The <literal>NOINLINE</literal> pragma does exactly what
4449         you'd expect: it stops the named function from being inlined
4450         by the compiler.  You shouldn't ever need to do this, unless
4451         you're very cautious about code size.</para>
4452
4453         <para><literal>NOTINLINE</literal> is a synonym for
4454         <literal>NOINLINE</literal> (<literal>NOINLINE</literal> is
4455         specified by Haskell 98 as the standard way to disable
4456         inlining, so it should be used if you want your code to be
4457         portable).</para>
4458       </sect3>
4459
4460       <sect3 id="phase-control">
4461         <title>Phase control</title>
4462
4463         <para> Sometimes you want to control exactly when in GHC's
4464         pipeline the INLINE pragma is switched on.  Inlining happens
4465         only during runs of the <emphasis>simplifier</emphasis>.  Each
4466         run of the simplifier has a different <emphasis>phase
4467         number</emphasis>; the phase number decreases towards zero.
4468         If you use <option>-dverbose-core2core</option> you'll see the
4469         sequence of phase numbers for successive runs of the
4470         simplifier.  In an INLINE pragma you can optionally specify a
4471         phase number, thus:</para>
4472
4473         <itemizedlist>
4474           <listitem>
4475             <para>You can say "inline <literal>f</literal> in Phase 2
4476             and all subsequent phases":
4477 <programlisting>
4478   {-# INLINE [2] f #-}
4479 </programlisting>
4480             </para>
4481           </listitem>
4482
4483           <listitem>
4484             <para>You can say "inline <literal>g</literal> in all
4485             phases up to, but not including, Phase 3":
4486 <programlisting>
4487   {-# INLINE [~3] g #-}
4488 </programlisting>
4489             </para>
4490           </listitem>
4491
4492           <listitem>
4493             <para>If you omit the phase indicator, you mean "inline in
4494             all phases".</para>
4495           </listitem>
4496         </itemizedlist>
4497
4498         <para>You can use a phase number on a NOINLINE pragma too:</para>
4499
4500         <itemizedlist>
4501           <listitem>
4502             <para>You can say "do not inline <literal>f</literal>
4503             until Phase 2; in Phase 2 and subsequently behave as if
4504             there was no pragma at all":
4505 <programlisting>
4506   {-# NOINLINE [2] f #-}
4507 </programlisting>
4508             </para>
4509           </listitem>
4510
4511           <listitem>
4512             <para>You can say "do not inline <literal>g</literal> in
4513             Phase 3 or any subsequent phase; before that, behave as if
4514             there was no pragma":
4515 <programlisting>
4516   {-# NOINLINE [~3] g #-}
4517 </programlisting>
4518             </para>
4519           </listitem>
4520
4521           <listitem>
4522             <para>If you omit the phase indicator, you mean "never
4523             inline this function".</para>
4524           </listitem>
4525         </itemizedlist>
4526
4527         <para>The same phase-numbering control is available for RULES
4528         (<xref linkend="rewrite-rules"/>).</para>
4529       </sect3>
4530     </sect2>
4531
4532     <sect2 id="line-pragma">
4533       <title>LINE pragma</title>
4534
4535       <indexterm><primary>LINE</primary><secondary>pragma</secondary></indexterm>
4536       <indexterm><primary>pragma</primary><secondary>LINE</secondary></indexterm>
4537       <para>This pragma is similar to C's <literal>&num;line</literal>
4538       pragma, and is mainly for use in automatically generated Haskell
4539       code.  It lets you specify the line number and filename of the
4540       original code; for example</para>
4541
4542 <programlisting>
4543 {-# LINE 42 "Foo.vhs" #-}
4544 </programlisting>
4545
4546       <para>if you'd generated the current file from something called
4547       <filename>Foo.vhs</filename> and this line corresponds to line
4548       42 in the original.  GHC will adjust its error messages to refer
4549       to the line/file named in the <literal>LINE</literal>
4550       pragma.</para>
4551     </sect2>
4552
4553     <sect2 id="options-pragma">
4554       <title>OPTIONS_GHC pragma</title>
4555       <indexterm><primary>OPTIONS_GHC</primary>
4556       </indexterm>
4557       <indexterm><primary>pragma</primary><secondary>OPTIONS_GHC</secondary>
4558       </indexterm>
4559
4560       <para>The <literal>OPTIONS_GHC</literal> pragma is used to specify
4561       additional options that are given to the compiler when compiling
4562       this source file.  See <xref linkend="source-file-options"/> for
4563       details.</para>
4564
4565       <para>Previous versions of GHC accepted <literal>OPTIONS</literal> rather
4566         than <literal>OPTIONS_GHC</literal>, but that is now deprecated.</para>
4567     </sect2>
4568
4569     <sect2 id="rules">
4570       <title>RULES pragma</title>
4571
4572       <para>The RULES pragma lets you specify rewrite rules.  It is
4573       described in <xref linkend="rewrite-rules"/>.</para>
4574     </sect2>
4575
4576     <sect2 id="specialize-pragma">
4577       <title>SPECIALIZE pragma</title>
4578
4579       <indexterm><primary>SPECIALIZE pragma</primary></indexterm>
4580       <indexterm><primary>pragma, SPECIALIZE</primary></indexterm>
4581       <indexterm><primary>overloading, death to</primary></indexterm>
4582
4583       <para>(UK spelling also accepted.)  For key overloaded
4584       functions, you can create extra versions (NB: more code space)
4585       specialised to particular types.  Thus, if you have an
4586       overloaded function:</para>
4587
4588 <programlisting>
4589 hammeredLookup :: Ord key => [(key, value)] -> key -> value
4590 </programlisting>
4591
4592       <para>If it is heavily used on lists with
4593       <literal>Widget</literal> keys, you could specialise it as
4594       follows:</para>
4595
4596 <programlisting>
4597 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
4598 </programlisting>
4599
4600       <para>A <literal>SPECIALIZE</literal> pragma for a function can
4601       be put anywhere its type signature could be put.</para>
4602
4603       <para>A <literal>SPECIALIZE</literal> has the effect of generating
4604       (a) a specialised version of the function and (b) a rewrite rule
4605       (see <xref linkend="rewrite-rules"/>) that rewrites a call to the
4606       un-specialised function into a call to the specialised one.</para>
4607
4608       <para>In earlier versions of GHC, it was possible to provide your own
4609       specialised function for a given type:
4610
4611 <programlisting>
4612 {-# SPECIALIZE hammeredLookup :: [(Int, value)] -> Int -> value = intLookup #-}
4613 </programlisting>
4614
4615       This feature has been removed, as it is now subsumed by the
4616       <literal>RULES</literal> pragma (see <xref linkend="rule-spec"/>).</para>
4617
4618     </sect2>
4619
4620 <sect2 id="specialize-instance-pragma">
4621 <title>SPECIALIZE instance pragma
4622 </title>
4623
4624 <para>
4625 <indexterm><primary>SPECIALIZE pragma</primary></indexterm>
4626 <indexterm><primary>overloading, death to</primary></indexterm>
4627 Same idea, except for instance declarations.  For example:
4628
4629 <programlisting>
4630 instance (Eq a) => Eq (Foo a) where { 
4631    {-# SPECIALIZE instance Eq (Foo [(Int, Bar)]) #-}
4632    ... usual stuff ...
4633  }
4634 </programlisting>
4635 The pragma must occur inside the <literal>where</literal> part
4636 of the instance declaration.
4637 </para>
4638 <para>
4639 Compatible with HBC, by the way, except perhaps in the placement
4640 of the pragma.
4641 </para>
4642
4643 </sect2>
4644
4645     <sect2 id="unpack-pragma">
4646       <title>UNPACK pragma</title>
4647
4648       <indexterm><primary>UNPACK</primary></indexterm>
4649       
4650       <para>The <literal>UNPACK</literal> indicates to the compiler
4651       that it should unpack the contents of a constructor field into
4652       the constructor itself, removing a level of indirection.  For
4653       example:</para>
4654
4655 <programlisting>
4656 data T = T {-# UNPACK #-} !Float
4657            {-# UNPACK #-} !Float
4658 </programlisting>
4659
4660       <para>will create a constructor <literal>T</literal> containing
4661       two unboxed floats.  This may not always be an optimisation: if
4662       the <function>T</function> constructor is scrutinised and the
4663       floats passed to a non-strict function for example, they will
4664       have to be reboxed (this is done automatically by the
4665       compiler).</para>
4666
4667       <para>Unpacking constructor fields should only be used in
4668       conjunction with <option>-O</option>, in order to expose
4669       unfoldings to the compiler so the reboxing can be removed as
4670       often as possible.  For example:</para>
4671
4672 <programlisting>
4673 f :: T -&#62; Float
4674 f (T f1 f2) = f1 + f2
4675 </programlisting>
4676
4677       <para>The compiler will avoid reboxing <function>f1</function>
4678       and <function>f2</function> by inlining <function>+</function>
4679       on floats, but only when <option>-O</option> is on.</para>
4680
4681       <para>Any single-constructor data is eligible for unpacking; for
4682       example</para>
4683
4684 <programlisting>
4685 data T = T {-# UNPACK #-} !(Int,Int)
4686 </programlisting>
4687
4688       <para>will store the two <literal>Int</literal>s directly in the
4689       <function>T</function> constructor, by flattening the pair.
4690       Multi-level unpacking is also supported:</para>
4691
4692 <programlisting>
4693 data T = T {-# UNPACK #-} !S
4694 data S = S {-# UNPACK #-} !Int {-# UNPACK #-} !Int
4695 </programlisting>
4696
4697       <para>will store two unboxed <literal>Int&num;</literal>s
4698       directly in the <function>T</function> constructor.  The
4699       unpacker can see through newtypes, too.</para>
4700
4701       <para>If a field cannot be unpacked, you will not get a warning,
4702       so it might be an idea to check the generated code with
4703       <option>-ddump-simpl</option>.</para>
4704
4705       <para>See also the <option>-funbox-strict-fields</option> flag,
4706       which essentially has the effect of adding
4707       <literal>{-#&nbsp;UNPACK&nbsp;#-}</literal> to every strict
4708       constructor field.</para>
4709     </sect2>
4710
4711 </sect1>
4712
4713 <!--  ======================= REWRITE RULES ======================== -->
4714
4715 <sect1 id="rewrite-rules">
4716 <title>Rewrite rules
4717
4718 <indexterm><primary>RULES pragma</primary></indexterm>
4719 <indexterm><primary>pragma, RULES</primary></indexterm>
4720 <indexterm><primary>rewrite rules</primary></indexterm></title>
4721
4722 <para>
4723 The programmer can specify rewrite rules as part of the source program
4724 (in a pragma).  GHC applies these rewrite rules wherever it can, provided (a) 
4725 the <option>-O</option> flag (<xref linkend="options-optimise"/>) is on, 
4726 and (b) the <option>-frules-off</option> flag
4727 (<xref linkend="options-f"/>) is not specified.
4728 </para>
4729
4730 <para>
4731 Here is an example:
4732
4733 <programlisting>
4734   {-# RULES
4735         "map/map"       forall f g xs. map f (map g xs) = map (f.g) xs
4736   #-}
4737 </programlisting>
4738
4739 </para>
4740
4741 <sect2>
4742 <title>Syntax</title>
4743
4744 <para>
4745 From a syntactic point of view:
4746
4747 <itemizedlist>
4748 <listitem>
4749
4750 <para>
4751  There may be zero or more rules in a <literal>RULES</literal> pragma.
4752 </para>
4753 </listitem>
4754
4755 <listitem>
4756
4757 <para>
4758  Each rule has a name, enclosed in double quotes.  The name itself has
4759 no significance at all.  It is only used when reporting how many times the rule fired.
4760 </para>
4761 </listitem>
4762
4763 <listitem>
4764 <para>
4765 A rule may optionally have a phase-control number (see <xref linkend="phase-control"/>),
4766 immediately after the name of the rule.  Thus:
4767 <programlisting>
4768   {-# RULES
4769         "map/map" [2]  forall f g xs. map f (map g xs) = map (f.g) xs
4770   #-}
4771 </programlisting>
4772 The "[2]" means that the rule is active in Phase 2 and subsequent phases.  The inverse
4773 notation "[~2]" is also accepted, meaning that the rule is active up to, but not including,
4774 Phase 2.
4775 </para>
4776 </listitem>
4777
4778
4779 <listitem>
4780
4781 <para>
4782  Layout applies in a <literal>RULES</literal> pragma.  Currently no new indentation level
4783 is set, so you must lay out your rules starting in the same column as the
4784 enclosing definitions.
4785 </para>
4786 </listitem>
4787
4788 <listitem>
4789
4790 <para>
4791  Each variable mentioned in a rule must either be in scope (e.g. <function>map</function>),
4792 or bound by the <literal>forall</literal> (e.g. <function>f</function>, <function>g</function>, <function>xs</function>).  The variables bound by
4793 the <literal>forall</literal> are called the <emphasis>pattern</emphasis> variables.  They are separated
4794 by spaces, just like in a type <literal>forall</literal>.
4795 </para>
4796 </listitem>
4797 <listitem>
4798
4799 <para>
4800  A pattern variable may optionally have a type signature.
4801 If the type of the pattern variable is polymorphic, it <emphasis>must</emphasis> have a type signature.
4802 For example, here is the <literal>foldr/build</literal> rule:
4803
4804 <programlisting>
4805 "fold/build"  forall k z (g::forall b. (a->b->b) -> b -> b) .
4806               foldr k z (build g) = g k z
4807 </programlisting>
4808
4809 Since <function>g</function> has a polymorphic type, it must have a type signature.
4810
4811 </para>
4812 </listitem>
4813 <listitem>
4814
4815 <para>
4816 The left hand side of a rule must consist of a top-level variable applied
4817 to arbitrary expressions.  For example, this is <emphasis>not</emphasis> OK:
4818
4819 <programlisting>
4820 "wrong1"   forall e1 e2.  case True of { True -> e1; False -> e2 } = e1
4821 "wrong2"   forall f.      f True = True
4822 </programlisting>
4823
4824 In <literal>"wrong1"</literal>, the LHS is not an application; in <literal>"wrong2"</literal>, the LHS has a pattern variable
4825 in the head.
4826 </para>
4827 </listitem>
4828 <listitem>
4829
4830 <para>
4831  A rule does not need to be in the same module as (any of) the
4832 variables it mentions, though of course they need to be in scope.
4833 </para>
4834 </listitem>
4835 <listitem>
4836
4837 <para>
4838  Rules are automatically exported from a module, just as instance declarations are.
4839 </para>
4840 </listitem>
4841
4842 </itemizedlist>
4843
4844 </para>
4845
4846 </sect2>
4847
4848 <sect2>
4849 <title>Semantics</title>
4850
4851 <para>
4852 From a semantic point of view:
4853
4854 <itemizedlist>
4855 <listitem>
4856
4857 <para>
4858 Rules are only applied if you use the <option>-O</option> flag.
4859 </para>
4860 </listitem>
4861
4862 <listitem>
4863 <para>
4864  Rules are regarded as left-to-right rewrite rules.
4865 When GHC finds an expression that is a substitution instance of the LHS
4866 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
4867 By "a substitution instance" we mean that the LHS can be made equal to the
4868 expression by substituting for the pattern variables.
4869
4870 </para>
4871 </listitem>
4872 <listitem>
4873
4874 <para>
4875  The LHS and RHS of a rule are typechecked, and must have the
4876 same type.
4877
4878 </para>
4879 </listitem>
4880 <listitem>
4881
4882 <para>
4883  GHC makes absolutely no attempt to verify that the LHS and RHS
4884 of a rule have the same meaning.  That is undecidable in general, and
4885 infeasible in most interesting cases.  The responsibility is entirely the programmer's!
4886
4887 </para>
4888 </listitem>
4889 <listitem>
4890
4891 <para>
4892  GHC makes no attempt to make sure that the rules are confluent or
4893 terminating.  For example:
4894
4895 <programlisting>
4896   "loop"        forall x,y.  f x y = f y x
4897 </programlisting>
4898
4899 This rule will cause the compiler to go into an infinite loop.
4900
4901 </para>
4902 </listitem>
4903 <listitem>
4904
4905 <para>
4906  If more than one rule matches a call, GHC will choose one arbitrarily to apply.
4907
4908 </para>
4909 </listitem>
4910 <listitem>
4911 <para>
4912  GHC currently uses a very simple, syntactic, matching algorithm
4913 for matching a rule LHS with an expression.  It seeks a substitution
4914 which makes the LHS and expression syntactically equal modulo alpha
4915 conversion.  The pattern (rule), but not the expression, is eta-expanded if
4916 necessary.  (Eta-expanding the expression can lead to laziness bugs.)
4917 But not beta conversion (that's called higher-order matching).
4918 </para>
4919
4920 <para>
4921 Matching is carried out on GHC's intermediate language, which includes
4922 type abstractions and applications.  So a rule only matches if the
4923 types match too.  See <xref linkend="rule-spec"/> below.
4924 </para>
4925 </listitem>
4926 <listitem>
4927
4928 <para>
4929  GHC keeps trying to apply the rules as it optimises the program.
4930 For example, consider:
4931
4932 <programlisting>
4933   let s = map f
4934       t = map g
4935   in
4936   s (t xs)
4937 </programlisting>
4938
4939 The expression <literal>s (t xs)</literal> does not match the rule <literal>"map/map"</literal>, but GHC
4940 will substitute for <varname>s</varname> and <varname>t</varname>, giving an expression which does match.
4941 If <varname>s</varname> or <varname>t</varname> was (a) used more than once, and (b) large or a redex, then it would
4942 not be substituted, and the rule would not fire.
4943
4944 </para>
4945 </listitem>
4946 <listitem>
4947
4948 <para>
4949  In the earlier phases of compilation, GHC inlines <emphasis>nothing
4950 that appears on the LHS of a rule</emphasis>, because once you have substituted
4951 for something you can't match against it (given the simple minded
4952 matching).  So if you write the rule
4953
4954 <programlisting>
4955         "map/map"       forall f,g.  map f . map g = map (f.g)
4956 </programlisting>
4957
4958 this <emphasis>won't</emphasis> match the expression <literal>map f (map g xs)</literal>.
4959 It will only match something written with explicit use of ".".
4960 Well, not quite.  It <emphasis>will</emphasis> match the expression
4961
4962 <programlisting>
4963 wibble f g xs
4964 </programlisting>
4965
4966 where <function>wibble</function> is defined:
4967
4968 <programlisting>
4969 wibble f g = map f . map g
4970 </programlisting>
4971
4972 because <function>wibble</function> will be inlined (it's small).
4973
4974 Later on in compilation, GHC starts inlining even things on the
4975 LHS of rules, but still leaves the rules enabled.  This inlining
4976 policy is controlled by the per-simplification-pass flag <option>-finline-phase</option><emphasis>n</emphasis>.
4977
4978 </para>
4979 </listitem>
4980 <listitem>
4981
4982 <para>
4983  All rules are implicitly exported from the module, and are therefore
4984 in force in any module that imports the module that defined the rule, directly
4985 or indirectly.  (That is, if A imports B, which imports C, then C's rules are
4986 in force when compiling A.)  The situation is very similar to that for instance
4987 declarations.
4988 </para>
4989 </listitem>
4990
4991 </itemizedlist>
4992
4993 </para>
4994
4995 </sect2>
4996
4997 <sect2>
4998 <title>List fusion</title>
4999
5000 <para>
5001 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
5002 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
5003 intermediate list should be eliminated entirely.
5004 </para>
5005
5006 <para>
5007 The following are good producers:
5008
5009 <itemizedlist>
5010 <listitem>
5011
5012 <para>
5013  List comprehensions
5014 </para>
5015 </listitem>
5016 <listitem>
5017
5018 <para>
5019  Enumerations of <literal>Int</literal> and <literal>Char</literal> (e.g. <literal>['a'..'z']</literal>).
5020 </para>
5021 </listitem>
5022 <listitem>
5023
5024 <para>
5025  Explicit lists (e.g. <literal>[True, False]</literal>)
5026 </para>
5027 </listitem>
5028 <listitem>
5029
5030 <para>
5031  The cons constructor (e.g <literal>3:4:[]</literal>)
5032 </para>
5033 </listitem>
5034 <listitem>
5035
5036 <para>
5037  <function>++</function>
5038 </para>
5039 </listitem>
5040
5041 <listitem>
5042 <para>
5043  <function>map</function>
5044 </para>
5045 </listitem>
5046
5047 <listitem>
5048 <para>
5049  <function>filter</function>
5050 </para>
5051 </listitem>
5052 <listitem>
5053
5054 <para>
5055  <function>iterate</function>, <function>repeat</function>
5056 </para>
5057 </listitem>
5058 <listitem>
5059
5060 <para>
5061  <function>zip</function>, <function>zipWith</function>
5062 </para>
5063 </listitem>
5064
5065 </itemizedlist>
5066
5067 </para>
5068
5069 <para>
5070 The following are good consumers:
5071
5072 <itemizedlist>
5073 <listitem>
5074
5075 <para>
5076  List comprehensions
5077 </para>
5078 </listitem>
5079 <listitem>
5080
5081 <para>
5082  <function>array</function> (on its second argument)
5083 </para>
5084 </listitem>
5085 <listitem>
5086
5087 <para>
5088  <function>length</function>
5089 </para>
5090 </listitem>
5091 <listitem>
5092
5093 <para>
5094  <function>++</function> (on its first argument)
5095 </para>
5096 </listitem>
5097
5098 <listitem>
5099 <para>
5100  <function>foldr</function>
5101 </para>
5102 </listitem>
5103
5104 <listitem>
5105 <para>
5106  <function>map</function>
5107 </para>
5108 </listitem>
5109 <listitem>
5110
5111 <para>
5112  <function>filter</function>
5113 </para>
5114 </listitem>
5115 <listitem>
5116
5117 <para>
5118  <function>concat</function>
5119 </para>
5120 </listitem>
5121 <listitem>
5122
5123 <para>
5124  <function>unzip</function>, <function>unzip2</function>, <function>unzip3</function>, <function>unzip4</function>
5125 </para>
5126 </listitem>
5127 <listitem>
5128
5129 <para>
5130  <function>zip</function>, <function>zipWith</function> (but on one argument only; if both are good producers, <function>zip</function>
5131 will fuse with one but not the other)
5132 </para>
5133 </listitem>
5134 <listitem>
5135
5136 <para>
5137  <function>partition</function>
5138 </para>
5139 </listitem>
5140 <listitem>
5141
5142 <para>
5143  <function>head</function>
5144 </para>
5145 </listitem>
5146 <listitem>
5147
5148 <para>
5149  <function>and</function>, <function>or</function>, <function>any</function>, <function>all</function>
5150 </para>
5151 </listitem>
5152 <listitem>
5153
5154 <para>
5155  <function>sequence&lowbar;</function>
5156 </para>
5157 </listitem>
5158 <listitem>
5159
5160 <para>
5161  <function>msum</function>
5162 </para>
5163 </listitem>
5164 <listitem>
5165
5166 <para>
5167  <function>sortBy</function>
5168 </para>
5169 </listitem>
5170
5171 </itemizedlist>
5172
5173 </para>
5174
5175  <para>
5176 So, for example, the following should generate no intermediate lists:
5177
5178 <programlisting>
5179 array (1,10) [(i,i*i) | i &#60;- map (+ 1) [0..9]]
5180 </programlisting>
5181
5182 </para>
5183
5184 <para>
5185 This list could readily be extended; if there are Prelude functions that you use
5186 a lot which are not included, please tell us.
5187 </para>
5188
5189 <para>
5190 If you want to write your own good consumers or producers, look at the
5191 Prelude definitions of the above functions to see how to do so.
5192 </para>
5193
5194 </sect2>
5195
5196 <sect2 id="rule-spec">
5197 <title>Specialisation
5198 </title>
5199
5200 <para>
5201 Rewrite rules can be used to get the same effect as a feature
5202 present in earlier versions of GHC.
5203 For example, suppose that:
5204
5205 <programlisting>
5206 genericLookup :: Ord a => Table a b   -> a   -> b
5207 intLookup     ::          Table Int b -> Int -> b
5208 </programlisting>
5209
5210 where <function>intLookup</function> is an implementation of
5211 <function>genericLookup</function> that works very fast for
5212 keys of type <literal>Int</literal>.  You might wish
5213 to tell GHC to use <function>intLookup</function> instead of
5214 <function>genericLookup</function> whenever the latter was called with
5215 type <literal>Table Int b -&gt; Int -&gt; b</literal>.
5216 It used to be possible to write
5217
5218 <programlisting>
5219 {-# SPECIALIZE genericLookup :: Table Int b -> Int -> b = intLookup #-}
5220 </programlisting>
5221
5222 This feature is no longer in GHC, but rewrite rules let you do the same thing:
5223
5224 <programlisting>
5225 {-# RULES "genericLookup/Int" genericLookup = intLookup #-}
5226 </programlisting>
5227
5228 This slightly odd-looking rule instructs GHC to replace
5229 <function>genericLookup</function> by <function>intLookup</function>
5230 <emphasis>whenever the types match</emphasis>.
5231 What is more, this rule does not need to be in the same
5232 file as <function>genericLookup</function>, unlike the
5233 <literal>SPECIALIZE</literal> pragmas which currently do (so that they
5234 have an original definition available to specialise).
5235 </para>
5236
5237 <para>It is <emphasis>Your Responsibility</emphasis> to make sure that
5238 <function>intLookup</function> really behaves as a specialised version
5239 of <function>genericLookup</function>!!!</para>
5240
5241 <para>An example in which using <literal>RULES</literal> for
5242 specialisation will Win Big:
5243
5244 <programlisting>
5245 toDouble :: Real a => a -> Double
5246 toDouble = fromRational . toRational
5247
5248 {-# RULES "toDouble/Int" toDouble = i2d #-}
5249 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
5250 </programlisting>
5251
5252 The <function>i2d</function> function is virtually one machine
5253 instruction; the default conversion&mdash;via an intermediate
5254 <literal>Rational</literal>&mdash;is obscenely expensive by
5255 comparison.
5256 </para>
5257
5258 </sect2>
5259
5260 <sect2>
5261 <title>Controlling what's going on</title>
5262
5263 <para>
5264
5265 <itemizedlist>
5266 <listitem>
5267
5268 <para>
5269  Use <option>-ddump-rules</option> to see what transformation rules GHC is using.
5270 </para>
5271 </listitem>
5272 <listitem>
5273
5274 <para>
5275  Use <option>-ddump-simpl-stats</option> to see what rules are being fired.
5276 If you add <option>-dppr-debug</option> you get a more detailed listing.
5277 </para>
5278 </listitem>
5279 <listitem>
5280
5281 <para>
5282  The definition of (say) <function>build</function> in <filename>GHC/Base.lhs</filename> looks llike this:
5283
5284 <programlisting>
5285         build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
5286         {-# INLINE build #-}
5287         build g = g (:) []
5288 </programlisting>
5289
5290 Notice the <literal>INLINE</literal>!  That prevents <literal>(:)</literal> from being inlined when compiling
5291 <literal>PrelBase</literal>, so that an importing module will &ldquo;see&rdquo; the <literal>(:)</literal>, and can
5292 match it on the LHS of a rule.  <literal>INLINE</literal> prevents any inlining happening
5293 in the RHS of the <literal>INLINE</literal> thing.  I regret the delicacy of this.
5294
5295 </para>
5296 </listitem>
5297 <listitem>
5298
5299 <para>
5300  In <filename>libraries/base/GHC/Base.lhs</filename> look at the rules for <function>map</function> to
5301 see how to write rules that will do fusion and yet give an efficient
5302 program even if fusion doesn't happen.  More rules in <filename>GHC/List.lhs</filename>.
5303 </para>
5304 </listitem>
5305
5306 </itemizedlist>
5307
5308 </para>
5309
5310 </sect2>
5311
5312 <sect2 id="core-pragma">
5313   <title>CORE pragma</title>
5314
5315   <indexterm><primary>CORE pragma</primary></indexterm>
5316   <indexterm><primary>pragma, CORE</primary></indexterm>
5317   <indexterm><primary>core, annotation</primary></indexterm>
5318
5319 <para>
5320   The external core format supports <quote>Note</quote> annotations;
5321   the <literal>CORE</literal> pragma gives a way to specify what these
5322   should be in your Haskell source code.  Syntactically, core
5323   annotations are attached to expressions and take a Haskell string
5324   literal as an argument.  The following function definition shows an
5325   example:
5326
5327 <programlisting>
5328 f x = ({-# CORE "foo" #-} show) ({-# CORE "bar" #-} x)
5329 </programlisting>
5330
5331   Semantically, this is equivalent to:
5332
5333 <programlisting>
5334 g x = show x
5335 </programlisting>
5336 </para>
5337
5338 <para>
5339   However, when external for is generated (via
5340   <option>-fext-core</option>), there will be Notes attached to the
5341   expressions <function>show</function> and <varname>x</varname>.
5342   The core function declaration for <function>f</function> is:
5343 </para>
5344
5345 <programlisting>
5346   f :: %forall a . GHCziShow.ZCTShow a ->
5347                    a -> GHCziBase.ZMZN GHCziBase.Char =
5348     \ @ a (zddShow::GHCziShow.ZCTShow a) (eta::a) ->
5349         (%note "foo"
5350          %case zddShow %of (tpl::GHCziShow.ZCTShow a)
5351            {GHCziShow.ZCDShow
5352             (tpl1::GHCziBase.Int ->
5353                    a ->
5354                    GHCziBase.ZMZN GHCziBase.Char -> GHCziBase.ZMZN GHCziBase.Cha
5355 r)
5356             (tpl2::a -> GHCziBase.ZMZN GHCziBase.Char)
5357             (tpl3::GHCziBase.ZMZN a ->
5358                    GHCziBase.ZMZN GHCziBase.Char -> GHCziBase.ZMZN GHCziBase.Cha
5359 r) ->
5360               tpl2})
5361         (%note "foo"
5362          eta);
5363 </programlisting>
5364
5365 <para>
5366   Here, we can see that the function <function>show</function> (which
5367   has been expanded out to a case expression over the Show dictionary)
5368   has a <literal>%note</literal> attached to it, as does the
5369   expression <varname>eta</varname> (which used to be called
5370   <varname>x</varname>).
5371 </para>
5372
5373 </sect2>
5374
5375 </sect1>
5376
5377 <sect1 id="generic-classes">
5378 <title>Generic classes</title>
5379
5380     <para>(Note: support for generic classes is currently broken in
5381     GHC 5.02).</para>
5382
5383 <para>
5384 The ideas behind this extension are described in detail in "Derivable type classes",
5385 Ralf Hinze and Simon Peyton Jones, Haskell Workshop, Montreal Sept 2000, pp94-105.
5386 An example will give the idea:
5387 </para>
5388
5389 <programlisting>
5390   import Generics
5391
5392   class Bin a where
5393     toBin   :: a -> [Int]
5394     fromBin :: [Int] -> (a, [Int])
5395   
5396     toBin {| Unit |}    Unit      = []
5397     toBin {| a :+: b |} (Inl x)   = 0 : toBin x
5398     toBin {| a :+: b |} (Inr y)   = 1 : toBin y
5399     toBin {| a :*: b |} (x :*: y) = toBin x ++ toBin y
5400   
5401     fromBin {| Unit |}    bs      = (Unit, bs)
5402     fromBin {| a :+: b |} (0:bs)  = (Inl x, bs')    where (x,bs') = fromBin bs
5403     fromBin {| a :+: b |} (1:bs)  = (Inr y, bs')    where (y,bs') = fromBin bs
5404     fromBin {| a :*: b |} bs      = (x :*: y, bs'') where (x,bs' ) = fromBin bs
5405                                                           (y,bs'') = fromBin bs'
5406 </programlisting>
5407 <para>
5408 This class declaration explains how <literal>toBin</literal> and <literal>fromBin</literal>
5409 work for arbitrary data types.  They do so by giving cases for unit, product, and sum,
5410 which are defined thus in the library module <literal>Generics</literal>:
5411 </para>
5412 <programlisting>
5413   data Unit    = Unit
5414   data a :+: b = Inl a | Inr b
5415   data a :*: b = a :*: b
5416 </programlisting>
5417 <para>
5418 Now you can make a data type into an instance of Bin like this:
5419 <programlisting>
5420   instance (Bin a, Bin b) => Bin (a,b)
5421   instance Bin a => Bin [a]
5422 </programlisting>
5423 That is, just leave off the "where" clause.  Of course, you can put in the
5424 where clause and over-ride whichever methods you please.
5425 </para>
5426
5427     <sect2>
5428       <title> Using generics </title>
5429       <para>To use generics you need to</para>
5430       <itemizedlist>
5431         <listitem>
5432           <para>Use the flags <option>-fglasgow-exts</option> (to enable the extra syntax), 
5433                 <option>-fgenerics</option> (to generate extra per-data-type code),
5434                 and <option>-package lang</option> (to make the <literal>Generics</literal> library
5435                 available.  </para>
5436         </listitem>
5437         <listitem>
5438           <para>Import the module <literal>Generics</literal> from the
5439           <literal>lang</literal> package.  This import brings into
5440           scope the data types <literal>Unit</literal>,
5441           <literal>:*:</literal>, and <literal>:+:</literal>.  (You
5442           don't need this import if you don't mention these types
5443           explicitly; for example, if you are simply giving instance
5444           declarations.)</para>
5445         </listitem>
5446       </itemizedlist>
5447     </sect2>
5448
5449 <sect2> <title> Changes wrt the paper </title>
5450 <para>
5451 Note that the type constructors <literal>:+:</literal> and <literal>:*:</literal> 
5452 can be written infix (indeed, you can now use
5453 any operator starting in a colon as an infix type constructor).  Also note that
5454 the type constructors are not exactly as in the paper (Unit instead of 1, etc).
5455 Finally, note that the syntax of the type patterns in the class declaration
5456 uses "<literal>{|</literal>" and "<literal>|}</literal>" brackets; curly braces
5457 alone would ambiguous when they appear on right hand sides (an extension we 
5458 anticipate wanting).
5459 </para>
5460 </sect2>
5461
5462 <sect2> <title>Terminology and restrictions</title>
5463 <para>
5464 Terminology.  A "generic default method" in a class declaration
5465 is one that is defined using type patterns as above.
5466 A "polymorphic default method" is a default method defined as in Haskell 98.
5467 A "generic class declaration" is a class declaration with at least one
5468 generic default method.
5469 </para>
5470
5471 <para>
5472 Restrictions:
5473 <itemizedlist>
5474 <listitem>
5475 <para>
5476 Alas, we do not yet implement the stuff about constructor names and 
5477 field labels.
5478 </para>
5479 </listitem>
5480
5481 <listitem>
5482 <para>
5483 A generic class can have only one parameter; you can't have a generic
5484 multi-parameter class.
5485 </para>
5486 </listitem>
5487
5488 <listitem>
5489 <para>
5490 A default method must be defined entirely using type patterns, or entirely
5491 without.  So this is illegal:
5492 <programlisting>
5493   class Foo a where
5494     op :: a -> (a, Bool)
5495     op {| Unit |} Unit = (Unit, True)
5496     op x               = (x,    False)
5497 </programlisting>
5498 However it is perfectly OK for some methods of a generic class to have 
5499 generic default methods and others to have polymorphic default methods.
5500 </para>
5501 </listitem>
5502
5503 <listitem>
5504 <para>
5505 The type variable(s) in the type pattern for a generic method declaration
5506 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:
5507 <programlisting>
5508   class Foo a where
5509     op :: a -> Bool
5510     op {| p :*: q |} (x :*: y) = op (x :: p)
5511     ...
5512 </programlisting>
5513 </para>
5514 </listitem>
5515
5516 <listitem>
5517 <para>
5518 The type patterns in a generic default method must take one of the forms:
5519 <programlisting>
5520        a :+: b
5521        a :*: b
5522        Unit
5523 </programlisting>
5524 where "a" and "b" are type variables.  Furthermore, all the type patterns for
5525 a single type constructor (<literal>:*:</literal>, say) must be identical; they
5526 must use the same type variables.  So this is illegal:
5527 <programlisting>
5528   class Foo a where
5529     op :: a -> Bool
5530     op {| a :+: b |} (Inl x) = True
5531     op {| p :+: q |} (Inr y) = False
5532 </programlisting>
5533 The type patterns must be identical, even in equations for different methods of the class.
5534 So this too is illegal:
5535 <programlisting>
5536   class Foo a where
5537     op1 :: a -> Bool
5538     op1 {| a :*: b |} (x :*: y) = True
5539
5540     op2 :: a -> Bool
5541     op2 {| p :*: q |} (x :*: y) = False
5542 </programlisting>
5543 (The reason for this restriction is that we gather all the equations for a particular type consructor
5544 into a single generic instance declaration.)
5545 </para>
5546 </listitem>
5547
5548 <listitem>
5549 <para>
5550 A generic method declaration must give a case for each of the three type constructors.
5551 </para>
5552 </listitem>
5553
5554 <listitem>
5555 <para>
5556 The type for a generic method can be built only from:
5557   <itemizedlist>
5558   <listitem> <para> Function arrows </para> </listitem>
5559   <listitem> <para> Type variables </para> </listitem>
5560   <listitem> <para> Tuples </para> </listitem>
5561   <listitem> <para> Arbitrary types not involving type variables </para> </listitem>
5562   </itemizedlist>
5563 Here are some example type signatures for generic methods:
5564 <programlisting>
5565     op1 :: a -> Bool
5566     op2 :: Bool -> (a,Bool)
5567     op3 :: [Int] -> a -> a
5568     op4 :: [a] -> Bool
5569 </programlisting>
5570 Here, op1, op2, op3 are OK, but op4 is rejected, because it has a type variable
5571 inside a list.  
5572 </para>
5573 <para>
5574 This restriction is an implementation restriction: we just havn't got around to
5575 implementing the necessary bidirectional maps over arbitrary type constructors.
5576 It would be relatively easy to add specific type constructors, such as Maybe and list,
5577 to the ones that are allowed.</para>
5578 </listitem>
5579
5580 <listitem>
5581 <para>
5582 In an instance declaration for a generic class, the idea is that the compiler
5583 will fill in the methods for you, based on the generic templates.  However it can only
5584 do so if
5585   <itemizedlist>
5586   <listitem>
5587   <para>
5588   The instance type is simple (a type constructor applied to type variables, as in Haskell 98).
5589   </para>
5590   </listitem>
5591   <listitem>
5592   <para>
5593   No constructor of the instance type has unboxed fields.
5594   </para>
5595   </listitem>
5596   </itemizedlist>
5597 (Of course, these things can only arise if you are already using GHC extensions.)
5598 However, you can still give an instance declarations for types which break these rules,
5599 provided you give explicit code to override any generic default methods.
5600 </para>
5601 </listitem>
5602
5603 </itemizedlist>
5604 </para>
5605
5606 <para>
5607 The option <option>-ddump-deriv</option> dumps incomprehensible stuff giving details of 
5608 what the compiler does with generic declarations.
5609 </para>
5610
5611 </sect2>
5612
5613 <sect2> <title> Another example </title>
5614 <para>
5615 Just to finish with, here's another example I rather like:
5616 <programlisting>
5617   class Tag a where
5618     nCons :: a -> Int
5619     nCons {| Unit |}    _ = 1
5620     nCons {| a :*: b |} _ = 1
5621     nCons {| a :+: b |} _ = nCons (bot::a) + nCons (bot::b)
5622   
5623     tag :: a -> Int
5624     tag {| Unit |}    _       = 1
5625     tag {| a :*: b |} _       = 1   
5626     tag {| a :+: b |} (Inl x) = tag x
5627     tag {| a :+: b |} (Inr y) = nCons (bot::a) + tag y
5628 </programlisting>
5629 </para>
5630 </sect2>
5631 </sect1>
5632
5633
5634
5635 <!-- Emacs stuff:
5636      ;;; Local Variables: ***
5637      ;;; mode: xml ***
5638      ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") ***
5639      ;;; End: ***
5640  -->
5641