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