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