Tidy up documtation of monomorphsim restriction etc
[ghc.git] / docs / users_guide / glasgow_exts.xml
1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <para>
3 <indexterm><primary>language, GHC</primary></indexterm>
4 <indexterm><primary>extensions, GHC</primary></indexterm>
5 As with all known Haskell systems, GHC implements some extensions to
6 the language. They can all be enabled or disabled by commandline flags
7 or language pragmas. By default GHC understands the most recent Haskell
8 version it supports, plus a handful of extensions.
9 </para>
10
11 <para>
12 Some of the Glasgow extensions serve to give you access to the
13 underlying facilities with which we implement Haskell. Thus, you can
14 get at the Raw Iron, if you are willing to write some non-portable
15 code at a more primitive level. You need not be &ldquo;stuck&rdquo;
16 on performance because of the implementation costs of Haskell's
17 &ldquo;high-level&rdquo; features&mdash;you can always code
18 &ldquo;under&rdquo; them. In an extreme case, you can write all your
19 time-critical code in C, and then just glue it together with Haskell!
20 </para>
21
22 <para>
23 Before you get too carried away working at the lowest level (e.g.,
24 sloshing <literal>MutableByteArray&num;</literal>s around your
25 program), you may wish to check if there are libraries that provide a
26 &ldquo;Haskellised veneer&rdquo; over the features you want. The
27 separate <ulink url="../libraries/index.html">libraries
28 documentation</ulink> describes all the libraries that come with GHC.
29 </para>
30
31 <!-- LANGUAGE OPTIONS -->
32 <sect1 id="options-language">
33 <title>Language options</title>
34
35 <indexterm><primary>language</primary><secondary>option</secondary>
36 </indexterm>
37 <indexterm><primary>options</primary><secondary>language</secondary>
38 </indexterm>
39 <indexterm><primary>extensions</primary><secondary>options controlling</secondary>
40 </indexterm>
41
42 <para>The language option flags control what variation of the language are
43 permitted.</para>
44
45 <para>Language options can be controlled in two ways:
46 <itemizedlist>
47 <listitem><para>Every language option can switched on by a command-line flag "<option>-X...</option>"
48 (e.g. <option>-XTemplateHaskell</option>), and switched off by the flag "<option>-XNo...</option>";
49 (e.g. <option>-XNoTemplateHaskell</option>).</para></listitem>
50 <listitem><para>
51 Language options recognised by Cabal can also be enabled using the <literal>LANGUAGE</literal> pragma,
52 thus <literal>{-# LANGUAGE TemplateHaskell #-}</literal> (see <xref linkend="language-pragma"/>). </para>
53 </listitem>
54 </itemizedlist></para>
55
56 <para>The flag <option>-fglasgow-exts</option>
57 <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
58 is equivalent to enabling the following extensions:
59 &what_glasgow_exts_does;
60 Enabling these options is the <emphasis>only</emphasis>
61 effect of <option>-fglasgow-exts</option>.
62 We are trying to move away from this portmanteau flag,
63 and towards enabling features individually.</para>
64
65 </sect1>
66
67 <!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS -->
68 <sect1 id="primitives">
69 <title>Unboxed types and primitive operations</title>
70
71 <para>GHC is built on a raft of primitive data types and operations;
72 "primitive" in the sense that they cannot be defined in Haskell itself.
73 While you really can use this stuff to write fast code,
74 we generally find it a lot less painful, and more satisfying in the
75 long run, to use higher-level language features and libraries. With
76 any luck, the code you write will be optimised to the efficient
77 unboxed version in any case. And if it isn't, we'd like to know
78 about it.</para>
79
80 <para>All these primitive data types and operations are exported by the
81 library <literal>GHC.Prim</literal>, for which there is
82 <ulink url="&libraryGhcPrimLocation;/GHC-Prim.html">detailed online documentation</ulink>.
83 (This documentation is generated from the file <filename>compiler/prelude/primops.txt.pp</filename>.)
84 </para>
85
86 <para>
87 If you want to mention any of the primitive data types or operations in your
88 program, you must first import <literal>GHC.Prim</literal> to bring them
89 into scope. Many of them have names ending in "&num;", and to mention such
90 names you need the <option>-XMagicHash</option> extension (<xref linkend="magic-hash"/>).
91 </para>
92
93 <para>The primops make extensive use of <link linkend="glasgow-unboxed">unboxed types</link>
94 and <link linkend="unboxed-tuples">unboxed tuples</link>, which
95 we briefly summarise here. </para>
96
97 <sect2 id="glasgow-unboxed">
98 <title>Unboxed types</title>
99
100 <para>
101 <indexterm><primary>Unboxed types (Glasgow extension)</primary></indexterm>
102 </para>
103
104 <para>Most types in GHC are <firstterm>boxed</firstterm>, which means
105 that values of that type are represented by a pointer to a heap
106 object. The representation of a Haskell <literal>Int</literal>, for
107 example, is a two-word heap object. An <firstterm>unboxed</firstterm>
108 type, however, is represented by the value itself, no pointers or heap
109 allocation are involved.
110 </para>
111
112 <para>
113 Unboxed types correspond to the &ldquo;raw machine&rdquo; types you
114 would use in C: <literal>Int&num;</literal> (long int),
115 <literal>Double&num;</literal> (double), <literal>Addr&num;</literal>
116 (void *), etc. The <emphasis>primitive operations</emphasis>
117 (PrimOps) on these types are what you might expect; e.g.,
118 <literal>(+&num;)</literal> is addition on
119 <literal>Int&num;</literal>s, and is the machine-addition that we all
120 know and love&mdash;usually one instruction.
121 </para>
122
123 <para>
124 Primitive (unboxed) types cannot be defined in Haskell, and are
125 therefore built into the language and compiler. Primitive types are
126 always unlifted; that is, a value of a primitive type cannot be
127 bottom. We use the convention (but it is only a convention)
128 that primitive types, values, and
129 operations have a <literal>&num;</literal> suffix (see <xref linkend="magic-hash"/>).
130 For some primitive types we have special syntax for literals, also
131 described in the <link linkend="magic-hash">same section</link>.
132 </para>
133
134 <para>
135 Primitive values are often represented by a simple bit-pattern, such
136 as <literal>Int&num;</literal>, <literal>Float&num;</literal>,
137 <literal>Double&num;</literal>. But this is not necessarily the case:
138 a primitive value might be represented by a pointer to a
139 heap-allocated object. Examples include
140 <literal>Array&num;</literal>, the type of primitive arrays. A
141 primitive array is heap-allocated because it is too big a value to fit
142 in a register, and would be too expensive to copy around; in a sense,
143 it is accidental that it is represented by a pointer. If a pointer
144 represents a primitive value, then it really does point to that value:
145 no unevaluated thunks, no indirections&hellip;nothing can be at the
146 other end of the pointer than the primitive value.
147 A numerically-intensive program using unboxed types can
148 go a <emphasis>lot</emphasis> faster than its &ldquo;standard&rdquo;
149 counterpart&mdash;we saw a threefold speedup on one example.
150 </para>
151
152 <para>
153 There are some restrictions on the use of primitive types:
154 <itemizedlist>
155 <listitem><para>The main restriction
156 is that you can't pass a primitive value to a polymorphic
157 function or store one in a polymorphic data type. This rules out
158 things like <literal>[Int&num;]</literal> (i.e. lists of primitive
159 integers). The reason for this restriction is that polymorphic
160 arguments and constructor fields are assumed to be pointers: if an
161 unboxed integer is stored in one of these, the garbage collector would
162 attempt to follow it, leading to unpredictable space leaks. Or a
163 <function>seq</function> operation on the polymorphic component may
164 attempt to dereference the pointer, with disastrous results. Even
165 worse, the unboxed value might be larger than a pointer
166 (<literal>Double&num;</literal> for instance).
167 </para>
168 </listitem>
169 <listitem><para> You cannot define a newtype whose representation type
170 (the argument type of the data constructor) is an unboxed type. Thus,
171 this is illegal:
172 <programlisting>
173 newtype A = MkA Int#
174 </programlisting>
175 </para></listitem>
176 <listitem><para> You cannot bind a variable with an unboxed type
177 in a <emphasis>top-level</emphasis> binding.
178 </para></listitem>
179 <listitem><para> You cannot bind a variable with an unboxed type
180 in a <emphasis>recursive</emphasis> binding.
181 </para></listitem>
182 <listitem><para> You may bind unboxed variables in a (non-recursive,
183 non-top-level) pattern binding, but you must make any such pattern-match
184 strict. For example, rather than:
185 <programlisting>
186 data Foo = Foo Int Int#
187
188 f x = let (Foo a b, w) = ..rhs.. in ..body..
189 </programlisting>
190 you must write:
191 <programlisting>
192 data Foo = Foo Int Int#
193
194 f x = let !(Foo a b, w) = ..rhs.. in ..body..
195 </programlisting>
196 since <literal>b</literal> has type <literal>Int#</literal>.
197 </para>
198 </listitem>
199 </itemizedlist>
200 </para>
201
202 </sect2>
203
204 <sect2 id="unboxed-tuples">
205 <title>Unboxed tuples</title>
206
207 <para>
208 Unboxed tuples aren't really exported by <literal>GHC.Exts</literal>;
209 they are a syntactic extension enabled by the language flag <option>-XUnboxedTuples</option>. An
210 unboxed tuple looks like this:
211 </para>
212
213 <para>
214
215 <programlisting>
216 (# e_1, ..., e_n #)
217 </programlisting>
218
219 </para>
220
221 <para>
222 where <literal>e&lowbar;1..e&lowbar;n</literal> are expressions of any
223 type (primitive or non-primitive). The type of an unboxed tuple looks
224 the same.
225 </para>
226
227 <para>
228 Unboxed tuples are used for functions that need to return multiple
229 values, but they avoid the heap allocation normally associated with
230 using fully-fledged tuples. When an unboxed tuple is returned, the
231 components are put directly into registers or on the stack; the
232 unboxed tuple itself does not have a composite representation. Many
233 of the primitive operations listed in <literal>primops.txt.pp</literal> return unboxed
234 tuples.
235 In particular, the <literal>IO</literal> and <literal>ST</literal> monads use unboxed
236 tuples to avoid unnecessary allocation during sequences of operations.
237 </para>
238
239 <para>
240 There are some restrictions on the use of unboxed tuples:
241 <itemizedlist>
242
243 <listitem>
244 <para>
245 Values of unboxed tuple types are subject to the same restrictions as
246 other unboxed types; i.e. they may not be stored in polymorphic data
247 structures or passed to polymorphic functions.
248 </para>
249 </listitem>
250
251 <listitem>
252 <para>
253 The typical use of unboxed tuples is simply to return multiple values,
254 binding those multiple results with a <literal>case</literal> expression, thus:
255 <programlisting>
256 f x y = (# x+1, y-1 #)
257 g x = case f x x of { (# a, b #) -&#62; a + b }
258 </programlisting>
259 You can have an unboxed tuple in a pattern binding, thus
260 <programlisting>
261 f x = let (# p,q #) = h x in ..body..
262 </programlisting>
263 If the types of <literal>p</literal> and <literal>q</literal> are not unboxed,
264 the resulting binding is lazy like any other Haskell pattern binding. The
265 above example desugars like this:
266 <programlisting>
267 f x = let t = case h x o f{ (# p,q #) -> (p,q)
268 p = fst t
269 q = snd t
270 in ..body..
271 </programlisting>
272 Indeed, the bindings can even be recursive.
273 </para>
274 </listitem>
275 </itemizedlist>
276
277 </para>
278
279 </sect2>
280 </sect1>
281
282
283 <!-- ====================== SYNTACTIC EXTENSIONS ======================= -->
284
285 <sect1 id="syntax-extns">
286 <title>Syntactic extensions</title>
287
288 <sect2 id="unicode-syntax">
289 <title>Unicode syntax</title>
290 <para>The language
291 extension <option>-XUnicodeSyntax</option><indexterm><primary><option>-XUnicodeSyntax</option></primary></indexterm>
292 enables Unicode characters to be used to stand for certain ASCII
293 character sequences. The following alternatives are provided:</para>
294
295 <informaltable>
296 <tgroup cols="2" align="left" colsep="1" rowsep="1">
297 <thead>
298 <row>
299 <entry>ASCII</entry>
300 <entry>Unicode alternative</entry>
301 <entry>Code point</entry>
302 <entry>Name</entry>
303 </row>
304 </thead>
305
306 <!--
307 to find the DocBook entities for these characters, find
308 the Unicode code point (e.g. 0x2237), and grep for it in
309 /usr/share/sgml/docbook/xml-dtd-*/ent/* (or equivalent on
310 your system. Some of these Unicode code points don't have
311 equivalent DocBook entities.
312 -->
313
314 <tbody>
315 <row>
316 <entry><literal>::</literal></entry>
317 <entry>::</entry> <!-- no special char, apparently -->
318 <entry>0x2237</entry>
319 <entry>PROPORTION</entry>
320 </row>
321 </tbody>
322 <tbody>
323 <row>
324 <entry><literal>=&gt;</literal></entry>
325 <entry>&rArr;</entry>
326 <entry>0x21D2</entry>
327 <entry>RIGHTWARDS DOUBLE ARROW</entry>
328 </row>
329 </tbody>
330 <tbody>
331 <row>
332 <entry><literal>forall</literal></entry>
333 <entry>&forall;</entry>
334 <entry>0x2200</entry>
335 <entry>FOR ALL</entry>
336 </row>
337 </tbody>
338 <tbody>
339 <row>
340 <entry><literal>-&gt;</literal></entry>
341 <entry>&rarr;</entry>
342 <entry>0x2192</entry>
343 <entry>RIGHTWARDS ARROW</entry>
344 </row>
345 </tbody>
346 <tbody>
347 <row>
348 <entry><literal>&lt;-</literal></entry>
349 <entry>&larr;</entry>
350 <entry>0x2190</entry>
351 <entry>LEFTWARDS ARROW</entry>
352 </row>
353 </tbody>
354
355 <tbody>
356 <row>
357 <entry>-&lt;</entry>
358 <entry>&larrtl;</entry>
359 <entry>0x2919</entry>
360 <entry>LEFTWARDS ARROW-TAIL</entry>
361 </row>
362 </tbody>
363
364 <tbody>
365 <row>
366 <entry>&gt;-</entry>
367 <entry>&rarrtl;</entry>
368 <entry>0x291A</entry>
369 <entry>RIGHTWARDS ARROW-TAIL</entry>
370 </row>
371 </tbody>
372
373 <tbody>
374 <row>
375 <entry>-&lt;&lt;</entry>
376 <entry></entry>
377 <entry>0x291B</entry>
378 <entry>LEFTWARDS DOUBLE ARROW-TAIL</entry>
379 </row>
380 </tbody>
381
382 <tbody>
383 <row>
384 <entry>&gt;&gt;-</entry>
385 <entry></entry>
386 <entry>0x291C</entry>
387 <entry>RIGHTWARDS DOUBLE ARROW-TAIL</entry>
388 </row>
389 </tbody>
390
391 <tbody>
392 <row>
393 <entry>*</entry>
394 <entry>&starf;</entry>
395 <entry>0x2605</entry>
396 <entry>BLACK STAR</entry>
397 </row>
398 </tbody>
399
400 </tgroup>
401 </informaltable>
402 </sect2>
403
404 <sect2 id="magic-hash">
405 <title>The magic hash</title>
406 <para>The language extension <option>-XMagicHash</option> allows "&num;" as a
407 postfix modifier to identifiers. Thus, "x&num;" is a valid variable, and "T&num;" is
408 a valid type constructor or data constructor.</para>
409
410 <para>The hash sign does not change semantics at all. We tend to use variable
411 names ending in "&num;" for unboxed values or types (e.g. <literal>Int&num;</literal>),
412 but there is no requirement to do so; they are just plain ordinary variables.
413 Nor does the <option>-XMagicHash</option> extension bring anything into scope.
414 For example, to bring <literal>Int&num;</literal> into scope you must
415 import <literal>GHC.Prim</literal> (see <xref linkend="primitives"/>);
416 the <option>-XMagicHash</option> extension
417 then allows you to <emphasis>refer</emphasis> to the <literal>Int&num;</literal>
418 that is now in scope.</para>
419 <para> The <option>-XMagicHash</option> also enables some new forms of literals (see <xref linkend="glasgow-unboxed"/>):
420 <itemizedlist>
421 <listitem><para> <literal>'x'&num;</literal> has type <literal>Char&num;</literal></para> </listitem>
422 <listitem><para> <literal>&quot;foo&quot;&num;</literal> has type <literal>Addr&num;</literal></para> </listitem>
423 <listitem><para> <literal>3&num;</literal> has type <literal>Int&num;</literal>. In general,
424 any Haskell integer lexeme followed by a <literal>&num;</literal> is an <literal>Int&num;</literal> literal, e.g.
425 <literal>-0x3A&num;</literal> as well as <literal>32&num;</literal></para>.</listitem>
426 <listitem><para> <literal>3&num;&num;</literal> has type <literal>Word&num;</literal>. In general,
427 any non-negative Haskell integer lexeme followed by <literal>&num;&num;</literal>
428 is a <literal>Word&num;</literal>. </para> </listitem>
429 <listitem><para> <literal>3.2&num;</literal> has type <literal>Float&num;</literal>.</para> </listitem>
430 <listitem><para> <literal>3.2&num;&num;</literal> has type <literal>Double&num;</literal></para> </listitem>
431 </itemizedlist>
432 </para>
433 </sect2>
434
435 <!-- ====================== HIERARCHICAL MODULES ======================= -->
436
437
438 <sect2 id="hierarchical-modules">
439 <title>Hierarchical Modules</title>
440
441 <para>GHC supports a small extension to the syntax of module
442 names: a module name is allowed to contain a dot
443 <literal>&lsquo;.&rsquo;</literal>. This is also known as the
444 &ldquo;hierarchical module namespace&rdquo; extension, because
445 it extends the normally flat Haskell module namespace into a
446 more flexible hierarchy of modules.</para>
447
448 <para>This extension has very little impact on the language
449 itself; modules names are <emphasis>always</emphasis> fully
450 qualified, so you can just think of the fully qualified module
451 name as <quote>the module name</quote>. In particular, this
452 means that the full module name must be given after the
453 <literal>module</literal> keyword at the beginning of the
454 module; for example, the module <literal>A.B.C</literal> must
455 begin</para>
456
457 <programlisting>module A.B.C</programlisting>
458
459
460 <para>It is a common strategy to use the <literal>as</literal>
461 keyword to save some typing when using qualified names with
462 hierarchical modules. For example:</para>
463
464 <programlisting>
465 import qualified Control.Monad.ST.Strict as ST
466 </programlisting>
467
468 <para>For details on how GHC searches for source and interface
469 files in the presence of hierarchical modules, see <xref
470 linkend="search-path"/>.</para>
471
472 <para>GHC comes with a large collection of libraries arranged
473 hierarchically; see the accompanying <ulink
474 url="../libraries/index.html">library
475 documentation</ulink>. More libraries to install are available
476 from <ulink
477 url="http://hackage.haskell.org/packages/hackage.html">HackageDB</ulink>.</para>
478 </sect2>
479
480 <!-- ====================== PATTERN GUARDS ======================= -->
481
482 <sect2 id="pattern-guards">
483 <title>Pattern guards</title>
484
485 <para>
486 <indexterm><primary>Pattern guards (Glasgow extension)</primary></indexterm>
487 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.)
488 </para>
489
490 <para>
491 Suppose we have an abstract data type of finite maps, with a
492 lookup operation:
493
494 <programlisting>
495 lookup :: FiniteMap -> Int -> Maybe Int
496 </programlisting>
497
498 The lookup returns <function>Nothing</function> if the supplied key is not in the domain of the mapping, and <function>(Just v)</function> otherwise,
499 where <varname>v</varname> is the value that the key maps to. Now consider the following definition:
500 </para>
501
502 <programlisting>
503 clunky env var1 var2 | ok1 &amp;&amp; ok2 = val1 + val2
504 | otherwise = var1 + var2
505 where
506 m1 = lookup env var1
507 m2 = lookup env var2
508 ok1 = maybeToBool m1
509 ok2 = maybeToBool m2
510 val1 = expectJust m1
511 val2 = expectJust m2
512 </programlisting>
513
514 <para>
515 The auxiliary functions are
516 </para>
517
518 <programlisting>
519 maybeToBool :: Maybe a -&gt; Bool
520 maybeToBool (Just x) = True
521 maybeToBool Nothing = False
522
523 expectJust :: Maybe a -&gt; a
524 expectJust (Just x) = x
525 expectJust Nothing = error "Unexpected Nothing"
526 </programlisting>
527
528 <para>
529 What is <function>clunky</function> doing? The guard <literal>ok1 &amp;&amp;
530 ok2</literal> checks that both lookups succeed, using
531 <function>maybeToBool</function> to convert the <function>Maybe</function>
532 types to booleans. The (lazily evaluated) <function>expectJust</function>
533 calls extract the values from the results of the lookups, and binds the
534 returned values to <varname>val1</varname> and <varname>val2</varname>
535 respectively. If either lookup fails, then clunky takes the
536 <literal>otherwise</literal> case and returns the sum of its arguments.
537 </para>
538
539 <para>
540 This is certainly legal Haskell, but it is a tremendously verbose and
541 un-obvious way to achieve the desired effect. Arguably, a more direct way
542 to write clunky would be to use case expressions:
543 </para>
544
545 <programlisting>
546 clunky env var1 var2 = case lookup env var1 of
547 Nothing -&gt; fail
548 Just val1 -&gt; case lookup env var2 of
549 Nothing -&gt; fail
550 Just val2 -&gt; val1 + val2
551 where
552 fail = var1 + var2
553 </programlisting>
554
555 <para>
556 This is a bit shorter, but hardly better. Of course, we can rewrite any set
557 of pattern-matching, guarded equations as case expressions; that is
558 precisely what the compiler does when compiling equations! The reason that
559 Haskell provides guarded equations is because they allow us to write down
560 the cases we want to consider, one at a time, independently of each other.
561 This structure is hidden in the case version. Two of the right-hand sides
562 are really the same (<function>fail</function>), and the whole expression
563 tends to become more and more indented.
564 </para>
565
566 <para>
567 Here is how I would write clunky:
568 </para>
569
570 <programlisting>
571 clunky env var1 var2
572 | Just val1 &lt;- lookup env var1
573 , Just val2 &lt;- lookup env var2
574 = val1 + val2
575 ...other equations for clunky...
576 </programlisting>
577
578 <para>
579 The semantics should be clear enough. The qualifiers are matched in order.
580 For a <literal>&lt;-</literal> qualifier, which I call a pattern guard, the
581 right hand side is evaluated and matched against the pattern on the left.
582 If the match fails then the whole guard fails and the next equation is
583 tried. If it succeeds, then the appropriate binding takes place, and the
584 next qualifier is matched, in the augmented environment. Unlike list
585 comprehensions, however, the type of the expression to the right of the
586 <literal>&lt;-</literal> is the same as the type of the pattern to its
587 left. The bindings introduced by pattern guards scope over all the
588 remaining guard qualifiers, and over the right hand side of the equation.
589 </para>
590
591 <para>
592 Just as with list comprehensions, boolean expressions can be freely mixed
593 with among the pattern guards. For example:
594 </para>
595
596 <programlisting>
597 f x | [y] &lt;- x
598 , y > 3
599 , Just z &lt;- h y
600 = ...
601 </programlisting>
602
603 <para>
604 Haskell's current guards therefore emerge as a special case, in which the
605 qualifier list has just one element, a boolean expression.
606 </para>
607 </sect2>
608
609 <!-- ===================== View patterns =================== -->
610
611 <sect2 id="view-patterns">
612 <title>View patterns
613 </title>
614
615 <para>
616 View patterns are enabled by the flag <literal>-XViewPatterns</literal>.
617 More information and examples of view patterns can be found on the
618 <ulink url="http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns">Wiki
619 page</ulink>.
620 </para>
621
622 <para>
623 View patterns are somewhat like pattern guards that can be nested inside
624 of other patterns. They are a convenient way of pattern-matching
625 against values of abstract types. For example, in a programming language
626 implementation, we might represent the syntax of the types of the
627 language as follows:
628
629 <programlisting>
630 type Typ
631
632 data TypView = Unit
633 | Arrow Typ Typ
634
635 view :: Typ -> TypView
636
637 -- additional operations for constructing Typ's ...
638 </programlisting>
639
640 The representation of Typ is held abstract, permitting implementations
641 to use a fancy representation (e.g., hash-consing to manage sharing).
642
643 Without view patterns, using this signature a little inconvenient:
644 <programlisting>
645 size :: Typ -> Integer
646 size t = case view t of
647 Unit -> 1
648 Arrow t1 t2 -> size t1 + size t2
649 </programlisting>
650
651 It is necessary to iterate the case, rather than using an equational
652 function definition. And the situation is even worse when the matching
653 against <literal>t</literal> is buried deep inside another pattern.
654 </para>
655
656 <para>
657 View patterns permit calling the view function inside the pattern and
658 matching against the result:
659 <programlisting>
660 size (view -> Unit) = 1
661 size (view -> Arrow t1 t2) = size t1 + size t2
662 </programlisting>
663
664 That is, we add a new form of pattern, written
665 <replaceable>expression</replaceable> <literal>-></literal>
666 <replaceable>pattern</replaceable> that means "apply the expression to
667 whatever we're trying to match against, and then match the result of
668 that application against the pattern". The expression can be any Haskell
669 expression of function type, and view patterns can be used wherever
670 patterns are used.
671 </para>
672
673 <para>
674 The semantics of a pattern <literal>(</literal>
675 <replaceable>exp</replaceable> <literal>-></literal>
676 <replaceable>pat</replaceable> <literal>)</literal> are as follows:
677
678 <itemizedlist>
679
680 <listitem> Scoping:
681
682 <para>The variables bound by the view pattern are the variables bound by
683 <replaceable>pat</replaceable>.
684 </para>
685
686 <para>
687 Any variables in <replaceable>exp</replaceable> are bound occurrences,
688 but variables bound "to the left" in a pattern are in scope. This
689 feature permits, for example, one argument to a function to be used in
690 the view of another argument. For example, the function
691 <literal>clunky</literal> from <xref linkend="pattern-guards" /> can be
692 written using view patterns as follows:
693
694 <programlisting>
695 clunky env (lookup env -> Just val1) (lookup env -> Just val2) = val1 + val2
696 ...other equations for clunky...
697 </programlisting>
698 </para>
699
700 <para>
701 More precisely, the scoping rules are:
702 <itemizedlist>
703 <listitem>
704 <para>
705 In a single pattern, variables bound by patterns to the left of a view
706 pattern expression are in scope. For example:
707 <programlisting>
708 example :: Maybe ((String -> Integer,Integer), String) -> Bool
709 example Just ((f,_), f -> 4) = True
710 </programlisting>
711
712 Additionally, in function definitions, variables bound by matching earlier curried
713 arguments may be used in view pattern expressions in later arguments:
714 <programlisting>
715 example :: (String -> Integer) -> String -> Bool
716 example f (f -> 4) = True
717 </programlisting>
718 That is, the scoping is the same as it would be if the curried arguments
719 were collected into a tuple.
720 </para>
721 </listitem>
722
723 <listitem>
724 <para>
725 In mutually recursive bindings, such as <literal>let</literal>,
726 <literal>where</literal>, or the top level, view patterns in one
727 declaration may not mention variables bound by other declarations. That
728 is, each declaration must be self-contained. For example, the following
729 program is not allowed:
730 <programlisting>
731 let {(x -> y) = e1 ;
732 (y -> x) = e2 } in x
733 </programlisting>
734
735 (For some amplification on this design choice see
736 <ulink url="http://hackage.haskell.org/trac/ghc/ticket/4061">Trac #4061</ulink>.)
737
738 </para>
739 </listitem>
740 </itemizedlist>
741
742 </para>
743 </listitem>
744
745 <listitem><para> Typing: If <replaceable>exp</replaceable> has type
746 <replaceable>T1</replaceable> <literal>-></literal>
747 <replaceable>T2</replaceable> and <replaceable>pat</replaceable> matches
748 a <replaceable>T2</replaceable>, then the whole view pattern matches a
749 <replaceable>T1</replaceable>.
750 </para></listitem>
751
752 <listitem><para> Matching: To the equations in Section 3.17.3 of the
753 <ulink url="http://www.haskell.org/onlinereport/">Haskell 98
754 Report</ulink>, add the following:
755 <programlisting>
756 case v of { (e -> p) -> e1 ; _ -> e2 }
757 =
758 case (e v) of { p -> e1 ; _ -> e2 }
759 </programlisting>
760 That is, to match a variable <replaceable>v</replaceable> against a pattern
761 <literal>(</literal> <replaceable>exp</replaceable>
762 <literal>-></literal> <replaceable>pat</replaceable>
763 <literal>)</literal>, evaluate <literal>(</literal>
764 <replaceable>exp</replaceable> <replaceable> v</replaceable>
765 <literal>)</literal> and match the result against
766 <replaceable>pat</replaceable>.
767 </para></listitem>
768
769 <listitem><para> Efficiency: When the same view function is applied in
770 multiple branches of a function definition or a case expression (e.g.,
771 in <literal>size</literal> above), GHC makes an attempt to collect these
772 applications into a single nested case expression, so that the view
773 function is only applied once. Pattern compilation in GHC follows the
774 matrix algorithm described in Chapter 4 of <ulink
775 url="http://research.microsoft.com/~simonpj/Papers/slpj-book-1987/">The
776 Implementation of Functional Programming Languages</ulink>. When the
777 top rows of the first column of a matrix are all view patterns with the
778 "same" expression, these patterns are transformed into a single nested
779 case. This includes, for example, adjacent view patterns that line up
780 in a tuple, as in
781 <programlisting>
782 f ((view -> A, p1), p2) = e1
783 f ((view -> B, p3), p4) = e2
784 </programlisting>
785 </para>
786
787 <para> The current notion of when two view pattern expressions are "the
788 same" is very restricted: it is not even full syntactic equality.
789 However, it does include variables, literals, applications, and tuples;
790 e.g., two instances of <literal>view ("hi", "there")</literal> will be
791 collected. However, the current implementation does not compare up to
792 alpha-equivalence, so two instances of <literal>(x, view x ->
793 y)</literal> will not be coalesced.
794 </para>
795
796 </listitem>
797
798 </itemizedlist>
799 </para>
800
801 </sect2>
802
803 <!-- ===================== n+k patterns =================== -->
804
805 <sect2 id="n-k-patterns">
806 <title>n+k patterns</title>
807 <indexterm><primary><option>-XNPlusKPatterns</option></primary></indexterm>
808
809 <para>
810 <literal>n+k</literal> pattern support is disabled by default. To enable
811 it, you can use the <option>-XNPlusKPatterns</option> flag.
812 </para>
813
814 </sect2>
815
816 <!-- ===================== Traditional record syntax =================== -->
817
818 <sect2 id="traditional-record-syntax">
819 <title>Traditional record syntax</title>
820 <indexterm><primary><option>-XNoTraditionalRecordSyntax</option></primary></indexterm>
821
822 <para>
823 Traditional record syntax, such as <literal>C {f = x}</literal>, is enabled by default.
824 To disable it, you can use the <option>-XNoTraditionalRecordSyntax</option> flag.
825 </para>
826
827 </sect2>
828
829 <!-- ===================== Recursive do-notation =================== -->
830
831 <sect2 id="recursive-do-notation">
832 <title>The recursive do-notation
833 </title>
834
835 <para>
836 The do-notation of Haskell 98 does not allow <emphasis>recursive bindings</emphasis>,
837 that is, the variables bound in a do-expression are visible only in the textually following
838 code block. Compare this to a let-expression, where bound variables are visible in the entire binding
839 group.
840 </para>
841
842 <para>
843 It turns out that such recursive bindings do indeed make sense for a variety of monads, but
844 not all. In particular, recursion in this sense requires a fixed-point operator for the underlying
845 monad, captured by the <literal>mfix</literal> method of the <literal>MonadFix</literal> class, defined in <literal>Control.Monad.Fix</literal> as follows:
846 <programlisting>
847 class Monad m => MonadFix m where
848 mfix :: (a -> m a) -> m a
849 </programlisting>
850 Haskell's
851 <literal>Maybe</literal>, <literal>[]</literal> (list), <literal>ST</literal> (both strict and lazy versions),
852 <literal>IO</literal>, and many other monads have <literal>MonadFix</literal> instances. On the negative
853 side, the continuation monad, with the signature <literal>(a -> r) -> r</literal>, does not.
854 </para>
855
856 <para>
857 For monads that do belong to the <literal>MonadFix</literal> class, GHC provides
858 an extended version of the do-notation that allows recursive bindings.
859 The <option>-XRecursiveDo</option> (language pragma: <literal>RecursiveDo</literal>)
860 provides the necessary syntactic support, introducing the keywords <literal>mdo</literal> and
861 <literal>rec</literal> for higher and lower levels of the notation respectively. Unlike
862 bindings in a <literal>do</literal> expression, those introduced by <literal>mdo</literal> and <literal>rec</literal>
863 are recursively defined, much like in an ordinary let-expression. Due to the new
864 keyword <literal>mdo</literal>, we also call this notation the <emphasis>mdo-notation</emphasis>.
865 </para>
866
867 <para>
868 Here is a simple (albeit contrived) example:
869 <programlisting>
870 {-# LANGUAGE RecursiveDo #-}
871 justOnes = mdo { xs &lt;- Just (1:xs)
872 ; return (map negate xs) }
873 </programlisting>
874 or equivalently
875 <programlisting>
876 {-# LANGUAGE RecursiveDo #-}
877 justOnes = do { rec { xs &lt;- Just (1:xs) }
878 ; return (map negate xs) }
879 </programlisting>
880 As you can guess <literal>justOnes</literal> will evaluate to <literal>Just [-1,-1,-1,...</literal>.
881 </para>
882
883 <para>
884 GHC's implementation the mdo-notation closely follows the original translation as described in the paper
885 <ulink url="https://sites.google.com/site/leventerkok/recdo.pdf">A recursive do for Haskell</ulink>, which
886 in turn is based on the work <ulink url="http://sites.google.com/site/leventerkok/erkok-thesis.pdf">Value Recursion
887 in Monadic Computations</ulink>. Furthermore, GHC extends the syntax described in the former paper
888 with a lower level syntax flagged by the <literal>rec</literal> keyword, as we describe next.
889 </para>
890
891 <sect3>
892 <title>Recursive binding groups</title>
893
894 <para>
895 The flag <option>-XRecursiveDo</option> also introduces a new keyword <literal>rec</literal>, which wraps a
896 mutually-recursive group of monadic statements inside a <literal>do</literal> expression, producing a single statement.
897 Similar to a <literal>let</literal> statement inside a <literal>do</literal>, variables bound in
898 the <literal>rec</literal> are visible throughout the <literal>rec</literal> group, and below it. For example, compare
899 <programlisting>
900 do { a &lt;- getChar do { a &lt;- getChar
901 ; let { r1 = f a r2 ; rec { r1 &lt;- f a r2
902 ; ; r2 = g r1 } ; ; r2 &lt;- g r1 }
903 ; return (r1 ++ r2) } ; return (r1 ++ r2) }
904 </programlisting>
905 In both cases, <literal>r1</literal> and <literal>r2</literal> are available both throughout
906 the <literal>let</literal> or <literal>rec</literal> block, and in the statements that follow it.
907 The difference is that <literal>let</literal> is non-monadic, while <literal>rec</literal> is monadic.
908 (In Haskell <literal>let</literal> is really <literal>letrec</literal>, of course.)
909 </para>
910
911 <para>
912 The semantics of <literal>rec</literal> is fairly straightforward. Whenever GHC finds a <literal>rec</literal>
913 group, it will compute its set of bound variables, and will introduce an appropriate call
914 to the underlying monadic value-recursion operator <literal>mfix</literal>, belonging to the
915 <literal>MonadFix</literal> class. Here is an example:
916 <programlisting>
917 rec { b &lt;- f a c ===> (b,c) &lt;- mfix (\~(b,c) -> do { b &lt;- f a c
918 ; c &lt;- f b a } ; c &lt;- f b a
919 ; return (b,c) })
920 </programlisting>
921 As usual, the meta-variables <literal>b</literal>, <literal>c</literal> etc., can be arbitrary patterns.
922 In general, the statement <literal>rec <replaceable>ss</replaceable></literal> is desugared to the statement
923 <programlisting>
924 <replaceable>vs</replaceable> &lt;- mfix (\~<replaceable>vs</replaceable> -&gt; do { <replaceable>ss</replaceable>; return <replaceable>vs</replaceable> })
925 </programlisting>
926 where <replaceable>vs</replaceable> is a tuple of the variables bound by <replaceable>ss</replaceable>.
927 </para>
928
929 <para>
930 Note in particular that the translation for a <literal>rec</literal> block only involves wrapping a call
931 to <literal>mfix</literal>: it performs no other analysis on the bindings. The latter is the task
932 for the <literal>mdo</literal> notation, which is described next.
933 </para>
934 </sect3>
935
936 <sect3>
937 <title>The <literal>mdo</literal> notation</title>
938
939 <para>
940 A <literal>rec</literal>-block tells the compiler where precisely the recursive knot should be tied. It turns out that
941 the placement of the recursive knots can be rather delicate: in particular, we would like the knots to be wrapped
942 around as minimal groups as possible. This process is known as <emphasis>segmentation</emphasis>, and is described
943 in detail in Secton 3.2 of <ulink url="https://sites.google.com/site/leventerkok/recdo.pdf">A recursive do for
944 Haskell</ulink>. Segmentation improves polymorphism and reduces the size of the recursive knot. Most importantly, it avoids
945 unnecessary interference caused by a fundamental issue with the so-called <emphasis>right-shrinking</emphasis>
946 axiom for monadic recursion. In brief, most monads of interest (IO, strict state, etc.) do <emphasis>not</emphasis>
947 have recursion operators that satisfy this axiom, and thus not performing segmentation can cause unnecessary
948 interference, changing the termination behavior of the resulting translation.
949 (Details can be found in Sections 3.1 and 7.2.2 of
950 <ulink url="http://sites.google.com/site/leventerkok/erkok-thesis.pdf">Value Recursion in Monadic Computations</ulink>.)
951 </para>
952
953 <para>
954 The <literal>mdo</literal> notation removes the burden of placing
955 explicit <literal>rec</literal> blocks in the code. Unlike an
956 ordinary <literal>do</literal> expression, in which variables bound by
957 statements are only in scope for later statements, variables bound in
958 an <literal>mdo</literal> expression are in scope for all statements
959 of the expression. The compiler then automatically identifies minimal
960 mutually recursively dependent segments of statements, treating them as
961 if the user had wrapped a <literal>rec</literal> qualifier around them.
962 </para>
963
964 <para>
965 The definition is syntactic:
966 </para>
967 <itemizedlist>
968 <listitem>
969 <para>
970 A generator <replaceable>g</replaceable>
971 <emphasis>depends</emphasis> on a textually following generator
972 <replaceable>g'</replaceable>, if
973 </para>
974 <itemizedlist>
975 <listitem>
976 <para>
977 <replaceable>g'</replaceable> defines a variable that
978 is used by <replaceable>g</replaceable>, or
979 </para>
980 </listitem>
981 <listitem>
982 <para>
983 <replaceable>g'</replaceable> textually appears between
984 <replaceable>g</replaceable> and
985 <replaceable>g''</replaceable>, where <replaceable>g</replaceable>
986 depends on <replaceable>g''</replaceable>.
987 </para>
988 </listitem>
989 </itemizedlist>
990 </listitem>
991 <listitem>
992 <para>
993 A <emphasis>segment</emphasis> of a given
994 <literal>mdo</literal>-expression is a minimal sequence of generators
995 such that no generator of the sequence depends on an outside
996 generator. As a special case, although it is not a generator,
997 the final expression in an <literal>mdo</literal>-expression is
998 considered to form a segment by itself.
999 </para>
1000 </listitem>
1001 </itemizedlist>
1002 <para>
1003 Segments in this sense are
1004 related to <emphasis>strongly-connected components</emphasis> analysis,
1005 with the exception that bindings in a segment cannot be reordered and
1006 must be contiguous.
1007 </para>
1008
1009 <para>
1010 Here is an example <literal>mdo</literal>-expression, and its translation to <literal>rec</literal> blocks:
1011 <programlisting>
1012 mdo { a &lt;- getChar ===> do { a &lt;- getChar
1013 ; b &lt;- f a c ; rec { b &lt;- f a c
1014 ; c &lt;- f b a ; ; c &lt;- f b a }
1015 ; z &lt;- h a b ; z &lt;- h a b
1016 ; d &lt;- g d e ; rec { d &lt;- g d e
1017 ; e &lt;- g a z ; ; e &lt;- g a z }
1018 ; putChar c } ; putChar c }
1019 </programlisting>
1020 Note that a given <literal>mdo</literal> expression can cause the creation of multiple <literal>rec</literal> blocks.
1021 If there are no recursive dependencies, <literal>mdo</literal> will introduce no <literal>rec</literal> blocks. In this
1022 latter case an <literal>mdo</literal> expression is precisely the same as a <literal>do</literal> expression, as one
1023 would expect.
1024 </para>
1025
1026 <para>
1027 In summary, given an <literal>mdo</literal> expression, GHC first performs segmentation, introducing
1028 <literal>rec</literal> blocks to wrap over minimal recursive groups. Then, each resulting
1029 <literal>rec</literal> is desugared, using a call to <literal>Control.Monad.Fix.mfix</literal> as described
1030 in the previous section. The original <literal>mdo</literal>-expression typechecks exactly when the desugared
1031 version would do so.
1032 </para>
1033
1034 <para>
1035 Here are some other important points in using the recursive-do notation:
1036
1037 <itemizedlist>
1038 <listitem>
1039 <para>
1040 It is enabled with the flag <literal>-XRecursiveDo</literal>, or the <literal>LANGUAGE RecursiveDo</literal>
1041 pragma. (The same flag enables both <literal>mdo</literal>-notation, and the use of <literal>rec</literal>
1042 blocks inside <literal>do</literal> expressions.)
1043 </para>
1044 </listitem>
1045 <listitem>
1046 <para>
1047 <literal>rec</literal> blocks can also be used inside <literal>mdo</literal>-expressions, which will be
1048 treated as a single statement. However, it is good style to either use <literal>mdo</literal> or
1049 <literal>rec</literal> blocks in a single expression.
1050 </para>
1051 </listitem>
1052 <listitem>
1053 <para>
1054 If recursive bindings are required for a monad, then that monad must be declared an instance of
1055 the <literal>MonadFix</literal> class.
1056 </para>
1057 </listitem>
1058 <listitem>
1059 <para>
1060 The following instances of <literal>MonadFix</literal> are automatically provided: List, Maybe, IO.
1061 Furthermore, the <literal>Control.Monad.ST</literal> and <literal>Control.Monad.ST.Lazy</literal>
1062 modules provide the instances of the <literal>MonadFix</literal> class for Haskell's internal
1063 state monad (strict and lazy, respectively).
1064 </para>
1065 </listitem>
1066 <listitem>
1067 <para>
1068 Like <literal>let</literal> and <literal>where</literal> bindings, name shadowing is not allowed within
1069 an <literal>mdo</literal>-expression or a <literal>rec</literal>-block; that is, all the names bound in
1070 a single <literal>rec</literal> must be distinct. (GHC will complain if this is not the case.)
1071 </para>
1072 </listitem>
1073 </itemizedlist>
1074 </para>
1075 </sect3>
1076
1077
1078 </sect2>
1079
1080
1081 <!-- ===================== PARALLEL LIST COMPREHENSIONS =================== -->
1082
1083 <sect2 id="parallel-list-comprehensions">
1084 <title>Parallel List Comprehensions</title>
1085 <indexterm><primary>list comprehensions</primary><secondary>parallel</secondary>
1086 </indexterm>
1087 <indexterm><primary>parallel list comprehensions</primary>
1088 </indexterm>
1089
1090 <para>Parallel list comprehensions are a natural extension to list
1091 comprehensions. List comprehensions can be thought of as a nice
1092 syntax for writing maps and filters. Parallel comprehensions
1093 extend this to include the zipWith family.</para>
1094
1095 <para>A parallel list comprehension has multiple independent
1096 branches of qualifier lists, each separated by a `|' symbol. For
1097 example, the following zips together two lists:</para>
1098
1099 <programlisting>
1100 [ (x, y) | x &lt;- xs | y &lt;- ys ]
1101 </programlisting>
1102
1103 <para>The behaviour of parallel list comprehensions follows that of
1104 zip, in that the resulting list will have the same length as the
1105 shortest branch.</para>
1106
1107 <para>We can define parallel list comprehensions by translation to
1108 regular comprehensions. Here's the basic idea:</para>
1109
1110 <para>Given a parallel comprehension of the form: </para>
1111
1112 <programlisting>
1113 [ e | p1 &lt;- e11, p2 &lt;- e12, ...
1114 | q1 &lt;- e21, q2 &lt;- e22, ...
1115 ...
1116 ]
1117 </programlisting>
1118
1119 <para>This will be translated to: </para>
1120
1121 <programlisting>
1122 [ e | ((p1,p2), (q1,q2), ...) &lt;- zipN [(p1,p2) | p1 &lt;- e11, p2 &lt;- e12, ...]
1123 [(q1,q2) | q1 &lt;- e21, q2 &lt;- e22, ...]
1124 ...
1125 ]
1126 </programlisting>
1127
1128 <para>where `zipN' is the appropriate zip for the given number of
1129 branches.</para>
1130
1131 </sect2>
1132
1133 <!-- ===================== TRANSFORM LIST COMPREHENSIONS =================== -->
1134
1135 <sect2 id="generalised-list-comprehensions">
1136 <title>Generalised (SQL-Like) List Comprehensions</title>
1137 <indexterm><primary>list comprehensions</primary><secondary>generalised</secondary>
1138 </indexterm>
1139 <indexterm><primary>extended list comprehensions</primary>
1140 </indexterm>
1141 <indexterm><primary>group</primary></indexterm>
1142 <indexterm><primary>sql</primary></indexterm>
1143
1144
1145 <para>Generalised list comprehensions are a further enhancement to the
1146 list comprehension syntactic sugar to allow operations such as sorting
1147 and grouping which are familiar from SQL. They are fully described in the
1148 paper <ulink url="http://research.microsoft.com/~simonpj/papers/list-comp">
1149 Comprehensive comprehensions: comprehensions with "order by" and "group by"</ulink>,
1150 except that the syntax we use differs slightly from the paper.</para>
1151 <para>The extension is enabled with the flag <option>-XTransformListComp</option>.</para>
1152 <para>Here is an example:
1153 <programlisting>
1154 employees = [ ("Simon", "MS", 80)
1155 , ("Erik", "MS", 100)
1156 , ("Phil", "Ed", 40)
1157 , ("Gordon", "Ed", 45)
1158 , ("Paul", "Yale", 60)]
1159
1160 output = [ (the dept, sum salary)
1161 | (name, dept, salary) &lt;- employees
1162 , then group by dept using groupWith
1163 , then sortWith by (sum salary)
1164 , then take 5 ]
1165 </programlisting>
1166 In this example, the list <literal>output</literal> would take on
1167 the value:
1168
1169 <programlisting>
1170 [("Yale", 60), ("Ed", 85), ("MS", 180)]
1171 </programlisting>
1172 </para>
1173 <para>There are three new keywords: <literal>group</literal>, <literal>by</literal>, and <literal>using</literal>.
1174 (The functions <literal>sortWith</literal> and <literal>groupWith</literal> are not keywords; they are ordinary
1175 functions that are exported by <literal>GHC.Exts</literal>.)</para>
1176
1177 <para>There are five new forms of comprehension qualifier,
1178 all introduced by the (existing) keyword <literal>then</literal>:
1179 <itemizedlist>
1180 <listitem>
1181
1182 <programlisting>
1183 then f
1184 </programlisting>
1185
1186 This statement requires that <literal>f</literal> have the type <literal>
1187 forall a. [a] -> [a]</literal>. You can see an example of its use in the
1188 motivating example, as this form is used to apply <literal>take 5</literal>.
1189
1190 </listitem>
1191
1192
1193 <listitem>
1194 <para>
1195 <programlisting>
1196 then f by e
1197 </programlisting>
1198
1199 This form is similar to the previous one, but allows you to create a function
1200 which will be passed as the first argument to f. As a consequence f must have
1201 the type <literal>forall a. (a -> t) -> [a] -> [a]</literal>. As you can see
1202 from the type, this function lets f &quot;project out&quot; some information
1203 from the elements of the list it is transforming.</para>
1204
1205 <para>An example is shown in the opening example, where <literal>sortWith</literal>
1206 is supplied with a function that lets it find out the <literal>sum salary</literal>
1207 for any item in the list comprehension it transforms.</para>
1208
1209 </listitem>
1210
1211
1212 <listitem>
1213
1214 <programlisting>
1215 then group by e using f
1216 </programlisting>
1217
1218 <para>This is the most general of the grouping-type statements. In this form,
1219 f is required to have type <literal>forall a. (a -> t) -> [a] -> [[a]]</literal>.
1220 As with the <literal>then f by e</literal> case above, the first argument
1221 is a function supplied to f by the compiler which lets it compute e on every
1222 element of the list being transformed. However, unlike the non-grouping case,
1223 f additionally partitions the list into a number of sublists: this means that
1224 at every point after this statement, binders occurring before it in the comprehension
1225 refer to <emphasis>lists</emphasis> of possible values, not single values. To help understand
1226 this, let's look at an example:</para>
1227
1228 <programlisting>
1229 -- This works similarly to groupWith in GHC.Exts, but doesn't sort its input first
1230 groupRuns :: Eq b => (a -> b) -> [a] -> [[a]]
1231 groupRuns f = groupBy (\x y -> f x == f y)
1232
1233 output = [ (the x, y)
1234 | x &lt;- ([1..3] ++ [1..2])
1235 , y &lt;- [4..6]
1236 , then group by x using groupRuns ]
1237 </programlisting>
1238
1239 <para>This results in the variable <literal>output</literal> taking on the value below:</para>
1240
1241 <programlisting>
1242 [(1, [4, 5, 6]), (2, [4, 5, 6]), (3, [4, 5, 6]), (1, [4, 5, 6]), (2, [4, 5, 6])]
1243 </programlisting>
1244
1245 <para>Note that we have used the <literal>the</literal> function to change the type
1246 of x from a list to its original numeric type. The variable y, in contrast, is left
1247 unchanged from the list form introduced by the grouping.</para>
1248
1249 </listitem>
1250
1251 <listitem>
1252
1253 <programlisting>
1254 then group using f
1255 </programlisting>
1256
1257 <para>With this form of the group statement, f is required to simply have the type
1258 <literal>forall a. [a] -> [[a]]</literal>, which will be used to group up the
1259 comprehension so far directly. An example of this form is as follows:</para>
1260
1261 <programlisting>
1262 output = [ x
1263 | y &lt;- [1..5]
1264 , x &lt;- "hello"
1265 , then group using inits]
1266 </programlisting>
1267
1268 <para>This will yield a list containing every prefix of the word "hello" written out 5 times:</para>
1269
1270 <programlisting>
1271 ["","h","he","hel","hell","hello","helloh","hellohe","hellohel","hellohell","hellohello","hellohelloh",...]
1272 </programlisting>
1273
1274 </listitem>
1275 </itemizedlist>
1276 </para>
1277 </sect2>
1278
1279 <!-- ===================== MONAD COMPREHENSIONS ===================== -->
1280
1281 <sect2 id="monad-comprehensions">
1282 <title>Monad comprehensions</title>
1283 <indexterm><primary>monad comprehensions</primary></indexterm>
1284
1285 <para>
1286 Monad comprehensions generalise the list comprehension notation,
1287 including parallel comprehensions
1288 (<xref linkend="parallel-list-comprehensions"/>) and
1289 transform comprehensions (<xref linkend="generalised-list-comprehensions"/>)
1290 to work for any monad.
1291 </para>
1292
1293 <para>Monad comprehensions support:</para>
1294
1295 <itemizedlist>
1296 <listitem>
1297 <para>
1298 Bindings:
1299 </para>
1300
1301 <programlisting>
1302 [ x + y | x &lt;- Just 1, y &lt;- Just 2 ]
1303 </programlisting>
1304
1305 <para>
1306 Bindings are translated with the <literal>(&gt;&gt;=)</literal> and
1307 <literal>return</literal> functions to the usual do-notation:
1308 </para>
1309
1310 <programlisting>
1311 do x &lt;- Just 1
1312 y &lt;- Just 2
1313 return (x+y)
1314 </programlisting>
1315
1316 </listitem>
1317 <listitem>
1318 <para>
1319 Guards:
1320 </para>
1321
1322 <programlisting>
1323 [ x | x &lt;- [1..10], x &lt;= 5 ]
1324 </programlisting>
1325
1326 <para>
1327 Guards are translated with the <literal>guard</literal> function,
1328 which requires a <literal>MonadPlus</literal> instance:
1329 </para>
1330
1331 <programlisting>
1332 do x &lt;- [1..10]
1333 guard (x &lt;= 5)
1334 return x
1335 </programlisting>
1336
1337 </listitem>
1338 <listitem>
1339 <para>
1340 Transform statements (as with <literal>-XTransformListComp</literal>):
1341 </para>
1342
1343 <programlisting>
1344 [ x+y | x &lt;- [1..10], y &lt;- [1..x], then take 2 ]
1345 </programlisting>
1346
1347 <para>
1348 This translates to:
1349 </para>
1350
1351 <programlisting>
1352 do (x,y) &lt;- take 2 (do x &lt;- [1..10]
1353 y &lt;- [1..x]
1354 return (x,y))
1355 return (x+y)
1356 </programlisting>
1357
1358 </listitem>
1359 <listitem>
1360 <para>
1361 Group statements (as with <literal>-XTransformListComp</literal>):
1362 </para>
1363
1364 <programlisting>
1365 [ x | x &lt;- [1,1,2,2,3], then group by x using GHC.Exts.groupWith ]
1366 [ x | x &lt;- [1,1,2,2,3], then group using myGroup ]
1367 </programlisting>
1368
1369 </listitem>
1370 <listitem>
1371 <para>
1372 Parallel statements (as with <literal>-XParallelListComp</literal>):
1373 </para>
1374
1375 <programlisting>
1376 [ (x+y) | x &lt;- [1..10]
1377 | y &lt;- [11..20]
1378 ]
1379 </programlisting>
1380
1381 <para>
1382 Parallel statements are translated using the
1383 <literal>mzip</literal> function, which requires a
1384 <literal>MonadZip</literal> instance defined in
1385 <ulink url="&libraryBaseLocation;/Control-Monad-Zip.html"><literal>Control.Monad.Zip</literal></ulink>:
1386 </para>
1387
1388 <programlisting>
1389 do (x,y) &lt;- mzip (do x &lt;- [1..10]
1390 return x)
1391 (do y &lt;- [11..20]
1392 return y)
1393 return (x+y)
1394 </programlisting>
1395
1396 </listitem>
1397 </itemizedlist>
1398
1399 <para>
1400 All these features are enabled by default if the
1401 <literal>MonadComprehensions</literal> extension is enabled. The types
1402 and more detailed examples on how to use comprehensions are explained
1403 in the previous chapters <xref
1404 linkend="generalised-list-comprehensions"/> and <xref
1405 linkend="parallel-list-comprehensions"/>. In general you just have
1406 to replace the type <literal>[a]</literal> with the type
1407 <literal>Monad m => m a</literal> for monad comprehensions.
1408 </para>
1409
1410 <para>
1411 Note: Even though most of these examples are using the list monad,
1412 monad comprehensions work for any monad.
1413 The <literal>base</literal> package offers all necessary instances for
1414 lists, which make <literal>MonadComprehensions</literal> backward
1415 compatible to built-in, transform and parallel list comprehensions.
1416 </para>
1417 <para> More formally, the desugaring is as follows. We write <literal>D[ e | Q]</literal>
1418 to mean the desugaring of the monad comprehension <literal>[ e | Q]</literal>:
1419 <programlisting>
1420 Expressions: e
1421 Declarations: d
1422 Lists of qualifiers: Q,R,S
1423
1424 -- Basic forms
1425 D[ e | ] = return e
1426 D[ e | p &lt;- e, Q ] = e &gt;&gt;= \p -&gt; D[ e | Q ]
1427 D[ e | e, Q ] = guard e &gt;&gt; \p -&gt; D[ e | Q ]
1428 D[ e | let d, Q ] = let d in D[ e | Q ]
1429
1430 -- Parallel comprehensions (iterate for multiple parallel branches)
1431 D[ e | (Q | R), S ] = mzip D[ Qv | Q ] D[ Rv | R ] &gt;&gt;= \(Qv,Rv) -&gt; D[ e | S ]
1432
1433 -- Transform comprehensions
1434 D[ e | Q then f, R ] = f D[ Qv | Q ] &gt;&gt;= \Qv -&gt; D[ e | R ]
1435
1436 D[ e | Q then f by b, R ] = f (\Qv -&gt; b) D[ Qv | Q ] &gt;&gt;= \Qv -&gt; D[ e | R ]
1437
1438 D[ e | Q then group using f, R ] = f D[ Qv | Q ] &gt;&gt;= \ys -&gt;
1439 case (fmap selQv1 ys, ..., fmap selQvn ys) of
1440 Qv -&gt; D[ e | R ]
1441
1442 D[ e | Q then group by b using f, R ] = f (\Qv -&gt; b) D[ Qv | Q ] &gt;&gt;= \ys -&gt;
1443 case (fmap selQv1 ys, ..., fmap selQvn ys) of
1444 Qv -&gt; D[ e | R ]
1445
1446 where Qv is the tuple of variables bound by Q (and used subsequently)
1447 selQvi is a selector mapping Qv to the ith component of Qv
1448
1449 Operator Standard binding Expected type
1450 --------------------------------------------------------------------
1451 return GHC.Base t1 -&gt; m t2
1452 (&gt;&gt;=) GHC.Base m1 t1 -&gt; (t2 -&gt; m2 t3) -&gt; m3 t3
1453 (&gt;&gt;) GHC.Base m1 t1 -&gt; m2 t2 -&gt; m3 t3
1454 guard Control.Monad t1 -&gt; m t2
1455 fmap GHC.Base forall a b. (a-&gt;b) -&gt; n a -&gt; n b
1456 mzip Control.Monad.Zip forall a b. m a -&gt; m b -&gt; m (a,b)
1457 </programlisting>
1458 The comprehension should typecheck when its desugaring would typecheck.
1459 </para>
1460 <para>
1461 Monad comprehensions support rebindable syntax (<xref linkend="rebindable-syntax"/>).
1462 Without rebindable
1463 syntax, the operators from the "standard binding" module are used; with
1464 rebindable syntax, the operators are looked up in the current lexical scope.
1465 For example, parallel comprehensions will be typechecked and desugared
1466 using whatever "<literal>mzip</literal>" is in scope.
1467 </para>
1468 <para>
1469 The rebindable operators must have the "Expected type" given in the
1470 table above. These types are surprisingly general. For example, you can
1471 use a bind operator with the type
1472 <programlisting>
1473 (>>=) :: T x y a -> (a -> T y z b) -> T x z b
1474 </programlisting>
1475 In the case of transform comprehensions, notice that the groups are
1476 parameterised over some arbitrary type <literal>n</literal> (provided it
1477 has an <literal>fmap</literal>, as well as
1478 the comprehension being over an arbitrary monad.
1479 </para>
1480 </sect2>
1481
1482 <!-- ===================== REBINDABLE SYNTAX =================== -->
1483
1484 <sect2 id="rebindable-syntax">
1485 <title>Rebindable syntax and the implicit Prelude import</title>
1486
1487 <para><indexterm><primary>-XNoImplicitPrelude
1488 option</primary></indexterm> GHC normally imports
1489 <filename>Prelude.hi</filename> files for you. If you'd
1490 rather it didn't, then give it a
1491 <option>-XNoImplicitPrelude</option> option. The idea is
1492 that you can then import a Prelude of your own. (But don't
1493 call it <literal>Prelude</literal>; the Haskell module
1494 namespace is flat, and you must not conflict with any
1495 Prelude module.)</para>
1496
1497 <para>Suppose you are importing a Prelude of your own
1498 in order to define your own numeric class
1499 hierarchy. It completely defeats that purpose if the
1500 literal "1" means "<literal>Prelude.fromInteger
1501 1</literal>", which is what the Haskell Report specifies.
1502 So the <option>-XRebindableSyntax</option>
1503 flag causes
1504 the following pieces of built-in syntax to refer to
1505 <emphasis>whatever is in scope</emphasis>, not the Prelude
1506 versions:
1507 <itemizedlist>
1508 <listitem>
1509 <para>An integer literal <literal>368</literal> means
1510 "<literal>fromInteger (368::Integer)</literal>", rather than
1511 "<literal>Prelude.fromInteger (368::Integer)</literal>".
1512 </para> </listitem>
1513
1514 <listitem><para>Fractional literals are handed in just the same way,
1515 except that the translation is
1516 <literal>fromRational (3.68::Rational)</literal>.
1517 </para> </listitem>
1518
1519 <listitem><para>The equality test in an overloaded numeric pattern
1520 uses whatever <literal>(==)</literal> is in scope.
1521 </para> </listitem>
1522
1523 <listitem><para>The subtraction operation, and the
1524 greater-than-or-equal test, in <literal>n+k</literal> patterns
1525 use whatever <literal>(-)</literal> and <literal>(>=)</literal> are in scope.
1526 </para></listitem>
1527
1528 <listitem>
1529 <para>Negation (e.g. "<literal>- (f x)</literal>")
1530 means "<literal>negate (f x)</literal>", both in numeric
1531 patterns, and expressions.
1532 </para></listitem>
1533
1534 <listitem>
1535 <para>Conditionals (e.g. "<literal>if</literal> e1 <literal>then</literal> e2 <literal>else</literal> e3")
1536 means "<literal>ifThenElse</literal> e1 e2 e3". However <literal>case</literal> expressions are unaffected.
1537 </para></listitem>
1538
1539 <listitem>
1540 <para>"Do" notation is translated using whatever
1541 functions <literal>(>>=)</literal>,
1542 <literal>(>>)</literal>, and <literal>fail</literal>,
1543 are in scope (not the Prelude
1544 versions). List comprehensions, mdo (<xref linkend="recursive-do-notation"/>), and parallel array
1545 comprehensions, are unaffected. </para></listitem>
1546
1547 <listitem>
1548 <para>Arrow
1549 notation (see <xref linkend="arrow-notation"/>)
1550 uses whatever <literal>arr</literal>,
1551 <literal>(>>>)</literal>, <literal>first</literal>,
1552 <literal>app</literal>, <literal>(|||)</literal> and
1553 <literal>loop</literal> functions are in scope. But unlike the
1554 other constructs, the types of these functions must match the
1555 Prelude types very closely. Details are in flux; if you want
1556 to use this, ask!
1557 </para></listitem>
1558 </itemizedlist>
1559 <option>-XRebindableSyntax</option> implies <option>-XNoImplicitPrelude</option>.
1560 </para>
1561 <para>
1562 In all cases (apart from arrow notation), the static semantics should be that of the desugared form,
1563 even if that is a little unexpected. For example, the
1564 static semantics of the literal <literal>368</literal>
1565 is exactly that of <literal>fromInteger (368::Integer)</literal>; it's fine for
1566 <literal>fromInteger</literal> to have any of the types:
1567 <programlisting>
1568 fromInteger :: Integer -> Integer
1569 fromInteger :: forall a. Foo a => Integer -> a
1570 fromInteger :: Num a => a -> Integer
1571 fromInteger :: Integer -> Bool -> Bool
1572 </programlisting>
1573 </para>
1574
1575 <para>Be warned: this is an experimental facility, with
1576 fewer checks than usual. Use <literal>-dcore-lint</literal>
1577 to typecheck the desugared program. If Core Lint is happy
1578 you should be all right.</para>
1579
1580 </sect2>
1581
1582 <sect2 id="postfix-operators">
1583 <title>Postfix operators</title>
1584
1585 <para>
1586 The <option>-XPostfixOperators</option> flag enables a small
1587 extension to the syntax of left operator sections, which allows you to
1588 define postfix operators. The extension is this: the left section
1589 <programlisting>
1590 (e !)
1591 </programlisting>
1592 is equivalent (from the point of view of both type checking and execution) to the expression
1593 <programlisting>
1594 ((!) e)
1595 </programlisting>
1596 (for any expression <literal>e</literal> and operator <literal>(!)</literal>.
1597 The strict Haskell 98 interpretation is that the section is equivalent to
1598 <programlisting>
1599 (\y -> (!) e y)
1600 </programlisting>
1601 That is, the operator must be a function of two arguments. GHC allows it to
1602 take only one argument, and that in turn allows you to write the function
1603 postfix.
1604 </para>
1605 <para>The extension does not extend to the left-hand side of function
1606 definitions; you must define such a function in prefix form.</para>
1607
1608 </sect2>
1609
1610 <sect2 id="tuple-sections">
1611 <title>Tuple sections</title>
1612
1613 <para>
1614 The <option>-XTupleSections</option> flag enables Python-style partially applied
1615 tuple constructors. For example, the following program
1616 <programlisting>
1617 (, True)
1618 </programlisting>
1619 is considered to be an alternative notation for the more unwieldy alternative
1620 <programlisting>
1621 \x -> (x, True)
1622 </programlisting>
1623 You can omit any combination of arguments to the tuple, as in the following
1624 <programlisting>
1625 (, "I", , , "Love", , 1337)
1626 </programlisting>
1627 which translates to
1628 <programlisting>
1629 \a b c d -> (a, "I", b, c, "Love", d, 1337)
1630 </programlisting>
1631 </para>
1632
1633 <para>
1634 If you have <link linkend="unboxed-tuples">unboxed tuples</link> enabled, tuple sections
1635 will also be available for them, like so
1636 <programlisting>
1637 (# , True #)
1638 </programlisting>
1639 Because there is no unboxed unit tuple, the following expression
1640 <programlisting>
1641 (# #)
1642 </programlisting>
1643 continues to stand for the unboxed singleton tuple data constructor.
1644 </para>
1645
1646 </sect2>
1647
1648 <sect2 id="lambda-case">
1649 <title>Lambda-case</title>
1650 <para>
1651 The <option>-XLambdaCase</option> flag enables expressions of the form
1652 <programlisting>
1653 \case { p1 -> e1; ...; pN -> eN }
1654 </programlisting>
1655 which is equivalent to
1656 <programlisting>
1657 \freshName -> case freshName of { p1 -> e1; ...; pN -> eN }
1658 </programlisting>
1659 Note that <literal>\case</literal> starts a layout, so you can write
1660 <programlisting>
1661 \case
1662 p1 -> e1
1663 ...
1664 pN -> eN
1665 </programlisting>
1666 </para>
1667 </sect2>
1668
1669 <sect2 id="multi-way-if">
1670 <title>Multi-way if-expressions</title>
1671 <para>
1672 With <option>-XMultiWayIf</option> flag GHC accepts conditional expressions
1673 with multiple branches:
1674 <programlisting>
1675 if | guard1 -> expr1
1676 | ...
1677 | guardN -> exprN
1678 </programlisting>
1679 which is roughly equivalent to
1680 <programlisting>
1681 case () of
1682 _ | guard1 -> expr1
1683 ...
1684 _ | guardN -> exprN
1685 </programlisting>
1686 except that multi-way if-expressions do not alter the layout.
1687 </para>
1688 </sect2>
1689
1690 <sect2 id="disambiguate-fields">
1691 <title>Record field disambiguation</title>
1692 <para>
1693 In record construction and record pattern matching
1694 it is entirely unambiguous which field is referred to, even if there are two different
1695 data types in scope with a common field name. For example:
1696 <programlisting>
1697 module M where
1698 data S = MkS { x :: Int, y :: Bool }
1699
1700 module Foo where
1701 import M
1702
1703 data T = MkT { x :: Int }
1704
1705 ok1 (MkS { x = n }) = n+1 -- Unambiguous
1706 ok2 n = MkT { x = n+1 } -- Unambiguous
1707
1708 bad1 k = k { x = 3 } -- Ambiguous
1709 bad2 k = x k -- Ambiguous
1710 </programlisting>
1711 Even though there are two <literal>x</literal>'s in scope,
1712 it is clear that the <literal>x</literal> in the pattern in the
1713 definition of <literal>ok1</literal> can only mean the field
1714 <literal>x</literal> from type <literal>S</literal>. Similarly for
1715 the function <literal>ok2</literal>. However, in the record update
1716 in <literal>bad1</literal> and the record selection in <literal>bad2</literal>
1717 it is not clear which of the two types is intended.
1718 </para>
1719 <para>
1720 Haskell 98 regards all four as ambiguous, but with the
1721 <option>-XDisambiguateRecordFields</option> flag, GHC will accept
1722 the former two. The rules are precisely the same as those for instance
1723 declarations in Haskell 98, where the method names on the left-hand side
1724 of the method bindings in an instance declaration refer unambiguously
1725 to the method of that class (provided they are in scope at all), even
1726 if there are other variables in scope with the same name.
1727 This reduces the clutter of qualified names when you import two
1728 records from different modules that use the same field name.
1729 </para>
1730 <para>
1731 Some details:
1732 <itemizedlist>
1733 <listitem><para>
1734 Field disambiguation can be combined with punning (see <xref linkend="record-puns"/>). For example:
1735 <programlisting>
1736 module Foo where
1737 import M
1738 x=True
1739 ok3 (MkS { x }) = x+1 -- Uses both disambiguation and punning
1740 </programlisting>
1741 </para></listitem>
1742
1743 <listitem><para>
1744 With <option>-XDisambiguateRecordFields</option> you can use <emphasis>unqualified</emphasis>
1745 field names even if the corresponding selector is only in scope <emphasis>qualified</emphasis>
1746 For example, assuming the same module <literal>M</literal> as in our earlier example, this is legal:
1747 <programlisting>
1748 module Foo where
1749 import qualified M -- Note qualified
1750
1751 ok4 (M.MkS { x = n }) = n+1 -- Unambiguous
1752 </programlisting>
1753 Since the constructor <literal>MkS</literal> is only in scope qualified, you must
1754 name it <literal>M.MkS</literal>, but the field <literal>x</literal> does not need
1755 to be qualified even though <literal>M.x</literal> is in scope but <literal>x</literal>
1756 is not. (In effect, it is qualified by the constructor.)
1757 </para></listitem>
1758 </itemizedlist>
1759 </para>
1760
1761 </sect2>
1762
1763 <!-- ===================== Record puns =================== -->
1764
1765 <sect2 id="record-puns">
1766 <title>Record puns
1767 </title>
1768
1769 <para>
1770 Record puns are enabled by the flag <literal>-XNamedFieldPuns</literal>.
1771 </para>
1772
1773 <para>
1774 When using records, it is common to write a pattern that binds a
1775 variable with the same name as a record field, such as:
1776
1777 <programlisting>
1778 data C = C {a :: Int}
1779 f (C {a = a}) = a
1780 </programlisting>
1781 </para>
1782
1783 <para>
1784 Record punning permits the variable name to be elided, so one can simply
1785 write
1786
1787 <programlisting>
1788 f (C {a}) = a
1789 </programlisting>
1790
1791 to mean the same pattern as above. That is, in a record pattern, the
1792 pattern <literal>a</literal> expands into the pattern <literal>a =
1793 a</literal> for the same name <literal>a</literal>.
1794 </para>
1795
1796 <para>
1797 Note that:
1798 <itemizedlist>
1799 <listitem><para>
1800 Record punning can also be used in an expression, writing, for example,
1801 <programlisting>
1802 let a = 1 in C {a}
1803 </programlisting>
1804 instead of
1805 <programlisting>
1806 let a = 1 in C {a = a}
1807 </programlisting>
1808 The expansion is purely syntactic, so the expanded right-hand side
1809 expression refers to the nearest enclosing variable that is spelled the
1810 same as the field name.
1811 </para></listitem>
1812
1813 <listitem><para>
1814 Puns and other patterns can be mixed in the same record:
1815 <programlisting>
1816 data C = C {a :: Int, b :: Int}
1817 f (C {a, b = 4}) = a
1818 </programlisting>
1819 </para></listitem>
1820
1821 <listitem><para>
1822 Puns can be used wherever record patterns occur (e.g. in
1823 <literal>let</literal> bindings or at the top-level).
1824 </para></listitem>
1825
1826 <listitem><para>
1827 A pun on a qualified field name is expanded by stripping off the module qualifier.
1828 For example:
1829 <programlisting>
1830 f (C {M.a}) = a
1831 </programlisting>
1832 means
1833 <programlisting>
1834 f (M.C {M.a = a}) = a
1835 </programlisting>
1836 (This is useful if the field selector <literal>a</literal> for constructor <literal>M.C</literal>
1837 is only in scope in qualified form.)
1838 </para></listitem>
1839 </itemizedlist>
1840 </para>
1841
1842
1843 </sect2>
1844
1845 <!-- ===================== Record wildcards =================== -->
1846
1847 <sect2 id="record-wildcards">
1848 <title>Record wildcards
1849 </title>
1850
1851 <para>
1852 Record wildcards are enabled by the flag <literal>-XRecordWildCards</literal>.
1853 This flag implies <literal>-XDisambiguateRecordFields</literal>.
1854 </para>
1855
1856 <para>
1857 For records with many fields, it can be tiresome to write out each field
1858 individually in a record pattern, as in
1859 <programlisting>
1860 data C = C {a :: Int, b :: Int, c :: Int, d :: Int}
1861 f (C {a = 1, b = b, c = c, d = d}) = b + c + d
1862 </programlisting>
1863 </para>
1864
1865 <para>
1866 Record wildcard syntax permits a "<literal>..</literal>" in a record
1867 pattern, where each elided field <literal>f</literal> is replaced by the
1868 pattern <literal>f = f</literal>. For example, the above pattern can be
1869 written as
1870 <programlisting>
1871 f (C {a = 1, ..}) = b + c + d
1872 </programlisting>
1873 </para>
1874
1875 <para>
1876 More details:
1877 <itemizedlist>
1878 <listitem><para>
1879 Wildcards can be mixed with other patterns, including puns
1880 (<xref linkend="record-puns"/>); for example, in a pattern <literal>C {a
1881 = 1, b, ..})</literal>. Additionally, record wildcards can be used
1882 wherever record patterns occur, including in <literal>let</literal>
1883 bindings and at the top-level. For example, the top-level binding
1884 <programlisting>
1885 C {a = 1, ..} = e
1886 </programlisting>
1887 defines <literal>b</literal>, <literal>c</literal>, and
1888 <literal>d</literal>.
1889 </para></listitem>
1890
1891 <listitem><para>
1892 Record wildcards can also be used in expressions, writing, for example,
1893 <programlisting>
1894 let {a = 1; b = 2; c = 3; d = 4} in C {..}
1895 </programlisting>
1896 in place of
1897 <programlisting>
1898 let {a = 1; b = 2; c = 3; d = 4} in C {a=a, b=b, c=c, d=d}
1899 </programlisting>
1900 The expansion is purely syntactic, so the record wildcard
1901 expression refers to the nearest enclosing variables that are spelled
1902 the same as the omitted field names.
1903 </para></listitem>
1904
1905 <listitem><para>
1906 The "<literal>..</literal>" expands to the missing
1907 <emphasis>in-scope</emphasis> record fields.
1908 Specifically the expansion of "<literal>C {..}</literal>" includes
1909 <literal>f</literal> if and only if:
1910 <itemizedlist>
1911 <listitem><para>
1912 <literal>f</literal> is a record field of constructor <literal>C</literal>.
1913 </para></listitem>
1914 <listitem><para>
1915 The record field <literal>f</literal> is in scope somehow (either qualified or unqualified).
1916 </para></listitem>
1917 <listitem><para>
1918 In the case of expressions (but not patterns),
1919 the variable <literal>f</literal> is in scope unqualified,
1920 apart from the binding of the record selector itself.
1921 </para></listitem>
1922 </itemizedlist>
1923 For example
1924 <programlisting>
1925 module M where
1926 data R = R { a,b,c :: Int }
1927 module X where
1928 import M( R(a,c) )
1929 f b = R { .. }
1930 </programlisting>
1931 The <literal>R{..}</literal> expands to <literal>R{M.a=a}</literal>,
1932 omitting <literal>b</literal> since the record field is not in scope,
1933 and omitting <literal>c</literal> since the variable <literal>c</literal>
1934 is not in scope (apart from the binding of the
1935 record selector <literal>c</literal>, of course).
1936 </para></listitem>
1937 </itemizedlist>
1938 </para>
1939
1940 </sect2>
1941
1942 <!-- ===================== Local fixity declarations =================== -->
1943
1944 <sect2 id="local-fixity-declarations">
1945 <title>Local Fixity Declarations
1946 </title>
1947
1948 <para>A careful reading of the Haskell 98 Report reveals that fixity
1949 declarations (<literal>infix</literal>, <literal>infixl</literal>, and
1950 <literal>infixr</literal>) are permitted to appear inside local bindings
1951 such those introduced by <literal>let</literal> and
1952 <literal>where</literal>. However, the Haskell Report does not specify
1953 the semantics of such bindings very precisely.
1954 </para>
1955
1956 <para>In GHC, a fixity declaration may accompany a local binding:
1957 <programlisting>
1958 let f = ...
1959 infixr 3 `f`
1960 in
1961 ...
1962 </programlisting>
1963 and the fixity declaration applies wherever the binding is in scope.
1964 For example, in a <literal>let</literal>, it applies in the right-hand
1965 sides of other <literal>let</literal>-bindings and the body of the
1966 <literal>let</literal>C. Or, in recursive <literal>do</literal>
1967 expressions (<xref linkend="recursive-do-notation"/>), the local fixity
1968 declarations of a <literal>let</literal> statement scope over other
1969 statements in the group, just as the bound name does.
1970 </para>
1971
1972 <para>
1973 Moreover, a local fixity declaration *must* accompany a local binding of
1974 that name: it is not possible to revise the fixity of name bound
1975 elsewhere, as in
1976 <programlisting>
1977 let infixr 9 $ in ...
1978 </programlisting>
1979
1980 Because local fixity declarations are technically Haskell 98, no flag is
1981 necessary to enable them.
1982 </para>
1983 </sect2>
1984
1985 <sect2 id="package-imports">
1986 <title>Package-qualified imports</title>
1987
1988 <para>With the <option>-XPackageImports</option> flag, GHC allows
1989 import declarations to be qualified by the package name that the
1990 module is intended to be imported from. For example:</para>
1991
1992 <programlisting>
1993 import "network" Network.Socket
1994 </programlisting>
1995
1996 <para>would import the module <literal>Network.Socket</literal> from
1997 the package <literal>network</literal> (any version). This may
1998 be used to disambiguate an import when the same module is
1999 available from multiple packages, or is present in both the
2000 current package being built and an external package.</para>
2001
2002 <para>The special package name <literal>this</literal> can be used to
2003 refer to the current package being built.</para>
2004
2005 <para>Note: you probably don't need to use this feature, it was
2006 added mainly so that we can build backwards-compatible versions of
2007 packages when APIs change. It can lead to fragile dependencies in
2008 the common case: modules occasionally move from one package to
2009 another, rendering any package-qualified imports broken.</para>
2010 </sect2>
2011
2012 <sect2 id="safe-imports-ext">
2013 <title>Safe imports</title>
2014
2015 <para>With the <option>-XSafe</option>, <option>-XTrustworthy</option>
2016 and <option>-XUnsafe</option> language flags, GHC extends
2017 the import declaration syntax to take an optional <literal>safe</literal>
2018 keyword after the <literal>import</literal> keyword. This feature
2019 is part of the Safe Haskell GHC extension. For example:</para>
2020
2021 <programlisting>
2022 import safe qualified Network.Socket as NS
2023 </programlisting>
2024
2025 <para>would import the module <literal>Network.Socket</literal>
2026 with compilation only succeeding if Network.Socket can be
2027 safely imported. For a description of when a import is
2028 considered safe see <xref linkend="safe-haskell"/></para>
2029
2030 </sect2>
2031
2032 <sect2 id="syntax-stolen">
2033 <title>Summary of stolen syntax</title>
2034
2035 <para>Turning on an option that enables special syntax
2036 <emphasis>might</emphasis> cause working Haskell 98 code to fail
2037 to compile, perhaps because it uses a variable name which has
2038 become a reserved word. This section lists the syntax that is
2039 "stolen" by language extensions.
2040 We use
2041 notation and nonterminal names from the Haskell 98 lexical syntax
2042 (see the Haskell 98 Report).
2043 We only list syntax changes here that might affect
2044 existing working programs (i.e. "stolen" syntax). Many of these
2045 extensions will also enable new context-free syntax, but in all
2046 cases programs written to use the new syntax would not be
2047 compilable without the option enabled.</para>
2048
2049 <para>There are two classes of special
2050 syntax:
2051
2052 <itemizedlist>
2053 <listitem>
2054 <para>New reserved words and symbols: character sequences
2055 which are no longer available for use as identifiers in the
2056 program.</para>
2057 </listitem>
2058 <listitem>
2059 <para>Other special syntax: sequences of characters that have
2060 a different meaning when this particular option is turned
2061 on.</para>
2062 </listitem>
2063 </itemizedlist>
2064
2065 The following syntax is stolen:
2066
2067 <variablelist>
2068 <varlistentry>
2069 <term>
2070 <literal>forall</literal>
2071 <indexterm><primary><literal>forall</literal></primary></indexterm>
2072 </term>
2073 <listitem><para>
2074 Stolen (in types) by: <option>-XExplicitForAll</option>, and hence by
2075 <option>-XScopedTypeVariables</option>,
2076 <option>-XLiberalTypeSynonyms</option>,
2077 <option>-XRankNTypes</option>,
2078 <option>-XExistentialQuantification</option>
2079 </para></listitem>
2080 </varlistentry>
2081
2082 <varlistentry>
2083 <term>
2084 <literal>mdo</literal>
2085 <indexterm><primary><literal>mdo</literal></primary></indexterm>
2086 </term>
2087 <listitem><para>
2088 Stolen by: <option>-XRecursiveDo</option>
2089 </para></listitem>
2090 </varlistentry>
2091
2092 <varlistentry>
2093 <term>
2094 <literal>foreign</literal>
2095 <indexterm><primary><literal>foreign</literal></primary></indexterm>
2096 </term>
2097 <listitem><para>
2098 Stolen by: <option>-XForeignFunctionInterface</option>
2099 </para></listitem>
2100 </varlistentry>
2101
2102 <varlistentry>
2103 <term>
2104 <literal>rec</literal>,
2105 <literal>proc</literal>, <literal>-&lt;</literal>,
2106 <literal>&gt;-</literal>, <literal>-&lt;&lt;</literal>,
2107 <literal>&gt;&gt;-</literal>, and <literal>(|</literal>,
2108 <literal>|)</literal> brackets
2109 <indexterm><primary><literal>proc</literal></primary></indexterm>
2110 </term>
2111 <listitem><para>
2112 Stolen by: <option>-XArrows</option>
2113 </para></listitem>
2114 </varlistentry>
2115
2116 <varlistentry>
2117 <term>
2118 <literal>?<replaceable>varid</replaceable></literal>,
2119 <literal>%<replaceable>varid</replaceable></literal>
2120 <indexterm><primary>implicit parameters</primary></indexterm>
2121 </term>
2122 <listitem><para>
2123 Stolen by: <option>-XImplicitParams</option>
2124 </para></listitem>
2125 </varlistentry>
2126
2127 <varlistentry>
2128 <term>
2129 <literal>[|</literal>,
2130 <literal>[e|</literal>, <literal>[p|</literal>,
2131 <literal>[d|</literal>, <literal>[t|</literal>,
2132 <literal>$(</literal>,
2133 <literal>$<replaceable>varid</replaceable></literal>
2134 <indexterm><primary>Template Haskell</primary></indexterm>
2135 </term>
2136 <listitem><para>
2137 Stolen by: <option>-XTemplateHaskell</option>
2138 </para></listitem>
2139 </varlistentry>
2140
2141 <varlistentry>
2142 <term>
2143 <literal>[:<replaceable>varid</replaceable>|</literal>
2144 <indexterm><primary>quasi-quotation</primary></indexterm>
2145 </term>
2146 <listitem><para>
2147 Stolen by: <option>-XQuasiQuotes</option>
2148 </para></listitem>
2149 </varlistentry>
2150
2151 <varlistentry>
2152 <term>
2153 <replaceable>varid</replaceable>{<literal>&num;</literal>},
2154 <replaceable>char</replaceable><literal>&num;</literal>,
2155 <replaceable>string</replaceable><literal>&num;</literal>,
2156 <replaceable>integer</replaceable><literal>&num;</literal>,
2157 <replaceable>float</replaceable><literal>&num;</literal>,
2158 <replaceable>float</replaceable><literal>&num;&num;</literal>,
2159 <literal>(&num;</literal>, <literal>&num;)</literal>
2160 </term>
2161 <listitem><para>
2162 Stolen by: <option>-XMagicHash</option>
2163 </para></listitem>
2164 </varlistentry>
2165 </variablelist>
2166 </para>
2167 </sect2>
2168 </sect1>
2169
2170
2171 <!-- TYPE SYSTEM EXTENSIONS -->
2172 <sect1 id="data-type-extensions">
2173 <title>Extensions to data types and type synonyms</title>
2174
2175 <sect2 id="nullary-types">
2176 <title>Data types with no constructors</title>
2177
2178 <para>With the <option>-XEmptyDataDecls</option> flag (or equivalent LANGUAGE pragma),
2179 GHC lets you declare a data type with no constructors. For example:</para>
2180
2181 <programlisting>
2182 data S -- S :: *
2183 data T a -- T :: * -> *
2184 </programlisting>
2185
2186 <para>Syntactically, the declaration lacks the "= constrs" part. The
2187 type can be parameterised over types of any kind, but if the kind is
2188 not <literal>*</literal> then an explicit kind annotation must be used
2189 (see <xref linkend="kinding"/>).</para>
2190
2191 <para>Such data types have only one value, namely bottom.
2192 Nevertheless, they can be useful when defining "phantom types".</para>
2193 </sect2>
2194
2195 <sect2 id="datatype-contexts">
2196 <title>Data type contexts</title>
2197
2198 <para>Haskell allows datatypes to be given contexts, e.g.</para>
2199
2200 <programlisting>
2201 data Eq a => Set a = NilSet | ConsSet a (Set a)
2202 </programlisting>
2203
2204 <para>give constructors with types:</para>
2205
2206 <programlisting>
2207 NilSet :: Set a
2208 ConsSet :: Eq a => a -> Set a -> Set a
2209 </programlisting>
2210
2211 <para>This is widely considered a misfeature, and is going to be removed from
2212 the language. In GHC, it is controlled by the deprecated extension
2213 <literal>DatatypeContexts</literal>.</para>
2214 </sect2>
2215
2216 <sect2 id="infix-tycons">
2217 <title>Infix type constructors, classes, and type variables</title>
2218
2219 <para>
2220 GHC allows type constructors, classes, and type variables to be operators, and
2221 to be written infix, very much like expressions. More specifically:
2222 <itemizedlist>
2223 <listitem><para>
2224 A type constructor or class can be an operator, beginning with a colon; e.g. <literal>:*:</literal>.
2225 The lexical syntax is the same as that for data constructors.
2226 </para></listitem>
2227 <listitem><para>
2228 Data type and type-synonym declarations can be written infix, parenthesised
2229 if you want further arguments. E.g.
2230 <screen>
2231 data a :*: b = Foo a b
2232 type a :+: b = Either a b
2233 class a :=: b where ...
2234
2235 data (a :**: b) x = Baz a b x
2236 type (a :++: b) y = Either (a,b) y
2237 </screen>
2238 </para></listitem>
2239 <listitem><para>
2240 Types, and class constraints, can be written infix. For example
2241 <screen>
2242 x :: Int :*: Bool
2243 f :: (a :=: b) => a -> b
2244 </screen>
2245 </para></listitem>
2246 <listitem><para>
2247 A type variable can be an (unqualified) operator e.g. <literal>+</literal>.
2248 The lexical syntax is the same as that for variable operators, excluding "(.)",
2249 "(!)", and "(*)". In a binding position, the operator must be
2250 parenthesised. For example:
2251 <programlisting>
2252 type T (+) = Int + Int
2253 f :: T Either
2254 f = Left 3
2255
2256 liftA2 :: Arrow (~>)
2257 => (a -> b -> c) -> (e ~> a) -> (e ~> b) -> (e ~> c)
2258 liftA2 = ...
2259 </programlisting>
2260 </para></listitem>
2261 <listitem><para>
2262 Back-quotes work
2263 as for expressions, both for type constructors and type variables; e.g. <literal>Int `Either` Bool</literal>, or
2264 <literal>Int `a` Bool</literal>. Similarly, parentheses work the same; e.g. <literal>(:*:) Int Bool</literal>.
2265 </para></listitem>
2266 <listitem><para>
2267 Fixities may be declared for type constructors, or classes, just as for data constructors. However,
2268 one cannot distinguish between the two in a fixity declaration; a fixity declaration
2269 sets the fixity for a data constructor and the corresponding type constructor. For example:
2270 <screen>
2271 infixl 7 T, :*:
2272 </screen>
2273 sets the fixity for both type constructor <literal>T</literal> and data constructor <literal>T</literal>,
2274 and similarly for <literal>:*:</literal>.
2275 <literal>Int `a` Bool</literal>.
2276 </para></listitem>
2277 <listitem><para>
2278 Function arrow is <literal>infixr</literal> with fixity 0. (This might change; I'm not sure what it should be.)
2279 </para></listitem>
2280
2281 </itemizedlist>
2282 </para>
2283 </sect2>
2284
2285 <sect2 id="type-synonyms">
2286 <title>Liberalised type synonyms</title>
2287
2288 <para>
2289 Type synonyms are like macros at the type level, but Haskell 98 imposes many rules
2290 on individual synonym declarations.
2291 With the <option>-XLiberalTypeSynonyms</option> extension,
2292 GHC does validity checking on types <emphasis>only after expanding type synonyms</emphasis>.
2293 That means that GHC can be very much more liberal about type synonyms than Haskell 98.
2294
2295 <itemizedlist>
2296 <listitem> <para>You can write a <literal>forall</literal> (including overloading)
2297 in a type synonym, thus:
2298 <programlisting>
2299 type Discard a = forall b. Show b => a -> b -> (a, String)
2300
2301 f :: Discard a
2302 f x y = (x, show y)
2303
2304 g :: Discard Int -> (Int,String) -- A rank-2 type
2305 g f = f 3 True
2306 </programlisting>
2307 </para>
2308 </listitem>
2309
2310 <listitem><para>
2311 If you also use <option>-XUnboxedTuples</option>,
2312 you can write an unboxed tuple in a type synonym:
2313 <programlisting>
2314 type Pr = (# Int, Int #)
2315
2316 h :: Int -> Pr
2317 h x = (# x, x #)
2318 </programlisting>
2319 </para></listitem>
2320
2321 <listitem><para>
2322 You can apply a type synonym to a forall type:
2323 <programlisting>
2324 type Foo a = a -> a -> Bool
2325
2326 f :: Foo (forall b. b->b)
2327 </programlisting>
2328 After expanding the synonym, <literal>f</literal> has the legal (in GHC) type:
2329 <programlisting>
2330 f :: (forall b. b->b) -> (forall b. b->b) -> Bool
2331 </programlisting>
2332 </para></listitem>
2333
2334 <listitem><para>
2335 You can apply a type synonym to a partially applied type synonym:
2336 <programlisting>
2337 type Generic i o = forall x. i x -> o x
2338 type Id x = x
2339
2340 foo :: Generic Id []
2341 </programlisting>
2342 After expanding the synonym, <literal>foo</literal> has the legal (in GHC) type:
2343 <programlisting>
2344 foo :: forall x. x -> [x]
2345 </programlisting>
2346 </para></listitem>
2347
2348 </itemizedlist>
2349 </para>
2350
2351 <para>
2352 GHC currently does kind checking before expanding synonyms (though even that
2353 could be changed.)
2354 </para>
2355 <para>
2356 After expanding type synonyms, GHC does validity checking on types, looking for
2357 the following mal-formedness which isn't detected simply by kind checking:
2358 <itemizedlist>
2359 <listitem><para>
2360 Type constructor applied to a type involving for-alls.
2361 </para></listitem>
2362 <listitem><para>
2363 Unboxed tuple on left of an arrow.
2364 </para></listitem>
2365 <listitem><para>
2366 Partially-applied type synonym.
2367 </para></listitem>
2368 </itemizedlist>
2369 So, for example,
2370 this will be rejected:
2371 <programlisting>
2372 type Pr = (# Int, Int #)
2373
2374 h :: Pr -> Int
2375 h x = ...
2376 </programlisting>
2377 because GHC does not allow unboxed tuples on the left of a function arrow.
2378 </para>
2379 </sect2>
2380
2381
2382 <sect2 id="existential-quantification">
2383 <title>Existentially quantified data constructors
2384 </title>
2385
2386 <para>
2387 The idea of using existential quantification in data type declarations
2388 was suggested by Perry, and implemented in Hope+ (Nigel Perry, <emphasis>The Implementation
2389 of Practical Functional Programming Languages</emphasis>, PhD Thesis, University of
2390 London, 1991). It was later formalised by Laufer and Odersky
2391 (<emphasis>Polymorphic type inference and abstract data types</emphasis>,
2392 TOPLAS, 16(5), pp1411-1430, 1994).
2393 It's been in Lennart
2394 Augustsson's <command>hbc</command> Haskell compiler for several years, and
2395 proved very useful. Here's the idea. Consider the declaration:
2396 </para>
2397
2398 <para>
2399
2400 <programlisting>
2401 data Foo = forall a. MkFoo a (a -> Bool)
2402 | Nil
2403 </programlisting>
2404
2405 </para>
2406
2407 <para>
2408 The data type <literal>Foo</literal> has two constructors with types:
2409 </para>
2410
2411 <para>
2412
2413 <programlisting>
2414 MkFoo :: forall a. a -> (a -> Bool) -> Foo
2415 Nil :: Foo
2416 </programlisting>
2417
2418 </para>
2419
2420 <para>
2421 Notice that the type variable <literal>a</literal> in the type of <function>MkFoo</function>
2422 does not appear in the data type itself, which is plain <literal>Foo</literal>.
2423 For example, the following expression is fine:
2424 </para>
2425
2426 <para>
2427
2428 <programlisting>
2429 [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
2430 </programlisting>
2431
2432 </para>
2433
2434 <para>
2435 Here, <literal>(MkFoo 3 even)</literal> packages an integer with a function
2436 <function>even</function> that maps an integer to <literal>Bool</literal>; and <function>MkFoo 'c'
2437 isUpper</function> packages a character with a compatible function. These
2438 two things are each of type <literal>Foo</literal> and can be put in a list.
2439 </para>
2440
2441 <para>
2442 What can we do with a value of type <literal>Foo</literal>?. In particular,
2443 what happens when we pattern-match on <function>MkFoo</function>?
2444 </para>
2445
2446 <para>
2447
2448 <programlisting>
2449 f (MkFoo val fn) = ???
2450 </programlisting>
2451
2452 </para>
2453
2454 <para>
2455 Since all we know about <literal>val</literal> and <function>fn</function> is that they
2456 are compatible, the only (useful) thing we can do with them is to
2457 apply <function>fn</function> to <literal>val</literal> to get a boolean. For example:
2458 </para>
2459
2460 <para>
2461
2462 <programlisting>
2463 f :: Foo -> Bool
2464 f (MkFoo val fn) = fn val
2465 </programlisting>
2466
2467 </para>
2468
2469 <para>
2470 What this allows us to do is to package heterogeneous values
2471 together with a bunch of functions that manipulate them, and then treat
2472 that collection of packages in a uniform manner. You can express
2473 quite a bit of object-oriented-like programming this way.
2474 </para>
2475
2476 <sect3 id="existential">
2477 <title>Why existential?
2478 </title>
2479
2480 <para>
2481 What has this to do with <emphasis>existential</emphasis> quantification?
2482 Simply that <function>MkFoo</function> has the (nearly) isomorphic type
2483 </para>
2484
2485 <para>
2486
2487 <programlisting>
2488 MkFoo :: (exists a . (a, a -> Bool)) -> Foo
2489 </programlisting>
2490
2491 </para>
2492
2493 <para>
2494 But Haskell programmers can safely think of the ordinary
2495 <emphasis>universally</emphasis> quantified type given above, thereby avoiding
2496 adding a new existential quantification construct.
2497 </para>
2498
2499 </sect3>
2500
2501 <sect3 id="existential-with-context">
2502 <title>Existentials and type classes</title>
2503
2504 <para>
2505 An easy extension is to allow
2506 arbitrary contexts before the constructor. For example:
2507 </para>
2508
2509 <para>
2510
2511 <programlisting>
2512 data Baz = forall a. Eq a => Baz1 a a
2513 | forall b. Show b => Baz2 b (b -> b)
2514 </programlisting>
2515
2516 </para>
2517
2518 <para>
2519 The two constructors have the types you'd expect:
2520 </para>
2521
2522 <para>
2523
2524 <programlisting>
2525 Baz1 :: forall a. Eq a => a -> a -> Baz
2526 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
2527 </programlisting>
2528
2529 </para>
2530
2531 <para>
2532 But when pattern matching on <function>Baz1</function> the matched values can be compared
2533 for equality, and when pattern matching on <function>Baz2</function> the first matched
2534 value can be converted to a string (as well as applying the function to it).
2535 So this program is legal:
2536 </para>
2537
2538 <para>
2539
2540 <programlisting>
2541 f :: Baz -> String
2542 f (Baz1 p q) | p == q = "Yes"
2543 | otherwise = "No"
2544 f (Baz2 v fn) = show (fn v)
2545 </programlisting>
2546
2547 </para>
2548
2549 <para>
2550 Operationally, in a dictionary-passing implementation, the
2551 constructors <function>Baz1</function> and <function>Baz2</function> must store the
2552 dictionaries for <literal>Eq</literal> and <literal>Show</literal> respectively, and
2553 extract it on pattern matching.
2554 </para>
2555
2556 </sect3>
2557
2558 <sect3 id="existential-records">
2559 <title>Record Constructors</title>
2560
2561 <para>
2562 GHC allows existentials to be used with records syntax as well. For example:
2563
2564 <programlisting>
2565 data Counter a = forall self. NewCounter
2566 { _this :: self
2567 , _inc :: self -> self
2568 , _display :: self -> IO ()
2569 , tag :: a
2570 }
2571 </programlisting>
2572 Here <literal>tag</literal> is a public field, with a well-typed selector
2573 function <literal>tag :: Counter a -> a</literal>. The <literal>self</literal>
2574 type is hidden from the outside; any attempt to apply <literal>_this</literal>,
2575 <literal>_inc</literal> or <literal>_display</literal> as functions will raise a
2576 compile-time error. In other words, <emphasis>GHC defines a record selector function
2577 only for fields whose type does not mention the existentially-quantified variables</emphasis>.
2578 (This example used an underscore in the fields for which record selectors
2579 will not be defined, but that is only programming style; GHC ignores them.)
2580 </para>
2581
2582 <para>
2583 To make use of these hidden fields, we need to create some helper functions:
2584
2585 <programlisting>
2586 inc :: Counter a -> Counter a
2587 inc (NewCounter x i d t) = NewCounter
2588 { _this = i x, _inc = i, _display = d, tag = t }
2589
2590 display :: Counter a -> IO ()
2591 display NewCounter{ _this = x, _display = d } = d x
2592 </programlisting>
2593
2594 Now we can define counters with different underlying implementations:
2595
2596 <programlisting>
2597 counterA :: Counter String
2598 counterA = NewCounter
2599 { _this = 0, _inc = (1+), _display = print, tag = "A" }
2600
2601 counterB :: Counter String
2602 counterB = NewCounter
2603 { _this = "", _inc = ('#':), _display = putStrLn, tag = "B" }
2604
2605 main = do
2606 display (inc counterA) -- prints "1"
2607 display (inc (inc counterB)) -- prints "##"
2608 </programlisting>
2609
2610 Record update syntax is supported for existentials (and GADTs):
2611 <programlisting>
2612 setTag :: Counter a -> a -> Counter a
2613 setTag obj t = obj{ tag = t }
2614 </programlisting>
2615 The rule for record update is this: <emphasis>
2616 the types of the updated fields may
2617 mention only the universally-quantified type variables
2618 of the data constructor. For GADTs, the field may mention only types
2619 that appear as a simple type-variable argument in the constructor's result
2620 type</emphasis>. For example:
2621 <programlisting>
2622 data T a b where { T1 { f1::a, f2::b, f3::(b,c) } :: T a b } -- c is existential
2623 upd1 t x = t { f1=x } -- OK: upd1 :: T a b -> a' -> T a' b
2624 upd2 t x = t { f3=x } -- BAD (f3's type mentions c, which is
2625 -- existentially quantified)
2626
2627 data G a b where { G1 { g1::a, g2::c } :: G a [c] }
2628 upd3 g x = g { g1=x } -- OK: upd3 :: G a b -> c -> G c b
2629 upd4 g x = g { g2=x } -- BAD (f2's type mentions c, which is not a simple
2630 -- type-variable argument in G1's result type)
2631 </programlisting>
2632 </para>
2633
2634 </sect3>
2635
2636
2637 <sect3>
2638 <title>Restrictions</title>
2639
2640 <para>
2641 There are several restrictions on the ways in which existentially-quantified
2642 constructors can be use.
2643 </para>
2644
2645 <para>
2646
2647 <itemizedlist>
2648 <listitem>
2649
2650 <para>
2651 When pattern matching, each pattern match introduces a new,
2652 distinct, type for each existential type variable. These types cannot
2653 be unified with any other type, nor can they escape from the scope of
2654 the pattern match. For example, these fragments are incorrect:
2655
2656
2657 <programlisting>
2658 f1 (MkFoo a f) = a
2659 </programlisting>
2660
2661
2662 Here, the type bound by <function>MkFoo</function> "escapes", because <literal>a</literal>
2663 is the result of <function>f1</function>. One way to see why this is wrong is to
2664 ask what type <function>f1</function> has:
2665
2666
2667 <programlisting>
2668 f1 :: Foo -> a -- Weird!
2669 </programlisting>
2670
2671
2672 What is this "<literal>a</literal>" in the result type? Clearly we don't mean
2673 this:
2674
2675
2676 <programlisting>
2677 f1 :: forall a. Foo -> a -- Wrong!
2678 </programlisting>
2679
2680
2681 The original program is just plain wrong. Here's another sort of error
2682
2683
2684 <programlisting>
2685 f2 (Baz1 a b) (Baz1 p q) = a==q
2686 </programlisting>
2687
2688
2689 It's ok to say <literal>a==b</literal> or <literal>p==q</literal>, but
2690 <literal>a==q</literal> is wrong because it equates the two distinct types arising
2691 from the two <function>Baz1</function> constructors.
2692
2693
2694 </para>
2695 </listitem>
2696 <listitem>
2697
2698 <para>
2699 You can't pattern-match on an existentially quantified
2700 constructor in a <literal>let</literal> or <literal>where</literal> group of
2701 bindings. So this is illegal:
2702
2703
2704 <programlisting>
2705 f3 x = a==b where { Baz1 a b = x }
2706 </programlisting>
2707
2708 Instead, use a <literal>case</literal> expression:
2709
2710 <programlisting>
2711 f3 x = case x of Baz1 a b -> a==b
2712 </programlisting>
2713
2714 In general, you can only pattern-match
2715 on an existentially-quantified constructor in a <literal>case</literal> expression or
2716 in the patterns of a function definition.
2717
2718 The reason for this restriction is really an implementation one.
2719 Type-checking binding groups is already a nightmare without
2720 existentials complicating the picture. Also an existential pattern
2721 binding at the top level of a module doesn't make sense, because it's
2722 not clear how to prevent the existentially-quantified type "escaping".
2723 So for now, there's a simple-to-state restriction. We'll see how
2724 annoying it is.
2725
2726 </para>
2727 </listitem>
2728 <listitem>
2729
2730 <para>
2731 You can't use existential quantification for <literal>newtype</literal>
2732 declarations. So this is illegal:
2733
2734
2735 <programlisting>
2736 newtype T = forall a. Ord a => MkT a
2737 </programlisting>
2738
2739
2740 Reason: a value of type <literal>T</literal> must be represented as a
2741 pair of a dictionary for <literal>Ord t</literal> and a value of type
2742 <literal>t</literal>. That contradicts the idea that
2743 <literal>newtype</literal> should have no concrete representation.
2744 You can get just the same efficiency and effect by using
2745 <literal>data</literal> instead of <literal>newtype</literal>. If
2746 there is no overloading involved, then there is more of a case for
2747 allowing an existentially-quantified <literal>newtype</literal>,
2748 because the <literal>data</literal> version does carry an
2749 implementation cost, but single-field existentially quantified
2750 constructors aren't much use. So the simple restriction (no
2751 existential stuff on <literal>newtype</literal>) stands, unless there
2752 are convincing reasons to change it.
2753
2754
2755 </para>
2756 </listitem>
2757 <listitem>
2758
2759 <para>
2760 You can't use <literal>deriving</literal> to define instances of a
2761 data type with existentially quantified data constructors.
2762
2763 Reason: in most cases it would not make sense. For example:;
2764
2765 <programlisting>
2766 data T = forall a. MkT [a] deriving( Eq )
2767 </programlisting>
2768
2769 To derive <literal>Eq</literal> in the standard way we would need to have equality
2770 between the single component of two <function>MkT</function> constructors:
2771
2772 <programlisting>
2773 instance Eq T where
2774 (MkT a) == (MkT b) = ???
2775 </programlisting>
2776
2777 But <varname>a</varname> and <varname>b</varname> have distinct types, and so can't be compared.
2778 It's just about possible to imagine examples in which the derived instance
2779 would make sense, but it seems altogether simpler simply to prohibit such
2780 declarations. Define your own instances!
2781 </para>
2782 </listitem>
2783
2784 </itemizedlist>
2785
2786 </para>
2787
2788 </sect3>
2789 </sect2>
2790
2791 <!-- ====================== Generalised algebraic data types ======================= -->
2792
2793 <sect2 id="gadt-style">
2794 <title>Declaring data types with explicit constructor signatures</title>
2795
2796 <para>When the <literal>GADTSyntax</literal> extension is enabled,
2797 GHC allows you to declare an algebraic data type by
2798 giving the type signatures of constructors explicitly. For example:
2799 <programlisting>
2800 data Maybe a where
2801 Nothing :: Maybe a
2802 Just :: a -> Maybe a
2803 </programlisting>
2804 The form is called a "GADT-style declaration"
2805 because Generalised Algebraic Data Types, described in <xref linkend="gadt"/>,
2806 can only be declared using this form.</para>
2807 <para>Notice that GADT-style syntax generalises existential types (<xref linkend="existential-quantification"/>).
2808 For example, these two declarations are equivalent:
2809 <programlisting>
2810 data Foo = forall a. MkFoo a (a -> Bool)
2811 data Foo' where { MKFoo :: a -> (a->Bool) -> Foo' }
2812 </programlisting>
2813 </para>
2814 <para>Any data type that can be declared in standard Haskell-98 syntax
2815 can also be declared using GADT-style syntax.
2816 The choice is largely stylistic, but GADT-style declarations differ in one important respect:
2817 they treat class constraints on the data constructors differently.
2818 Specifically, if the constructor is given a type-class context, that
2819 context is made available by pattern matching. For example:
2820 <programlisting>
2821 data Set a where
2822 MkSet :: Eq a => [a] -> Set a
2823
2824 makeSet :: Eq a => [a] -> Set a
2825 makeSet xs = MkSet (nub xs)
2826
2827 insert :: a -> Set a -> Set a
2828 insert a (MkSet as) | a `elem` as = MkSet as
2829 | otherwise = MkSet (a:as)
2830 </programlisting>
2831 A use of <literal>MkSet</literal> as a constructor (e.g. in the definition of <literal>makeSet</literal>)
2832 gives rise to a <literal>(Eq a)</literal>
2833 constraint, as you would expect. The new feature is that pattern-matching on <literal>MkSet</literal>
2834 (as in the definition of <literal>insert</literal>) makes <emphasis>available</emphasis> an <literal>(Eq a)</literal>
2835 context. In implementation terms, the <literal>MkSet</literal> constructor has a hidden field that stores
2836 the <literal>(Eq a)</literal> dictionary that is passed to <literal>MkSet</literal>; so
2837 when pattern-matching that dictionary becomes available for the right-hand side of the match.
2838 In the example, the equality dictionary is used to satisfy the equality constraint
2839 generated by the call to <literal>elem</literal>, so that the type of
2840 <literal>insert</literal> itself has no <literal>Eq</literal> constraint.
2841 </para>
2842 <para>
2843 For example, one possible application is to reify dictionaries:
2844 <programlisting>
2845 data NumInst a where
2846 MkNumInst :: Num a => NumInst a
2847
2848 intInst :: NumInst Int
2849 intInst = MkNumInst
2850
2851 plus :: NumInst a -> a -> a -> a
2852 plus MkNumInst p q = p + q
2853 </programlisting>
2854 Here, a value of type <literal>NumInst a</literal> is equivalent
2855 to an explicit <literal>(Num a)</literal> dictionary.
2856 </para>
2857 <para>
2858 All this applies to constructors declared using the syntax of <xref linkend="existential-with-context"/>.
2859 For example, the <literal>NumInst</literal> data type above could equivalently be declared
2860 like this:
2861 <programlisting>
2862 data NumInst a
2863 = Num a => MkNumInst (NumInst a)
2864 </programlisting>
2865 Notice that, unlike the situation when declaring an existential, there is
2866 no <literal>forall</literal>, because the <literal>Num</literal> constrains the
2867 data type's universally quantified type variable <literal>a</literal>.
2868 A constructor may have both universal and existential type variables: for example,
2869 the following two declarations are equivalent:
2870 <programlisting>
2871 data T1 a
2872 = forall b. (Num a, Eq b) => MkT1 a b
2873 data T2 a where
2874 MkT2 :: (Num a, Eq b) => a -> b -> T2 a
2875 </programlisting>
2876 </para>
2877 <para>All this behaviour contrasts with Haskell 98's peculiar treatment of
2878 contexts on a data type declaration (Section 4.2.1 of the Haskell 98 Report).
2879 In Haskell 98 the definition
2880 <programlisting>
2881 data Eq a => Set' a = MkSet' [a]
2882 </programlisting>
2883 gives <literal>MkSet'</literal> the same type as <literal>MkSet</literal> above. But instead of
2884 <emphasis>making available</emphasis> an <literal>(Eq a)</literal> constraint, pattern-matching
2885 on <literal>MkSet'</literal> <emphasis>requires</emphasis> an <literal>(Eq a)</literal> constraint!
2886 GHC faithfully implements this behaviour, odd though it is. But for GADT-style declarations,
2887 GHC's behaviour is much more useful, as well as much more intuitive.
2888 </para>
2889
2890 <para>
2891 The rest of this section gives further details about GADT-style data
2892 type declarations.
2893
2894 <itemizedlist>
2895 <listitem><para>
2896 The result type of each data constructor must begin with the type constructor being defined.
2897 If the result type of all constructors
2898 has the form <literal>T a1 ... an</literal>, where <literal>a1 ... an</literal>
2899 are distinct type variables, then the data type is <emphasis>ordinary</emphasis>;
2900 otherwise is a <emphasis>generalised</emphasis> data type (<xref linkend="gadt"/>).
2901 </para></listitem>
2902
2903 <listitem><para>
2904 As with other type signatures, you can give a single signature for several data constructors.
2905 In this example we give a single signature for <literal>T1</literal> and <literal>T2</literal>:
2906 <programlisting>
2907 data T a where
2908 T1,T2 :: a -> T a
2909 T3 :: T a
2910 </programlisting>
2911 </para></listitem>
2912
2913 <listitem><para>
2914 The type signature of
2915 each constructor is independent, and is implicitly universally quantified as usual.
2916 In particular, the type variable(s) in the "<literal>data T a where</literal>" header
2917 have no scope, and different constructors may have different universally-quantified type variables:
2918 <programlisting>
2919 data T a where -- The 'a' has no scope
2920 T1,T2 :: b -> T b -- Means forall b. b -> T b
2921 T3 :: T a -- Means forall a. T a
2922 </programlisting>
2923 </para></listitem>
2924
2925 <listitem><para>
2926 A constructor signature may mention type class constraints, which can differ for
2927 different constructors. For example, this is fine:
2928 <programlisting>
2929 data T a where
2930 T1 :: Eq b => b -> b -> T b
2931 T2 :: (Show c, Ix c) => c -> [c] -> T c
2932 </programlisting>
2933 When pattern matching, these constraints are made available to discharge constraints
2934 in the body of the match. For example:
2935 <programlisting>
2936 f :: T a -> String
2937 f (T1 x y) | x==y = "yes"
2938 | otherwise = "no"
2939 f (T2 a b) = show a
2940 </programlisting>
2941 Note that <literal>f</literal> is not overloaded; the <literal>Eq</literal> constraint arising
2942 from the use of <literal>==</literal> is discharged by the pattern match on <literal>T1</literal>
2943 and similarly the <literal>Show</literal> constraint arising from the use of <literal>show</literal>.
2944 </para></listitem>
2945
2946 <listitem><para>
2947 Unlike a Haskell-98-style
2948 data type declaration, the type variable(s) in the "<literal>data Set a where</literal>" header
2949 have no scope. Indeed, one can write a kind signature instead:
2950 <programlisting>
2951 data Set :: * -> * where ...
2952 </programlisting>
2953 or even a mixture of the two:
2954 <programlisting>
2955 data Bar a :: (* -> *) -> * where ...
2956 </programlisting>
2957 The type variables (if given) may be explicitly kinded, so we could also write the header for <literal>Foo</literal>
2958 like this:
2959 <programlisting>
2960 data Bar a (b :: * -> *) where ...
2961 </programlisting>
2962 </para></listitem>
2963
2964
2965 <listitem><para>
2966 You can use strictness annotations, in the obvious places
2967 in the constructor type:
2968 <programlisting>
2969 data Term a where
2970 Lit :: !Int -> Term Int
2971 If :: Term Bool -> !(Term a) -> !(Term a) -> Term a
2972 Pair :: Term a -> Term b -> Term (a,b)
2973 </programlisting>
2974 </para></listitem>
2975
2976 <listitem><para>
2977 You can use a <literal>deriving</literal> clause on a GADT-style data type
2978 declaration. For example, these two declarations are equivalent
2979 <programlisting>
2980 data Maybe1 a where {
2981 Nothing1 :: Maybe1 a ;
2982 Just1 :: a -> Maybe1 a
2983 } deriving( Eq, Ord )
2984
2985 data Maybe2 a = Nothing2 | Just2 a
2986 deriving( Eq, Ord )
2987 </programlisting>
2988 </para></listitem>
2989
2990 <listitem><para>
2991 The type signature may have quantified type variables that do not appear
2992 in the result type:
2993 <programlisting>
2994 data Foo where
2995 MkFoo :: a -> (a->Bool) -> Foo
2996 Nil :: Foo
2997 </programlisting>
2998 Here the type variable <literal>a</literal> does not appear in the result type
2999 of either constructor.
3000 Although it is universally quantified in the type of the constructor, such
3001 a type variable is often called "existential".
3002 Indeed, the above declaration declares precisely the same type as
3003 the <literal>data Foo</literal> in <xref linkend="existential-quantification"/>.
3004 </para><para>
3005 The type may contain a class context too, of course:
3006 <programlisting>
3007 data Showable where
3008 MkShowable :: Show a => a -> Showable
3009 </programlisting>
3010 </para></listitem>
3011
3012 <listitem><para>
3013 You can use record syntax on a GADT-style data type declaration:
3014
3015 <programlisting>
3016 data Person where
3017 Adult :: { name :: String, children :: [Person] } -> Person
3018 Child :: Show a => { name :: !String, funny :: a } -> Person
3019 </programlisting>
3020 As usual, for every constructor that has a field <literal>f</literal>, the type of
3021 field <literal>f</literal> must be the same (modulo alpha conversion).
3022 The <literal>Child</literal> constructor above shows that the signature
3023 may have a context, existentially-quantified variables, and strictness annotations,
3024 just as in the non-record case. (NB: the "type" that follows the double-colon
3025 is not really a type, because of the record syntax and strictness annotations.
3026 A "type" of this form can appear only in a constructor signature.)
3027 </para></listitem>
3028
3029 <listitem><para>
3030 Record updates are allowed with GADT-style declarations,
3031 only fields that have the following property: the type of the field
3032 mentions no existential type variables.
3033 </para></listitem>
3034
3035 <listitem><para>
3036 As in the case of existentials declared using the Haskell-98-like record syntax
3037 (<xref linkend="existential-records"/>),
3038 record-selector functions are generated only for those fields that have well-typed
3039 selectors.
3040 Here is the example of that section, in GADT-style syntax:
3041 <programlisting>
3042 data Counter a where
3043 NewCounter { _this :: self
3044 , _inc :: self -> self
3045 , _display :: self -> IO ()
3046 , tag :: a
3047 }
3048 :: Counter a
3049 </programlisting>
3050 As before, only one selector function is generated here, that for <literal>tag</literal>.
3051 Nevertheless, you can still use all the field names in pattern matching and record construction.
3052 </para></listitem>
3053
3054 <listitem><para>
3055 In a GADT-style data type declaration there is no obvious way to specify that a data constructor
3056 should be infix, which makes a difference if you derive <literal>Show</literal> for the type.
3057 (Data constructors declared infix are displayed infix by the derived <literal>show</literal>.)
3058 So GHC implements the following design: a data constructor declared in a GADT-style data type
3059 declaration is displayed infix by <literal>Show</literal> iff (a) it is an operator symbol,
3060 (b) it has two arguments, (c) it has a programmer-supplied fixity declaration. For example
3061 <programlisting>
3062 infix 6 (:--:)
3063 data T a where
3064 (:--:) :: Int -> Bool -> T Int
3065 </programlisting>
3066 </para></listitem>
3067 </itemizedlist></para>
3068 </sect2>
3069
3070 <sect2 id="gadt">
3071 <title>Generalised Algebraic Data Types (GADTs)</title>
3072
3073 <para>Generalised Algebraic Data Types generalise ordinary algebraic data types
3074 by allowing constructors to have richer return types. Here is an example:
3075 <programlisting>
3076 data Term a where
3077 Lit :: Int -> Term Int
3078 Succ :: Term Int -> Term Int
3079 IsZero :: Term Int -> Term Bool
3080 If :: Term Bool -> Term a -> Term a -> Term a
3081 Pair :: Term a -> Term b -> Term (a,b)
3082 </programlisting>
3083 Notice that the return type of the constructors is not always <literal>Term a</literal>, as is the
3084 case with ordinary data types. This generality allows us to
3085 write a well-typed <literal>eval</literal> function
3086 for these <literal>Terms</literal>:
3087 <programlisting>
3088 eval :: Term a -> a
3089 eval (Lit i) = i
3090 eval (Succ t) = 1 + eval t
3091 eval (IsZero t) = eval t == 0
3092 eval (If b e1 e2) = if eval b then eval e1 else eval e2
3093 eval (Pair e1 e2) = (eval e1, eval e2)
3094 </programlisting>
3095 The key point about GADTs is that <emphasis>pattern matching causes type refinement</emphasis>.
3096 For example, in the right hand side of the equation
3097 <programlisting>
3098 eval :: Term a -> a
3099 eval (Lit i) = ...
3100 </programlisting>
3101 the type <literal>a</literal> is refined to <literal>Int</literal>. That's the whole point!
3102 A precise specification of the type rules is beyond what this user manual aspires to,
3103 but the design closely follows that described in
3104 the paper <ulink
3105 url="http://research.microsoft.com/%7Esimonpj/papers/gadt/">Simple
3106 unification-based type inference for GADTs</ulink>,
3107 (ICFP 2006).
3108 The general principle is this: <emphasis>type refinement is only carried out
3109 based on user-supplied type annotations</emphasis>.
3110 So if no type signature is supplied for <literal>eval</literal>, no type refinement happens,
3111 and lots of obscure error messages will
3112 occur. However, the refinement is quite general. For example, if we had:
3113 <programlisting>
3114 eval :: Term a -> a -> a
3115 eval (Lit i) j = i+j
3116 </programlisting>
3117 the pattern match causes the type <literal>a</literal> to be refined to <literal>Int</literal> (because of the type
3118 of the constructor <literal>Lit</literal>), and that refinement also applies to the type of <literal>j</literal>, and
3119 the result type of the <literal>case</literal> expression. Hence the addition <literal>i+j</literal> is legal.
3120 </para>
3121 <para>
3122 These and many other examples are given in papers by Hongwei Xi, and
3123 Tim Sheard. There is a longer introduction
3124 <ulink url="http://www.haskell.org/haskellwiki/GADT">on the wiki</ulink>,
3125 and Ralf Hinze's
3126 <ulink url="http://www.informatik.uni-bonn.de/~ralf/publications/With.pdf">Fun with phantom types</ulink> also has a number of examples. Note that papers
3127 may use different notation to that implemented in GHC.
3128 </para>
3129 <para>
3130 The rest of this section outlines the extensions to GHC that support GADTs. The extension is enabled with
3131 <option>-XGADTs</option>. The <option>-XGADTs</option> flag also sets <option>-XRelaxedPolyRec</option>.
3132 <itemizedlist>
3133 <listitem><para>
3134 A GADT can only be declared using GADT-style syntax (<xref linkend="gadt-style"/>);
3135 the old Haskell-98 syntax for data declarations always declares an ordinary data type.
3136 The result type of each constructor must begin with the type constructor being defined,
3137 but for a GADT the arguments to the type constructor can be arbitrary monotypes.
3138 For example, in the <literal>Term</literal> data
3139 type above, the type of each constructor must end with <literal>Term ty</literal>, but
3140 the <literal>ty</literal> need not be a type variable (e.g. the <literal>Lit</literal>
3141 constructor).
3142 </para></listitem>
3143
3144 <listitem><para>
3145 It is permitted to declare an ordinary algebraic data type using GADT-style syntax.
3146 What makes a GADT into a GADT is not the syntax, but rather the presence of data constructors
3147 whose result type is not just <literal>T a b</literal>.
3148 </para></listitem>
3149
3150 <listitem><para>
3151 You cannot use a <literal>deriving</literal> clause for a GADT; only for
3152 an ordinary data type.
3153 </para></listitem>
3154
3155 <listitem><para>
3156 As mentioned in <xref linkend="gadt-style"/>, record syntax is supported.
3157 For example:
3158 <programlisting>
3159 data Term a where
3160 Lit { val :: Int } :: Term Int
3161 Succ { num :: Term Int } :: Term Int
3162 Pred { num :: Term Int } :: Term Int
3163 IsZero { arg :: Term Int } :: Term Bool
3164 Pair { arg1 :: Term a
3165 , arg2 :: Term b
3166 } :: Term (a,b)
3167 If { cnd :: Term Bool
3168 , tru :: Term a
3169 , fls :: Term a
3170 } :: Term a
3171 </programlisting>
3172 However, for GADTs there is the following additional constraint:
3173 every constructor that has a field <literal>f</literal> must have
3174 the same result type (modulo alpha conversion)
3175 Hence, in the above example, we cannot merge the <literal>num</literal>
3176 and <literal>arg</literal> fields above into a
3177 single name. Although their field types are both <literal>Term Int</literal>,
3178 their selector functions actually have different types:
3179
3180 <programlisting>
3181 num :: Term Int -> Term Int
3182 arg :: Term Bool -> Term Int
3183 </programlisting>
3184 </para></listitem>
3185
3186 <listitem><para>
3187 When pattern-matching against data constructors drawn from a GADT,
3188 for example in a <literal>case</literal> expression, the following rules apply:
3189 <itemizedlist>
3190 <listitem><para>The type of the scrutinee must be rigid.</para></listitem>
3191 <listitem><para>The type of the entire <literal>case</literal> expression must be rigid.</para></listitem>
3192 <listitem><para>The type of any free variable mentioned in any of
3193 the <literal>case</literal> alternatives must be rigid.</para></listitem>
3194 </itemizedlist>
3195 A type is "rigid" if it is completely known to the compiler at its binding site. The easiest
3196 way to ensure that a variable a rigid type is to give it a type signature.
3197 For more precise details see <ulink url="http://research.microsoft.com/%7Esimonpj/papers/gadt">
3198 Simple unification-based type inference for GADTs
3199 </ulink>. The criteria implemented by GHC are given in the Appendix.
3200
3201 </para></listitem>
3202
3203 </itemizedlist>
3204 </para>
3205
3206 </sect2>
3207 </sect1>
3208
3209 <!-- ====================== End of Generalised algebraic data types ======================= -->
3210
3211 <sect1 id="deriving">
3212 <title>Extensions to the "deriving" mechanism</title>
3213
3214 <sect2 id="deriving-inferred">
3215 <title>Inferred context for deriving clauses</title>
3216
3217 <para>
3218 The Haskell Report is vague about exactly when a <literal>deriving</literal> clause is
3219 legal. For example:
3220 <programlisting>
3221 data T0 f a = MkT0 a deriving( Eq )
3222 data T1 f a = MkT1 (f a) deriving( Eq )
3223 data T2 f a = MkT2 (f (f a)) deriving( Eq )
3224 </programlisting>
3225 The natural generated <literal>Eq</literal> code would result in these instance declarations:
3226 <programlisting>
3227 instance Eq a => Eq (T0 f a) where ...
3228 instance Eq (f a) => Eq (T1 f a) where ...
3229 instance Eq (f (f a)) => Eq (T2 f a) where ...
3230 </programlisting>
3231 The first of these is obviously fine. The second is still fine, although less obviously.
3232 The third is not Haskell 98, and risks losing termination of instances.
3233 </para>
3234 <para>
3235 GHC takes a conservative position: it accepts the first two, but not the third. The rule is this:
3236 each constraint in the inferred instance context must consist only of type variables,
3237 with no repetitions.
3238 </para>
3239 <para>
3240 This rule is applied regardless of flags. If you want a more exotic context, you can write
3241 it yourself, using the <link linkend="stand-alone-deriving">standalone deriving mechanism</link>.
3242 </para>
3243 </sect2>
3244
3245 <sect2 id="stand-alone-deriving">
3246 <title>Stand-alone deriving declarations</title>
3247
3248 <para>
3249 GHC now allows stand-alone <literal>deriving</literal> declarations, enabled by <literal>-XStandaloneDeriving</literal>:
3250 <programlisting>
3251 data Foo a = Bar a | Baz String
3252
3253 deriving instance Eq a => Eq (Foo a)
3254 </programlisting>
3255 The syntax is identical to that of an ordinary instance declaration apart from (a) the keyword
3256 <literal>deriving</literal>, and (b) the absence of the <literal>where</literal> part.
3257 Note the following points:
3258 <itemizedlist>
3259 <listitem><para>
3260 You must supply an explicit context (in the example the context is <literal>(Eq a)</literal>),
3261 exactly as you would in an ordinary instance declaration.
3262 (In contrast, in a <literal>deriving</literal> clause
3263 attached to a data type declaration, the context is inferred.)
3264 </para></listitem>
3265
3266 <listitem><para>
3267 A <literal>deriving instance</literal> declaration
3268 must obey the same rules concerning form and termination as ordinary instance declarations,
3269 controlled by the same flags; see <xref linkend="instance-decls"/>.
3270 </para></listitem>
3271
3272 <listitem><para>
3273 Unlike a <literal>deriving</literal>
3274 declaration attached to a <literal>data</literal> declaration, the instance can be more specific
3275 than the data type (assuming you also use
3276 <literal>-XFlexibleInstances</literal>, <xref linkend="instance-rules"/>). Consider
3277 for example
3278 <programlisting>
3279 data Foo a = Bar a | Baz String
3280
3281 deriving instance Eq a => Eq (Foo [a])
3282 deriving instance Eq a => Eq (Foo (Maybe a))
3283 </programlisting>
3284 This will generate a derived instance for <literal>(Foo [a])</literal> and <literal>(Foo (Maybe a))</literal>,
3285 but other types such as <literal>(Foo (Int,Bool))</literal> will not be an instance of <literal>Eq</literal>.
3286 </para></listitem>
3287
3288 <listitem><para>
3289 Unlike a <literal>deriving</literal>
3290 declaration attached to a <literal>data</literal> declaration,
3291 GHC does not restrict the form of the data type. Instead, GHC simply generates the appropriate
3292 boilerplate code for the specified class, and typechecks it. If there is a type error, it is
3293 your problem. (GHC will show you the offending code if it has a type error.)
3294 The merit of this is that you can derive instances for GADTs and other exotic
3295 data types, providing only that the boilerplate code does indeed typecheck. For example:
3296 <programlisting>
3297 data T a where
3298 T1 :: T Int
3299 T2 :: T Bool
3300
3301 deriving instance Show (T a)
3302 </programlisting>
3303 In this example, you cannot say <literal>... deriving( Show )</literal> on the
3304 data type declaration for <literal>T</literal>,
3305 because <literal>T</literal> is a GADT, but you <emphasis>can</emphasis> generate
3306 the instance declaration using stand-alone deriving.
3307 </para>
3308 </listitem>
3309
3310 <listitem>
3311 <para>The stand-alone syntax is generalised for newtypes in exactly the same
3312 way that ordinary <literal>deriving</literal> clauses are generalised (<xref linkend="newtype-deriving"/>).
3313 For example:
3314 <programlisting>
3315 newtype Foo a = MkFoo (State Int a)
3316
3317 deriving instance MonadState Int Foo
3318 </programlisting>
3319 GHC always treats the <emphasis>last</emphasis> parameter of the instance
3320 (<literal>Foo</literal> in this example) as the type whose instance is being derived.
3321 </para></listitem>
3322 </itemizedlist></para>
3323
3324 </sect2>
3325
3326
3327 <sect2 id="deriving-typeable">
3328 <title>Deriving clause for extra classes (<literal>Typeable</literal>, <literal>Data</literal>, etc)</title>
3329
3330 <para>
3331 Haskell 98 allows the programmer to add "<literal>deriving( Eq, Ord )</literal>" to a data type
3332 declaration, to generate a standard instance declaration for classes specified in the <literal>deriving</literal> clause.
3333 In Haskell 98, the only classes that may appear in the <literal>deriving</literal> clause are the standard
3334 classes <literal>Eq</literal>, <literal>Ord</literal>,
3335 <literal>Enum</literal>, <literal>Ix</literal>, <literal>Bounded</literal>, <literal>Read</literal>, and <literal>Show</literal>.
3336 </para>
3337 <para>
3338 GHC extends this list with several more classes that may be automatically derived:
3339 <itemizedlist>
3340 <listitem><para> With <option>-XDeriveDataTypeable</option>, you can derive instances of the classes
3341 <literal>Typeable</literal>, and <literal>Data</literal>, defined in the library
3342 modules <literal>Data.Typeable</literal> and <literal>Data.Generics</literal> respectively.
3343 </para>
3344 <para>An instance of <literal>Typeable</literal> can only be derived if the
3345 data type has seven or fewer type parameters, all of kind <literal>*</literal>.
3346 The reason for this is that the <literal>Typeable</literal> class is derived using the scheme
3347 described in
3348 <ulink url="http://research.microsoft.com/%7Esimonpj/papers/hmap/gmap2.ps">
3349 Scrap More Boilerplate: Reflection, Zips, and Generalised Casts
3350 </ulink>.
3351 (Section 7.4 of the paper describes the multiple <literal>Typeable</literal> classes that
3352 are used, and only <literal>Typeable1</literal> up to
3353 <literal>Typeable7</literal> are provided in the library.)
3354 In other cases, there is nothing to stop the programmer writing a <literal>TypeableX</literal>
3355 class, whose kind suits that of the data type constructor, and
3356 then writing the data type instance by hand.
3357 </para>
3358 </listitem>
3359
3360 <listitem><para> With <option>-XDeriveGeneric</option>, you can derive
3361 instances of the classes <literal>Generic</literal> and
3362 <literal>Generic1</literal>, defined in <literal>GHC.Generics</literal>.
3363 You can use these to define generic functions,
3364 as described in <xref linkend="generic-programming"/>.
3365 </para></listitem>
3366
3367 <listitem><para> With <option>-XDeriveFunctor</option>, you can derive instances of
3368 the class <literal>Functor</literal>,
3369 defined in <literal>GHC.Base</literal>.
3370 </para></listitem>
3371
3372 <listitem><para> With <option>-XDeriveFoldable</option>, you can derive instances of
3373 the class <literal>Foldable</literal>,
3374 defined in <literal>Data.Foldable</literal>.
3375 </para></listitem>
3376
3377 <listitem><para> With <option>-XDeriveTraversable</option>, you can derive instances of
3378 the class <literal>Traversable</literal>,
3379 defined in <literal>Data.Traversable</literal>.
3380 </para></listitem>
3381 </itemizedlist>
3382 In each case the appropriate class must be in scope before it
3383 can be mentioned in the <literal>deriving</literal> clause.
3384 </para>
3385 </sect2>
3386
3387 <sect2 id="newtype-deriving">
3388 <title>Generalised derived instances for newtypes</title>
3389
3390 <para>
3391 When you define an abstract type using <literal>newtype</literal>, you may want
3392 the new type to inherit some instances from its representation. In
3393 Haskell 98, you can inherit instances of <literal>Eq</literal>, <literal>Ord</literal>,
3394 <literal>Enum</literal> and <literal>Bounded</literal> by deriving them, but for any
3395 other classes you have to write an explicit instance declaration. For
3396 example, if you define
3397
3398 <programlisting>
3399 newtype Dollars = Dollars Int
3400 </programlisting>
3401
3402 and you want to use arithmetic on <literal>Dollars</literal>, you have to
3403 explicitly define an instance of <literal>Num</literal>:
3404
3405 <programlisting>
3406 instance Num Dollars where
3407 Dollars a + Dollars b = Dollars (a+b)
3408 ...
3409 </programlisting>
3410 All the instance does is apply and remove the <literal>newtype</literal>
3411 constructor. It is particularly galling that, since the constructor
3412 doesn't appear at run-time, this instance declaration defines a
3413 dictionary which is <emphasis>wholly equivalent</emphasis> to the <literal>Int</literal>
3414 dictionary, only slower!
3415 </para>
3416
3417
3418 <sect3> <title> Generalising the deriving clause </title>
3419 <para>
3420 GHC now permits such instances to be derived instead,
3421 using the flag <option>-XGeneralizedNewtypeDeriving</option>,
3422 so one can write
3423 <programlisting>
3424 newtype Dollars = Dollars Int deriving (Eq,Show,Num)
3425 </programlisting>
3426
3427 and the implementation uses the <emphasis>same</emphasis> <literal>Num</literal> dictionary
3428 for <literal>Dollars</literal> as for <literal>Int</literal>. Notionally, the compiler
3429 derives an instance declaration of the form
3430
3431 <programlisting>
3432 instance Num Int => Num Dollars
3433 </programlisting>
3434
3435 which just adds or removes the <literal>newtype</literal> constructor according to the type.
3436 </para>
3437 <para>
3438
3439 We can also derive instances of constructor classes in a similar
3440 way. For example, suppose we have implemented state and failure monad
3441 transformers, such that
3442
3443 <programlisting>
3444 instance Monad m => Monad (State s m)
3445 instance Monad m => Monad (Failure m)
3446 </programlisting>
3447 In Haskell 98, we can define a parsing monad by
3448 <programlisting>
3449 type Parser tok m a = State [tok] (Failure m) a
3450 </programlisting>
3451
3452 which is automatically a monad thanks to the instance declarations
3453 above. With the extension, we can make the parser type abstract,
3454 without needing to write an instance of class <literal>Monad</literal>, via
3455
3456 <programlisting>
3457 newtype Parser tok m a = Parser (State [tok] (Failure m) a)
3458 deriving Monad
3459 </programlisting>
3460 In this case the derived instance declaration is of the form
3461 <programlisting>
3462 instance Monad (State [tok] (Failure m)) => Monad (Parser tok m)
3463 </programlisting>
3464
3465 Notice that, since <literal>Monad</literal> is a constructor class, the
3466 instance is a <emphasis>partial application</emphasis> of the new type, not the
3467 entire left hand side. We can imagine that the type declaration is
3468 "eta-converted" to generate the context of the instance
3469 declaration.
3470 </para>
3471 <para>
3472
3473 We can even derive instances of multi-parameter classes, provided the
3474 newtype is the last class parameter. In this case, a ``partial
3475 application'' of the class appears in the <literal>deriving</literal>
3476 clause. For example, given the class
3477
3478 <programlisting>
3479 class StateMonad s m | m -> s where ...
3480 instance Monad m => StateMonad s (State s m) where ...
3481 </programlisting>
3482 then we can derive an instance of <literal>StateMonad</literal> for <literal>Parser</literal>s by
3483 <programlisting>
3484 newtype Parser tok m a = Parser (State [tok] (Failure m) a)
3485 deriving (Monad, StateMonad [tok])
3486 </programlisting>
3487
3488 The derived instance is obtained by completing the application of the
3489 class to the new type:
3490
3491 <programlisting>
3492 instance StateMonad [tok] (State [tok] (Failure m)) =>
3493 StateMonad [tok] (Parser tok m)
3494 </programlisting>
3495 </para>
3496 <para>
3497
3498 As a result of this extension, all derived instances in newtype
3499 declarations are treated uniformly (and implemented just by reusing
3500 the dictionary for the representation type), <emphasis>except</emphasis>
3501 <literal>Show</literal> and <literal>Read</literal>, which really behave differently for
3502 the newtype and its representation.
3503 </para>
3504 </sect3>
3505
3506 <sect3> <title> A more precise specification </title>
3507 <para>
3508 Derived instance declarations are constructed as follows. Consider the
3509 declaration (after expansion of any type synonyms)
3510
3511 <programlisting>
3512 newtype T v1...vn = T' (t vk+1...vn) deriving (c1...cm)
3513 </programlisting>
3514
3515 where
3516 <itemizedlist>
3517 <listitem><para>
3518 The <literal>ci</literal> are partial applications of
3519 classes of the form <literal>C t1'...tj'</literal>, where the arity of <literal>C</literal>
3520 is exactly <literal>j+1</literal>. That is, <literal>C</literal> lacks exactly one type argument.
3521 </para></listitem>
3522 <listitem><para>
3523 The <literal>k</literal> is chosen so that <literal>ci (T v1...vk)</literal> is well-kinded.
3524 </para></listitem>
3525 <listitem><para>
3526 The type <literal>t</literal> is an arbitrary type.
3527 </para></listitem>
3528 <listitem><para>
3529 The type variables <literal>vk+1...vn</literal> do not occur in <literal>t</literal>,
3530 nor in the <literal>ci</literal>, and
3531 </para></listitem>
3532 <listitem><para>
3533 None of the <literal>ci</literal> is <literal>Read</literal>, <literal>Show</literal>,
3534 <literal>Typeable</literal>, or <literal>Data</literal>. These classes
3535 should not "look through" the type or its constructor. You can still
3536 derive these classes for a newtype, but it happens in the usual way, not
3537 via this new mechanism.
3538 </para></listitem>
3539 </itemizedlist>
3540 Then, for each <literal>ci</literal>, the derived instance
3541 declaration is:
3542 <programlisting>
3543 instance ci t => ci (T v1...vk)
3544 </programlisting>
3545 As an example which does <emphasis>not</emphasis> work, consider
3546 <programlisting>
3547 newtype NonMonad m s = NonMonad (State s m s) deriving Monad
3548 </programlisting>
3549 Here we cannot derive the instance
3550 <programlisting>
3551 instance Monad (State s m) => Monad (NonMonad m)
3552 </programlisting>
3553
3554 because the type variable <literal>s</literal> occurs in <literal>State s m</literal>,
3555 and so cannot be "eta-converted" away. It is a good thing that this
3556 <literal>deriving</literal> clause is rejected, because <literal>NonMonad m</literal> is
3557 not, in fact, a monad --- for the same reason. Try defining
3558 <literal>>>=</literal> with the correct type: you won't be able to.
3559 </para>
3560 <para>
3561
3562 Notice also that the <emphasis>order</emphasis> of class parameters becomes
3563 important, since we can only derive instances for the last one. If the
3564 <literal>StateMonad</literal> class above were instead defined as
3565
3566 <programlisting>
3567 class StateMonad m s | m -> s where ...
3568 </programlisting>
3569
3570 then we would not have been able to derive an instance for the
3571 <literal>Parser</literal> type above. We hypothesise that multi-parameter
3572 classes usually have one "main" parameter for which deriving new
3573 instances is most interesting.
3574 </para>
3575 <para>Lastly, all of this applies only for classes other than
3576 <literal>Read</literal>, <literal>Show</literal>, <literal>Typeable</literal>,
3577 and <literal>Data</literal>, for which the built-in derivation applies (section
3578 4.3.3. of the Haskell Report).
3579 (For the standard classes <literal>Eq</literal>, <literal>Ord</literal>,
3580 <literal>Ix</literal>, and <literal>Bounded</literal> it is immaterial whether
3581 the standard method is used or the one described here.)
3582 </para>
3583 </sect3>
3584 </sect2>
3585 </sect1>
3586
3587
3588 <!-- TYPE SYSTEM EXTENSIONS -->
3589 <sect1 id="type-class-extensions">
3590 <title>Class and instances declarations</title>
3591
3592 <sect2 id="multi-param-type-classes">
3593 <title>Class declarations</title>
3594
3595 <para>
3596 This section, and the next one, documents GHC's type-class extensions.
3597 There's lots of background in the paper <ulink
3598 url="http://research.microsoft.com/~simonpj/Papers/type-class-design-space/">Type
3599 classes: exploring the design space</ulink> (Simon Peyton Jones, Mark
3600 Jones, Erik Meijer).
3601 </para>
3602
3603 <sect3>
3604 <title>Multi-parameter type classes</title>
3605 <para>
3606 Multi-parameter type classes are permitted, with flag <option>-XMultiParamTypeClasses</option>.
3607 For example:
3608
3609
3610 <programlisting>
3611 class Collection c a where
3612 union :: c a -> c a -> c a
3613 ...etc.
3614 </programlisting>
3615
3616 </para>
3617 </sect3>
3618
3619 <sect3 id="superclass-rules">
3620 <title>The superclasses of a class declaration</title>
3621
3622 <para>
3623 In Haskell 98 the context of a class declaration (which introduces superclasses)
3624 must be simple; that is, each predicate must consist of a class applied to
3625 type variables. The flag <option>-XFlexibleContexts</option>
3626 (<xref linkend="flexible-contexts"/>)
3627 lifts this restriction,
3628 so that the only restriction on the context in a class declaration is
3629 that the class hierarchy must be acyclic. So these class declarations are OK:
3630
3631
3632 <programlisting>
3633 class Functor (m k) => FiniteMap m k where
3634 ...
3635
3636 class (Monad m, Monad (t m)) => Transform t m where
3637 lift :: m a -> (t m) a
3638 </programlisting>
3639
3640
3641 </para>
3642 <para>
3643 As in Haskell 98, The class hierarchy must be acyclic. However, the definition
3644 of "acyclic" involves only the superclass relationships. For example,
3645 this is OK:
3646
3647
3648 <programlisting>
3649 class C a where {
3650 op :: D b => a -> b -> b
3651 }
3652
3653 class C a => D a where { ... }
3654 </programlisting>
3655
3656
3657 Here, <literal>C</literal> is a superclass of <literal>D</literal>, but it's OK for a
3658 class operation <literal>op</literal> of <literal>C</literal> to mention <literal>D</literal>. (It
3659 would not be OK for <literal>D</literal> to be a superclass of <literal>C</literal>.)
3660 </para>
3661 <para>
3662 With the extension that adds a <link linkend="constraint-kind">kind of constraints</link>,
3663 you can write more exotic superclass definitions. The superclass cycle check is even more
3664 liberal in these case. For example, this is OK:
3665
3666 <programlisting>
3667 class A cls c where
3668 meth :: cls c => c -> c
3669
3670 class A B c => B c where
3671 </programlisting>
3672
3673 A superclass context for a class <literal>C</literal> is allowed if, after expanding
3674 type synonyms to their right-hand-sides, and uses of classes (other than <literal>C</literal>)
3675 to their superclasses, <literal>C</literal> does not occur syntactically in the context.
3676 </para>
3677 </sect3>
3678
3679
3680
3681
3682 <sect3 id="class-method-types">
3683 <title>Class method types</title>
3684
3685 <para>
3686 Haskell 98 prohibits class method types to mention constraints on the
3687 class type variable, thus:
3688 <programlisting>
3689 class Seq s a where
3690 fromList :: [a] -> s a
3691 elem :: Eq a => a -> s a -> Bool
3692 </programlisting>
3693 The type of <literal>elem</literal> is illegal in Haskell 98, because it
3694 contains the constraint <literal>Eq a</literal>, constrains only the
3695 class type variable (in this case <literal>a</literal>).
3696 GHC lifts this restriction (flag <option>-XConstrainedClassMethods</option>).
3697 </para>
3698
3699
3700 </sect3>
3701
3702
3703 <sect3 id="class-default-signatures">
3704 <title>Default method signatures</title>
3705
3706 <para>
3707 Haskell 98 allows you to define a default implementation when declaring a class:
3708 <programlisting>
3709 class Enum a where
3710 enum :: [a]
3711 enum = []
3712 </programlisting>
3713 The type of the <literal>enum</literal> method is <literal>[a]</literal>, and
3714 this is also the type of the default method. You can lift this restriction
3715 and give another type to the default method using the flag
3716 <option>-XDefaultSignatures</option>. For instance, if you have written a
3717 generic implementation of enumeration in a class <literal>GEnum</literal>
3718 with method <literal>genum</literal> in terms of <literal>GHC.Generics</literal>,
3719 you can specify a default method that uses that generic implementation:
3720 <programlisting>
3721 class Enum a where
3722 enum :: [a]
3723 default enum :: (Generic a, GEnum (Rep a)) => [a]
3724 enum = map to genum
3725 </programlisting>
3726 We reuse the keyword <literal>default</literal> to signal that a signature
3727 applies to the default method only; when defining instances of the
3728 <literal>Enum</literal> class, the original type <literal>[a]</literal> of
3729 <literal>enum</literal> still applies. When giving an empty instance, however,
3730 the default implementation <literal>map to genum</literal> is filled-in,
3731 and type-checked with the type
3732 <literal>(Generic a, GEnum (Rep a)) => [a]</literal>.
3733 </para>
3734
3735 <para>
3736 We use default signatures to simplify generic programming in GHC
3737 (<xref linkend="generic-programming"/>).
3738 </para>
3739
3740
3741 </sect3>
3742 </sect2>
3743
3744 <sect2 id="functional-dependencies">
3745 <title>Functional dependencies
3746 </title>
3747
3748 <para> Functional dependencies are implemented as described by Mark Jones
3749 in &ldquo;<ulink url="http://citeseer.ist.psu.edu/jones00type.html">Type Classes with Functional Dependencies</ulink>&rdquo;, Mark P. Jones,
3750 In Proceedings of the 9th European Symposium on Programming,
3751 ESOP 2000, Berlin, Germany, March 2000, Springer-Verlag LNCS 1782,
3752 .
3753 </para>
3754 <para>
3755 Functional dependencies are introduced by a vertical bar in the syntax of a
3756 class declaration; e.g.
3757 <programlisting>
3758 class (Monad m) => MonadState s m | m -> s where ...
3759
3760 class Foo a b c | a b -> c where ...
3761 </programlisting>
3762 There should be more documentation, but there isn't (yet). Yell if you need it.
3763 </para>
3764
3765 <sect3><title>Rules for functional dependencies </title>
3766 <para>
3767 In a class declaration, all of the class type variables must be reachable (in the sense
3768 mentioned in <xref linkend="flexible-contexts"/>)
3769 from the free variables of each method type.
3770 For example:
3771
3772 <programlisting>
3773 class Coll s a where
3774 empty :: s
3775 insert :: s -> a -> s
3776 </programlisting>
3777
3778 is not OK, because the type of <literal>empty</literal> doesn't mention
3779 <literal>a</literal>. Functional dependencies can make the type variable
3780 reachable:
3781 <programlisting>
3782 class Coll s a | s -> a where
3783 empty :: s
3784 insert :: s -> a -> s
3785 </programlisting>
3786
3787 Alternatively <literal>Coll</literal> might be rewritten
3788
3789 <programlisting>
3790 class Coll s a where
3791 empty :: s a
3792 insert :: s a -> a -> s a
3793 </programlisting>
3794
3795
3796 which makes the connection between the type of a collection of
3797 <literal>a</literal>'s (namely <literal>(s a)</literal>) and the element type <literal>a</literal>.
3798 Occasionally this really doesn't work, in which case you can split the
3799 class like this:
3800
3801
3802 <programlisting>
3803 class CollE s where
3804 empty :: s
3805
3806 class CollE s => Coll s a where
3807 insert :: s -> a -> s
3808 </programlisting>
3809 </para>
3810 </sect3>
3811
3812
3813 <sect3>
3814 <title>Background on functional dependencies</title>
3815
3816 <para>The following description of the motivation and use of functional dependencies is taken
3817 from the Hugs user manual, reproduced here (with minor changes) by kind
3818 permission of Mark Jones.
3819 </para>
3820 <para>
3821 Consider the following class, intended as part of a
3822 library for collection types:
3823 <programlisting>
3824 class Collects e ce where
3825 empty :: ce
3826 insert :: e -> ce -> ce
3827 member :: e -> ce -> Bool
3828 </programlisting>
3829 The type variable e used here represents the element type, while ce is the type
3830 of the container itself. Within this framework, we might want to define
3831 instances of this class for lists or characteristic functions (both of which
3832 can be used to represent collections of any equality type), bit sets (which can
3833 be used to represent collections of characters), or hash tables (which can be
3834 used to represent any collection whose elements have a hash function). Omitting
3835 standard implementation details, this would lead to the following declarations:
3836 <programlisting>
3837 instance Eq e => Collects e [e] where ...
3838 instance Eq e => Collects e (e -> Bool) where ...
3839 instance Collects Char BitSet where ...
3840 instance (Hashable e, Collects a ce)
3841 => Collects e (Array Int ce) where ...
3842 </programlisting>
3843 All this looks quite promising; we have a class and a range of interesting
3844 implementations. Unfortunately, there are some serious problems with the class
3845 declaration. First, the empty function has an ambiguous type:
3846 <programlisting>
3847 empty :: Collects e ce => ce
3848 </programlisting>
3849 By "ambiguous" we mean that there is a type variable e that appears on the left
3850 of the <literal>=&gt;</literal> symbol, but not on the right. The problem with
3851 this is that, according to the theoretical foundations of Haskell overloading,
3852 we cannot guarantee a well-defined semantics for any term with an ambiguous
3853 type.
3854 </para>
3855 <para>
3856 We can sidestep this specific problem by removing the empty member from the
3857 class declaration. However, although the remaining members, insert and member,
3858 do not have ambiguous types, we still run into problems when we try to use
3859 them. For example, consider the following two functions:
3860 <programlisting>
3861 f x y = insert x . insert y
3862 g = f True 'a'
3863 </programlisting>
3864 for which GHC infers the following types:
3865 <programlisting>
3866 f :: (Collects a c, Collects b c) => a -> b -> c -> c
3867 g :: (Collects Bool c, Collects Char c) => c -> c
3868 </programlisting>
3869 Notice that the type for f allows the two parameters x and y to be assigned
3870 different types, even though it attempts to insert each of the two values, one
3871 after the other, into the same collection. If we're trying to model collections
3872 that contain only one type of value, then this is clearly an inaccurate
3873 type. Worse still, the definition for g is accepted, without causing a type
3874 error. As a result, the error in this code will not be flagged at the point
3875 where it appears. Instead, it will show up only when we try to use g, which
3876 might even be in a different module.
3877 </para>
3878
3879 <sect4><title>An attempt to use constructor classes</title>
3880
3881 <para>
3882 Faced with the problems described above, some Haskell programmers might be
3883 tempted to use something like the following version of the class declaration:
3884 <programlisting>
3885 class Collects e c where
3886 empty :: c e
3887 insert :: e -> c e -> c e
3888 member :: e -> c e -> Bool
3889 </programlisting>
3890 The key difference here is that we abstract over the type constructor c that is
3891 used to form the collection type c e, and not over that collection type itself,
3892 represented by ce in the original class declaration. This avoids the immediate
3893 problems that we mentioned above: empty has type <literal>Collects e c => c
3894 e</literal>, which is not ambiguous.
3895 </para>
3896 <para>
3897 The function f from the previous section has a more accurate type:
3898 <programlisting>
3899 f :: (Collects e c) => e -> e -> c e -> c e
3900 </programlisting>
3901 The function g from the previous section is now rejected with a type error as
3902 we would hope because the type of f does not allow the two arguments to have
3903 different types.
3904 This, then, is an example of a multiple parameter class that does actually work
3905 quite well in practice, without ambiguity problems.
3906 There is, however, a catch. This version of the Collects class is nowhere near
3907 as general as the original class seemed to be: only one of the four instances
3908 for <literal>Collects</literal>
3909 given above can be used with this version of Collects because only one of
3910 them---the instance for lists---has a collection type that can be written in
3911 the form c e, for some type constructor c, and element type e.
3912 </para>
3913 </sect4>
3914
3915 <sect4><title>Adding functional dependencies</title>
3916
3917 <para>
3918 To get a more useful version of the Collects class, Hugs provides a mechanism
3919 that allows programmers to specify dependencies between the parameters of a
3920 multiple parameter class (For readers with an interest in theoretical
3921 foundations and previous work: The use of dependency information can be seen
3922 both as a generalization of the proposal for `parametric type classes' that was
3923 put forward by Chen, Hudak, and Odersky, or as a special case of Mark Jones's
3924 later framework for "improvement" of qualified types. The
3925 underlying ideas are also discussed in a more theoretical and abstract setting
3926 in a manuscript [implparam], where they are identified as one point in a
3927 general design space for systems of implicit parameterization.).
3928
3929 To start with an abstract example, consider a declaration such as:
3930 <programlisting>
3931 class C a b where ...
3932 </programlisting>
3933 which tells us simply that C can be thought of as a binary relation on types
3934 (or type constructors, depending on the kinds of a and b). Extra clauses can be
3935 included in the definition of classes to add information about dependencies
3936 between parameters, as in the following examples:
3937 <programlisting>
3938 class D a b | a -> b where ...
3939 class E a b | a -> b, b -> a where ...
3940 </programlisting>
3941 The notation <literal>a -&gt; b</literal> used here between the | and where
3942 symbols --- not to be
3943 confused with a function type --- indicates that the a parameter uniquely
3944 determines the b parameter, and might be read as "a determines b." Thus D is
3945 not just a relation, but actually a (partial) function. Similarly, from the two
3946 dependencies that are included in the definition of E, we can see that E
3947 represents a (partial) one-one mapping between types.
3948 </para>
3949 <para>
3950 More generally, dependencies take the form <literal>x1 ... xn -&gt; y1 ... ym</literal>,
3951 where x1, ..., xn, and y1, ..., yn are type variables with n&gt;0 and
3952 m&gt;=0, meaning that the y parameters are uniquely determined by the x
3953 parameters. Spaces can be used as separators if more than one variable appears
3954 on any single side of a dependency, as in <literal>t -&gt; a b</literal>. Note that a class may be
3955 annotated with multiple dependencies using commas as separators, as in the
3956 definition of E above. Some dependencies that we can write in this notation are
3957 redundant, and will be rejected because they don't serve any useful
3958 purpose, and may instead indicate an error in the program. Examples of
3959 dependencies like this include <literal>a -&gt; a </literal>,
3960 <literal>a -&gt; a a </literal>,
3961 <literal>a -&gt; </literal>, etc. There can also be
3962 some redundancy if multiple dependencies are given, as in
3963 <literal>a-&gt;b</literal>,
3964 <literal>b-&gt;c </literal>, <literal>a-&gt;c </literal>, and
3965 in which some subset implies the remaining dependencies. Examples like this are
3966 not treated as errors. Note that dependencies appear only in class
3967 declarations, and not in any other part of the language. In particular, the
3968 syntax for instance declarations, class constraints, and types is completely
3969 unchanged.
3970 </para>
3971 <para>
3972 By including dependencies in a class declaration, we provide a mechanism for
3973 the programmer to specify each multiple parameter class more precisely. The
3974 compiler, on the other hand, is responsible for ensuring that the set of
3975 instances that are in scope at any given point in the program is consistent
3976 with any declared dependencies. For example, the following pair of instance
3977 declarations cannot appear together in the same scope because they violate the
3978 dependency for D, even though either one on its own would be acceptable:
3979 <programlisting>
3980 instance D Bool Int where ...
3981 instance D Bool Char where ...
3982 </programlisting>
3983 Note also that the following declaration is not allowed, even by itself:
3984 <programlisting>
3985 instance D [a] b where ...
3986 </programlisting>
3987 The problem here is that this instance would allow one particular choice of [a]
3988 to be associated with more than one choice for b, which contradicts the
3989 dependency specified in the definition of D. More generally, this means that,
3990 in any instance of the form:
3991 <programlisting>
3992 instance D t s where ...
3993 </programlisting>
3994 for some particular types t and s, the only variables that can appear in s are
3995 the ones that appear in t, and hence, if the type t is known, then s will be
3996 uniquely determined.
3997 </para>
3998 <para>
3999 The benefit of including dependency information is that it allows us to define
4000 more general multiple parameter classes, without ambiguity problems, and with
4001 the benefit of more accurate types. To illustrate this, we return to the
4002 collection class example, and annotate the original definition of <literal>Collects</literal>
4003 with a simple dependency:
4004 <programlisting>
4005 class Collects e ce | ce -> e where
4006 empty :: ce
4007 insert :: e -> ce -> ce
4008 member :: e -> ce -> Bool
4009 </programlisting>
4010 The dependency <literal>ce -&gt; e</literal> here specifies that the type e of elements is uniquely
4011 determined by the type of the collection ce. Note that both parameters of
4012 Collects are of kind *; there are no constructor classes here. Note too that
4013 all of the instances of Collects that we gave earlier can be used
4014 together with this new definition.
4015 </para>
4016 <para>
4017 What about the ambiguity problems that we encountered with the original
4018 definition? The empty function still has type Collects e ce => ce, but it is no
4019 longer necessary to regard that as an ambiguous type: Although the variable e
4020 does not appear on the right of the => symbol, the dependency for class
4021 Collects tells us that it is uniquely determined by ce, which does appear on
4022 the right of the => symbol. Hence the context in which empty is used can still
4023 give enough information to determine types for both ce and e, without
4024 ambiguity. More generally, we need only regard a type as ambiguous if it
4025 contains a variable on the left of the => that is not uniquely determined
4026 (either directly or indirectly) by the variables on the right.
4027 </para>
4028 <para>
4029 Dependencies also help to produce more accurate types for user defined
4030 functions, and hence to provide earlier detection of errors, and less cluttered
4031 types for programmers to work with. Recall the previous definition for a
4032 function f:
4033 <programlisting>
4034 f x y = insert x y = insert x . insert y
4035 </programlisting>
4036 for which we originally obtained a type:
4037 <programlisting>
4038 f :: (Collects a c, Collects b c) => a -> b -> c -> c
4039 </programlisting>
4040 Given the dependency information that we have for Collects, however, we can
4041 deduce that a and b must be equal because they both appear as the second
4042 parameter in a Collects constraint with the same first parameter c. Hence we
4043 can infer a shorter and more accurate type for f:
4044 <programlisting>
4045 f :: (Collects a c) => a -> a -> c -> c
4046 </programlisting>
4047 In a similar way, the earlier definition of g will now be flagged as a type error.
4048 </para>
4049 <para>
4050 Although we have given only a few examples here, it should be clear that the
4051 addition of dependency information can help to make multiple parameter classes
4052 more useful in practice, avoiding ambiguity problems, and allowing more general
4053 sets of instance declarations.
4054 </para>
4055 </sect4>
4056 </sect3>
4057 </sect2>
4058
4059 <sect2 id="instance-decls">
4060 <title>Instance declarations</title>
4061
4062 <para>An instance declaration has the form
4063 <screen>
4064 instance ( <replaceable>assertion</replaceable><subscript>1</subscript>, ..., <replaceable>assertion</replaceable><subscript>n</subscript>) =&gt; <replaceable>class</replaceable> <replaceable>type</replaceable><subscript>1</subscript> ... <replaceable>type</replaceable><subscript>m</subscript> where ...
4065 </screen>
4066 The part before the "<literal>=&gt;</literal>" is the
4067 <emphasis>context</emphasis>, while the part after the
4068 "<literal>=&gt;</literal>" is the <emphasis>head</emphasis> of the instance declaration.
4069 </para>
4070
4071 <sect3 id="instance-resolution">
4072 <title>Instance resolution</title>
4073
4074 <para>
4075 When GHC tries to resolve, say, the constraint <literal>C Int Bool</literal>,
4076 it tries to match every instance declaration against the
4077 constraint,
4078 by instantiating the head of the instance declaration. Consider
4079 these declarations:
4080 <programlisting>
4081 instance context1 => C Int a where ... -- (A)
4082 instance context2 => C a Bool where ... -- (B)
4083 </programlisting>
4084 GHC's default behaviour is that <emphasis>exactly one instance must match the
4085 constraint it is trying to resolve</emphasis>.
4086 For example, the constraint <literal>C Int Bool</literal> matches instances (A) and (B),
4087 and hence would be rejected; while <literal>C Int Char</literal> matches only (A)
4088 and hence (A) is chosen.</para>
4089
4090 <para>
4091 Notice that
4092 <itemizedlist>
4093 <listitem><para>
4094 When matching, GHC takes
4095 no account of the context of the instance declaration
4096 (<literal>context1</literal> etc).
4097 </para></listitem>
4098 <listitem><para>
4099 It is fine for there to be a <emphasis>potential</emphasis> of overlap (by
4100 including both declarations (A) and (B), say); an error is only reported if a
4101 particular constraint matche