glasgow_exts.sgml 142 KB
Newer Older
1
2
3
<para>
<indexterm><primary>language, GHC</primary></indexterm>
<indexterm><primary>extensions, GHC</primary></indexterm>
rrt's avatar
rrt committed
4
As with all known Haskell systems, GHC implements some extensions to
5
6
7
the language.  To use them, you'll need to give a <option>-fglasgow-exts</option>
<indexterm><primary>-fglasgow-exts option</primary></indexterm> option.
</para>
rrt's avatar
rrt committed
8

9
<para>
rrt's avatar
rrt committed
10
11
12
Virtually all of the Glasgow extensions serve to give you access to
the underlying facilities with which we implement Haskell.  Thus, you
can get at the Raw Iron, if you are willing to write some non-standard
rrt's avatar
rrt committed
13
code at a more primitive level.  You need not be &ldquo;stuck&rdquo; on
rrt's avatar
rrt committed
14
performance because of the implementation costs of Haskell's
rrt's avatar
rrt committed
15
&ldquo;high-level&rdquo; features&mdash;you can always code &ldquo;under&rdquo; them.  In an extreme case, you can write all your time-critical code in C, and then just glue it together with Haskell!
16
</para>
rrt's avatar
rrt committed
17

18
<para>
rrt's avatar
rrt committed
19
Before you get too carried away working at the lowest level (e.g.,
20
sloshing <literal>MutableByteArray&num;</literal>s around your
21
program), you may wish to check if there are libraries that provide a
22
23
24
&ldquo;Haskellised veneer&rdquo; over the features you want.  The
separate libraries documentation describes all the libraries that come
with GHC.
25
</para>
rrt's avatar
rrt committed
26

27
<!-- LANGUAGE OPTIONS -->
28
29
  <sect1 id="options-language">
    <title>Language options</title>
30

31
32
33
34
35
36
    <indexterm><primary>language</primary><secondary>option</secondary>
    </indexterm>
    <indexterm><primary>options</primary><secondary>language</secondary>
    </indexterm>
    <indexterm><primary>extensions</primary><secondary>options controlling</secondary>
    </indexterm>
37

38
39
    <para> These flags control what variation of the language are
    permitted.  Leaving out all of them gives you standard Haskell
40
    98.</para>
41

42
    <variablelist>
43

44
45
46
47
48
49
50
51
52
53
      <varlistentry>
	<term><option>-fglasgow-exts</option>:</term>
	<indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
	<listitem>
	  <para>This simultaneously enables all of the extensions to
          Haskell 98 described in <xref
          linkend="ghc-language-features">, except where otherwise
          noted. </para>
	</listitem>
      </varlistentry>
54

chak's avatar
chak committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
      <varlistentry>
	<term><option>-ffi</option> and <option>-fffi</option>:</term>
	<indexterm><primary><option>-ffi</option></primary></indexterm>
	<indexterm><primary><option>-fffi</option></primary></indexterm>
	<listitem>
	  <para>This option enables the language extension defined in the
	  Haskell 98 Foreign Function Interface Addendum plus deprecated
	  syntax of previous versions of the FFI for backwards
	  compatibility.</para> 
	</listitem>
      </varlistentry>

      <varlistentry>
	<term><option>-fwith</option>:</term>
	<indexterm><primary><option>-fwith</option></primary></indexterm>
	<listitem>
	  <para>This option enables the deprecated <literal>with</literal>
	  keyword for implicit parameters; it is merely provided for backwards
	  compatibility.
          It is independent of the <option>-fglasgow-exts</option>
          flag. </para>
	</listitem>
      </varlistentry>

79
80
81
82
83
      <varlistentry>
	<term><option>-fno-monomorphism-restriction</option>:</term>
	<indexterm><primary><option>-fno-monomorphism-restriction</option></primary></indexterm>
	<listitem>
	  <para> Switch off the Haskell 98 monomorphism restriction.
84
          Independent of the <option>-fglasgow-exts</option>
85
86
87
          flag. </para>
	</listitem>
      </varlistentry>
88

89
90
91
      <varlistentry>
	<term><option>-fallow-overlapping-instances</option></term>
	<term><option>-fallow-undecidable-instances</option></term>
92
	<term><option>-fallow-incoherent-instances</option></term>
93
94
95
96
97
	<term><option>-fcontext-stack</option></term>
	<indexterm><primary><option>-fallow-overlapping-instances</option></primary></indexterm>
	<indexterm><primary><option>-fallow-undecidable-instances</option></primary></indexterm>
	<indexterm><primary><option>-fcontext-stack</option></primary></indexterm>
	<listitem>
98
	  <para> See <xref LinkEnd="instance-decls">.  Only relevant
99
100
101
          if you also use <option>-fglasgow-exts</option>.</para>
	</listitem>
      </varlistentry>
102

103
104
105
106
      <varlistentry>
	<term><option>-finline-phase</option></term>
	<indexterm><primary><option>-finline-phase</option></primary></indexterm>
	<listitem>
107
108
	  <para>See <xref LinkEnd="rewrite-rules">.  Only relevant if
          you also use <option>-fglasgow-exts</option>.</para>
109
110
	</listitem>
      </varlistentry>
111

112
113
114
115
      <varlistentry>
	<term><option>-fgenerics</option></term>
	<indexterm><primary><option>-fgenerics</option></primary></indexterm>
	<listitem>
116
117
	  <para>See <xref LinkEnd="generic-classes">.  Independent of
          <option>-fglasgow-exts</option>.</para>
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
	</listitem>
      </varlistentry>

	<varlistentry>
	  <term><option>-fno-implicit-prelude</option></term>
	  <listitem>
	    <para><indexterm><primary>-fno-implicit-prelude
            option</primary></indexterm> GHC normally imports
            <filename>Prelude.hi</filename> files for you.  If you'd
            rather it didn't, then give it a
            <option>-fno-implicit-prelude</option> option.  The idea
            is that you can then import a Prelude of your own.  (But
            don't call it <literal>Prelude</literal>; the Haskell
            module namespace is flat, and you must not conflict with
            any Prelude module.)</para>

134
	    <para>Even though you have not imported the Prelude, most of
135
136
137
138
139
140
141
142
            the built-in syntax still refers to the built-in Haskell
            Prelude types and values, as specified by the Haskell
            Report.  For example, the type <literal>[Int]</literal>
            still means <literal>Prelude.[] Int</literal>; tuples
            continue to refer to the standard Prelude tuples; the
            translation for list comprehensions continues to use
            <literal>Prelude.map</literal> etc.</para>

143
144
145
	    <para>However, <option>-fno-implicit-prelude</option> does
	    change the handling of certain built-in syntax: see
	    <xref LinkEnd="rebindable-syntax">.</para>
146

147
148
149
150
	  </listitem>
	</varlistentry>

    </variablelist>
151
  </sect1>
152

153
<!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS -->
154
<!--    included from primitives.sgml  -->
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<!-- &primitives; -->
<sect1 id="primitives">
  <title>Unboxed types and primitive operations</title>

<para>GHC is built on a raft of primitive data types and operations.
While you really can use this stuff to write fast code,
  we generally find it a lot less painful, and more satisfying in the
  long run, to use higher-level language features and libraries.  With
  any luck, the code you write will be optimised to the efficient
  unboxed version in any case.  And if it isn't, we'd like to know
  about it.</para>

<para>We do not currently have good, up-to-date documentation about the
primitives, perhaps because they are mainly intended for internal use.
There used to be a long section about them here in the User Guide, but it
became out of date, and wrong information is worse than none.</para>

<para>The Real Truth about what primitive types there are, and what operations
work over those types, is held in the file
<filename>fptools/ghc/compiler/prelude/primops.txt</filename>.
This file is used directly to generate GHC's primitive-operation definitions, so
it is always correct!  It is also intended for processing into text.</para>

<para> Indeed,
the result of such processing is part of the description of the 
 <ulink
      url="http://haskell.cs.yale.edu/ghc/docs/papers/core.ps.gz">External
	 Core language</ulink>.
So that document is a good place to look for a type-set version.
We would be very happy if someone wanted to volunteer to produce an SGML
back end to the program that processes <filename>primops.txt</filename> so that
we could include the results here in the User Guide.</para>

<para>What follows here is a brief summary of some main points.</para>
  
<sect2 id="glasgow-unboxed">
<title>Unboxed types
</title>

<para>
<indexterm><primary>Unboxed types (Glasgow extension)</primary></indexterm>
</para>

<para>Most types in GHC are <firstterm>boxed</firstterm>, which means
that values of that type are represented by a pointer to a heap
object.  The representation of a Haskell <literal>Int</literal>, for
example, is a two-word heap object.  An <firstterm>unboxed</firstterm>
type, however, is represented by the value itself, no pointers or heap
allocation are involved.
</para>

<para>
Unboxed types correspond to the &ldquo;raw machine&rdquo; types you
would use in C: <literal>Int&num;</literal> (long int),
<literal>Double&num;</literal> (double), <literal>Addr&num;</literal>
(void *), etc.  The <emphasis>primitive operations</emphasis>
(PrimOps) on these types are what you might expect; e.g.,
<literal>(+&num;)</literal> is addition on
<literal>Int&num;</literal>s, and is the machine-addition that we all
know and love&mdash;usually one instruction.
</para>

<para>
Primitive (unboxed) types cannot be defined in Haskell, and are
therefore built into the language and compiler.  Primitive types are
always unlifted; that is, a value of a primitive type cannot be
bottom.  We use the convention that primitive types, values, and
operations have a <literal>&num;</literal> suffix.
</para>

<para>
Primitive values are often represented by a simple bit-pattern, such
as <literal>Int&num;</literal>, <literal>Float&num;</literal>,
<literal>Double&num;</literal>.  But this is not necessarily the case:
a primitive value might be represented by a pointer to a
heap-allocated object.  Examples include
<literal>Array&num;</literal>, the type of primitive arrays.  A
primitive array is heap-allocated because it is too big a value to fit
in a register, and would be too expensive to copy around; in a sense,
it is accidental that it is represented by a pointer.  If a pointer
represents a primitive value, then it really does point to that value:
no unevaluated thunks, no indirections&hellip;nothing can be at the
other end of the pointer than the primitive value.
</para>

<para>
There are some restrictions on the use of primitive types, the main
one being that you can't pass a primitive value to a polymorphic
function or store one in a polymorphic data type.  This rules out
things like <literal>[Int&num;]</literal> (i.e. lists of primitive
integers).  The reason for this restriction is that polymorphic
arguments and constructor fields are assumed to be pointers: if an
unboxed integer is stored in one of these, the garbage collector would
attempt to follow it, leading to unpredictable space leaks.  Or a
<function>seq</function> operation on the polymorphic component may
attempt to dereference the pointer, with disastrous results.  Even
worse, the unboxed value might be larger than a pointer
(<literal>Double&num;</literal> for instance).
</para>

<para>
Nevertheless, A numerically-intensive program using unboxed types can
go a <emphasis>lot</emphasis> faster than its &ldquo;standard&rdquo;
counterpart&mdash;we saw a threefold speedup on one example.
</para>

</sect2>

<sect2 id="unboxed-tuples">
<title>Unboxed Tuples
</title>

<para>
Unboxed tuples aren't really exported by <literal>GHC.Exts</literal>,
they're available by default with <option>-fglasgow-exts</option>.  An
unboxed tuple looks like this:
</para>

<para>

<programlisting>
(# e_1, ..., e_n #)
</programlisting>

</para>

<para>
where <literal>e&lowbar;1..e&lowbar;n</literal> are expressions of any
type (primitive or non-primitive).  The type of an unboxed tuple looks
the same.
</para>

<para>
Unboxed tuples are used for functions that need to return multiple
values, but they avoid the heap allocation normally associated with
using fully-fledged tuples.  When an unboxed tuple is returned, the
components are put directly into registers or on the stack; the
unboxed tuple itself does not have a composite representation.  Many
of the primitive operations listed in this section return unboxed
tuples.
</para>

<para>
There are some pretty stringent restrictions on the use of unboxed tuples:
</para>

<para>

<itemizedlist>
<listitem>

<para>
 Unboxed tuple types are subject to the same restrictions as
other unboxed types; i.e. they may not be stored in polymorphic data
structures or passed to polymorphic functions.

</para>
</listitem>
<listitem>

<para>
 Unboxed tuples may only be constructed as the direct result of
a function, and may only be deconstructed with a <literal>case</literal> expression.
eg. the following are valid:


<programlisting>
f x y = (# x+1, y-1 #)
g x = case f x x of { (# a, b #) -&#62; a + b }
</programlisting>


but the following are invalid:


<programlisting>
f x y = g (# x, y #)
g (# x, y #) = x + y
</programlisting>


</para>
</listitem>
<listitem>

<para>
 No variable can have an unboxed tuple type.  This is illegal:


<programlisting>
f :: (# Int, Int #) -&#62; (# Int, Int #)
f x = x
</programlisting>


because <literal>x</literal> has an unboxed tuple type.

</para>
</listitem>

</itemizedlist>

</para>

<para>
Note: we may relax some of these restrictions in the future.
</para>

<para>
The <literal>IO</literal> and <literal>ST</literal> monads use unboxed
tuples to avoid unnecessary allocation during sequences of operations.
</para>

</sect2>
</sect1>

rrt's avatar
rrt committed
371

372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
<!-- ====================== SYNTACTIC EXTENSIONS =======================  -->

<sect1 id="syntax-extns">
<title>Syntactic extensions</title>
 
    <!-- ====================== HIERARCHICAL MODULES =======================  -->

    <sect2 id="hierarchical-modules">
      <title>Hierarchical Modules</title>

      <para>GHC supports a small extension to the syntax of module
      names: a module name is allowed to contain a dot
      <literal>&lsquo;.&rsquo;</literal>.  This is also known as the
      &ldquo;hierarchical module namespace&rdquo; extension, because
      it extends the normally flat Haskell module namespace into a
      more flexible hierarchy of modules.</para>

      <para>This extension has very little impact on the language
      itself; modules names are <emphasis>always</emphasis> fully
      qualified, so you can just think of the fully qualified module
      name as <quote>the module name</quote>.  In particular, this
      means that the full module name must be given after the
      <literal>module</literal> keyword at the beginning of the
      module; for example, the module <literal>A.B.C</literal> must
      begin</para>

<programlisting>module A.B.C</programlisting>


      <para>It is a common strategy to use the <literal>as</literal>
      keyword to save some typing when using qualified names with
      hierarchical modules.  For example:</para>

<programlisting>
import qualified Control.Monad.ST.Strict as ST
</programlisting>

      <para>Hierarchical modules have an impact on the way that GHC
      searches for files.  For a description, see <xref
      linkend="finding-hierarchical-modules">.</para>

      <para>GHC comes with a large collection of libraries arranged
      hierarchically; see the accompanying library documentation.
      There is an ongoing project to create and maintain a stable set
      of <quote>core</quote> libraries used by several Haskell
      compilers, and the libraries that GHC comes with represent the
      current status of that project.  For more details, see <ulink
      url="http://www.haskell.org/~simonmar/libraries/libraries.html">Haskell
      Libraries</ulink>.</para>

    </sect2>

    <!-- ====================== PATTERN GUARDS =======================  -->

<sect2 id="pattern-guards">
<title>Pattern guards</title>

<para>
<indexterm><primary>Pattern guards (Glasgow extension)</primary></indexterm>
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.)
</para>

<para>
Suppose we have an abstract data type of finite maps, with a
lookup operation:

<programlisting>
lookup :: FiniteMap -> Int -> Maybe Int
</programlisting>

The lookup returns <function>Nothing</function> if the supplied key is not in the domain of the mapping, and <function>(Just v)</function> otherwise,
where <VarName>v</VarName> is the value that the key maps to.  Now consider the following definition:
</para>

<programlisting>
clunky env var1 var2 | ok1 && ok2 = val1 + val2
| otherwise  = var1 + var2
where
  m1 = lookup env var1
  m2 = lookup env var2
  ok1 = maybeToBool m1
  ok2 = maybeToBool m2
  val1 = expectJust m1
  val2 = expectJust m2
</programlisting>

<para>
The auxiliary functions are 
</para>

<programlisting>
maybeToBool :: Maybe a -&gt; Bool
maybeToBool (Just x) = True
maybeToBool Nothing  = False

expectJust :: Maybe a -&gt; a
expectJust (Just x) = x
expectJust Nothing  = error "Unexpected Nothing"
</programlisting>

<para>
What is <function>clunky</function> doing? The guard <literal>ok1 &&
ok2</literal> checks that both lookups succeed, using
<function>maybeToBool</function> to convert the <function>Maybe</function>
types to booleans. The (lazily evaluated) <function>expectJust</function>
calls extract the values from the results of the lookups, and binds the
returned values to <VarName>val1</VarName> and <VarName>val2</VarName>
respectively.  If either lookup fails, then clunky takes the
<literal>otherwise</literal> case and returns the sum of its arguments.
</para>

<para>
This is certainly legal Haskell, but it is a tremendously verbose and
un-obvious way to achieve the desired effect.  Arguably, a more direct way
to write clunky would be to use case expressions:
</para>

<programlisting>
clunky env var1 var1 = case lookup env var1 of
  Nothing -&gt; fail
  Just val1 -&gt; case lookup env var2 of
    Nothing -&gt; fail
    Just val2 -&gt; val1 + val2
where
  fail = val1 + val2
</programlisting>

<para>
This is a bit shorter, but hardly better.  Of course, we can rewrite any set
of pattern-matching, guarded equations as case expressions; that is
precisely what the compiler does when compiling equations! The reason that
Haskell provides guarded equations is because they allow us to write down
the cases we want to consider, one at a time, independently of each other. 
This structure is hidden in the case version.  Two of the right-hand sides
are really the same (<function>fail</function>), and the whole expression
tends to become more and more indented. 
</para>

<para>
Here is how I would write clunky:
</para>

<programlisting>
clunky env var1 var1
  | Just val1 &lt;- lookup env var1
  , Just val2 &lt;- lookup env var2
  = val1 + val2
...other equations for clunky...
</programlisting>

<para>
The semantics should be clear enough.  The qualifers are matched in order. 
For a <literal>&lt;-</literal> qualifier, which I call a pattern guard, the
right hand side is evaluated and matched against the pattern on the left. 
If the match fails then the whole guard fails and the next equation is
tried.  If it succeeds, then the appropriate binding takes place, and the
next qualifier is matched, in the augmented environment.  Unlike list
comprehensions, however, the type of the expression to the right of the
<literal>&lt;-</literal> is the same as the type of the pattern to its
left.  The bindings introduced by pattern guards scope over all the
remaining guard qualifiers, and over the right hand side of the equation.
</para>

<para>
Just as with list comprehensions, boolean expressions can be freely mixed
with among the pattern guards.  For example:
</para>

<programlisting>
f x | [y] <- x
    , y > 3
    , Just z <- h y
    = ...
</programlisting>

<para>
Haskell's current guards therefore emerge as a special case, in which the
qualifier list has just one element, a boolean expression.
</para>
</sect2>

    <!-- ===================== Recursive do-notation ===================  -->

<sect2 id="mdo-notation">
<title>The recursive do-notation
</title>

<para> The recursive do-notation (also known as mdo-notation) is implemented as described in
"A recursive do for Haskell",
Levent Erkok, John Launchbury",
Haskell Workshop 2002, pages: 29-37. Pittsburgh, Pennsylvania. 
</para>
<para>
The do-notation of Haskell does not allow <emphasis>recursive bindings</emphasis>,
that is, the variables bound in a do-expression are visible only in the textually following 
code block. Compare this to a let-expression, where bound variables are visible in the entire binding
group. It turns out that several applications can benefit from recursive bindings in
the do-notation, and this extension provides the necessary syntactic support.
</para>
<para>
Here is a simple (yet contrived) example:
</para>
<programlisting>
575
576
import Control.Monad.Fix

577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
justOnes = mdo xs <- Just (1:xs)
               return xs
</programlisting>
<para>
As you can guess <literal>justOnes</literal> will evaluate to <literal>Just [1,1,1,...</literal>.
</para>

<para>
The Control.Monad.Fix library introduces the <literal>MonadFix</literal> class. It's definition is:
</para>
<programlisting>
class Monad m => MonadFix m where
   mfix :: (a -> m a) -> m a
</programlisting>
<para>
The function <literal>mfix</literal>
dictates how the required recursion operation should be performed. If recursive bindings are required for a monad,
then that monad must be declared an instance of the <literal>MonadFix</literal> class.
For details, see the above mentioned reference.
</para>
<para>
598
599
600
The following instances of <literal>MonadFix</literal> are automatically provided: List, Maybe, IO. 
Furthermore, the Control.Monad.ST and Control.Monad.ST.Lazy modules provide the instances of the MonadFix class 
for Haskell's internal state monad (strict and lazy, respectively).
601
602
603
604
605
606
607
608
609
610
</para>
<para>
There are three important points in using the recursive-do notation:
<itemizedlist>
<listitem><para>
The recursive version of the do-notation uses the keyword <literal>mdo</literal> (rather
than <literal>do</literal>).
</para></listitem>

<listitem><para>
611
612
613
614
You should <literal>import Control.Monad.Fix</literal>.
(Note: Strictly speaking, this import is required only when you need to refer to the name
<literal>MonadFix</literal> in your program, but the import is always safe, and the programmers
are encouraged to always import this module when using the mdo-notation.)
615
616
617
618
619
620
621
622
623
</para></listitem>

<listitem><para>
As with other extensions, ghc should be given the flag <literal>-fglasgow-exts</literal>
</para></listitem>
</itemizedlist>
</para>

<para>
624
625
The web page: <ulink url="http://www.cse.ogi.edu/PacSoft/projects/rmb">http://www.cse.ogi.edu/PacSoft/projects/rmb</ulink>
contains up to date information on recursive monadic bindings.
626
627
628
</para>

<para>
629
630
631
632
Historical note: The old implementation of the mdo-notation (and most
of the existing documents) used the name
<literal>MonadRec</literal> for the class and the corresponding library.
This name is not supported by GHC.
633
634
</para>

635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
</sect2>


<sect2> <title> Infix type constructors </title>

<para>GHC supports infix type constructors, much as it supports infix data constructors.  For example:
<programlisting>
  infixl 5 :+:

  data a :+: b = Inl a | Inr b

  f :: a `Either` b -> a :+: b
  f (Left x) = Inl x
</programlisting>
</para>
<para>The lexical 
syntax of an infix type constructor is just like that of an infix data constructor: either
it's an operator beginning with ":", or it is an ordinary (alphabetic) type constructor enclosed in
back-quotes.</para>

<para>
When you give a fixity declaration, the fixity applies to both the data constructor and the
type constructor with the specified name.  You cannot give different fixities to the type constructor T
and the data constructor T.
</para>


662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
</sect2>

   <!-- ===================== PARALLEL LIST COMPREHENSIONS ===================  -->

  <sect2 id="parallel-list-comprehensions">
    <title>Parallel List Comprehensions</title>
    <indexterm><primary>list comprehensions</primary><secondary>parallel</secondary>
    </indexterm>
    <indexterm><primary>parallel list comprehensions</primary>
    </indexterm>

    <para>Parallel list comprehensions are a natural extension to list
    comprehensions.  List comprehensions can be thought of as a nice
    syntax for writing maps and filters.  Parallel comprehensions
    extend this to include the zipWith family.</para>

    <para>A parallel list comprehension has multiple independent
    branches of qualifier lists, each separated by a `|' symbol.  For
    example, the following zips together two lists:</para>

<programlisting>
   [ (x, y) | x <- xs | y <- ys ] 
</programlisting>

    <para>The behavior of parallel list comprehensions follows that of
    zip, in that the resulting list will have the same length as the
    shortest branch.</para>

    <para>We can define parallel list comprehensions by translation to
    regular comprehensions.  Here's the basic idea:</para>

    <para>Given a parallel comprehension of the form: </para>

<programlisting>
   [ e | p1 <- e11, p2 <- e12, ... 
       | q1 <- e21, q2 <- e22, ... 
       ... 
   ] 
</programlisting>

    <para>This will be translated to: </para>

<programlisting>
   [ e | ((p1,p2), (q1,q2), ...) <- zipN [(p1,p2) | p1 <- e11, p2 <- e12, ...] 
                                         [(q1,q2) | q1 <- e21, q2 <- e22, ...] 
                                         ... 
   ] 
</programlisting>

    <para>where `zipN' is the appropriate zip for the given number of
    branches.</para>

  </sect2>

<sect2 id="rebindable-syntax">
<title>Rebindable syntax</title>


      <para>GHC allows most kinds of built-in syntax to be rebound by
      the user, to facilitate replacing the <literal>Prelude</literal>
      with a home-grown version, for example.</para>

            <para>You may want to define your own numeric class
            hierarchy.  It completely defeats that purpose if the
            literal "1" means "<literal>Prelude.fromInteger
            1</literal>", which is what the Haskell Report specifies.
            So the <option>-fno-implicit-prelude</option> flag causes
            the following pieces of built-in syntax to refer to
            <emphasis>whatever is in scope</emphasis>, not the Prelude
            versions:</para>

	    <itemizedlist>
	      <listitem>
		<para>Integer and fractional literals mean
                "<literal>fromInteger 1</literal>" and
                "<literal>fromRational 3.2</literal>", not the
                Prelude-qualified versions; both in expressions and in
                patterns. </para>
		<para>However, the standard Prelude <literal>Eq</literal> class
		is still used for the equality test necessary for literal patterns.</para>
	      </listitem>

	      <listitem>
		<para>Negation (e.g. "<literal>- (f x)</literal>")
		means "<literal>negate (f x)</literal>" (not
		<literal>Prelude.negate</literal>).</para>
	      </listitem>

	      <listitem>
		<para>In an n+k pattern, the standard Prelude
                <literal>Ord</literal> class is still used for comparison,
                but the necessary subtraction uses whatever
                "<literal>(-)</literal>" is in scope (not
                "<literal>Prelude.(-)</literal>").</para>
	      </listitem>

	      <listitem>
	  <para>"Do" notation is translated using whatever
	      functions <literal>(>>=)</literal>,
	      <literal>(>>)</literal>, <literal>fail</literal>, and
	      <literal>return</literal>, are in scope (not the Prelude
	      versions).  List comprehensions, and parallel array
	      comprehensions, are unaffected.  </para></listitem>
	    </itemizedlist>

	     <para>Be warned: this is an experimental facility, with fewer checks than
	     usual.  In particular, it is essential that the functions GHC finds in scope
	     must have the appropriate types, namely:
	     <screen>
	        fromInteger  :: forall a. (...) => Integer  -> a
		fromRational :: forall a. (...) => Rational -> a
		negate       :: forall a. (...) => a -> a
		(-)          :: forall a. (...) => a -> a -> a
		(>>=)	     :: forall m a. (...) => m a -> (a -> m b) -> m b
		(>>)	     :: forall m a. (...) => m a -> m b -> m b
		return	     :: forall m a. (...) => a      -> m a
		fail	     :: forall m a. (...) => String -> m a
	     </screen>
	     (The (...) part can be any context including the empty context; that part 
	     is up to you.)
	     If the functions don't have the right type, very peculiar things may 
	     happen.  Use <literal>-dcore-lint</literal> to
	     typecheck the desugared program.  If Core Lint is happy you should be all right.</para>

</sect2>
</sect1>

rrt's avatar
rrt committed
789

790
791
792
<!-- TYPE SYSTEM EXTENSIONS -->
<sect1 id="type-extensions">
<title>Type system extensions</title>
rrt's avatar
rrt committed
793

794
<sect2 id="nullary-types">
795
796
<title>Data types with no constructors</title>

797
<para>With the <option>-fglasgow-exts</option> flag, GHC lets you declare
798
a data type with no constructors.  For example:</para>
799

800
801
802
803
<programlisting>
  data S      -- S :: *
  data T a    -- T :: * -> *
</programlisting>
804

805
<para>Syntactically, the declaration lacks the "= constrs" part.  The 
806
807
808
type can be parameterised over types of any kind, but if the kind is
not <literal>*</literal> then an explicit kind annotation must be used
(see <xref linkend="sec-kinding">).</para>
809
810
811

<para>Such data types have only one value, namely bottom.
Nevertheless, they can be useful when defining "phantom types".</para>
812
</sect2>
813

814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
<sect2 id="infix-tycons">
<title>Infix type constructors</title>

<para>
GHC allows type constructors to be operators, and to be written infix, very much 
like expressions.  More specifically:
<itemizedlist>
<listitem><para>
  A type constructor can be an operator, beginning with a colon; e.g. <literal>:*:</literal>.
  The lexical syntax is the same as that for data constructors.
  </para></listitem>
<listitem><para>
  Types can be written infix.  For example <literal>Int :*: Bool</literal>.  
  </para></listitem>
<listitem><para>
  Back-quotes work
  as for expressions, both for type constructors and type variables;  e.g. <literal>Int `Either` Bool</literal>, or
  <literal>Int `a` Bool</literal>.  Similarly, parentheses work the same; e.g.  <literal>(:*:) Int Bool</literal>.
  </para></listitem>
<listitem><para>
  Fixities may be declared for type constructors just as for data constructors.  However,
  one cannot distinguish between the two in a fixity declaration; a fixity declaration
  sets the fixity for a data constructor and the corresponding type constructor.  For example:
<screen>
  infixl 7 T, :*:
</screen>
  sets the fixity for both type constructor <literal>T</literal> and data constructor <literal>T</literal>,
  and similarly for <literal>:*:</literal>.
  <literal>Int `a` Bool</literal>.
  </para></listitem>
<listitem><para>
  Function arrow is <literal>infixr</literal> with fixity 0.  (This might change; I'm not sure what it should be.)
  </para></listitem>
<listitem><para>
  Data type and type-synonym declarations can be written infix.  E.g.
<screen>
  data a :*: b = Foo a b
  type a :+: b = Either a b
</screen>
  </para></listitem>
<listitem><para>
  The only thing that differs between operators in types and operators in expressions is that
  ordinary non-constructor operators, such as <literal>+</literal> and <literal>*</literal>
  are not allowed in types. Reason: the uniform thing to do would be to make them type
  variables, but that's not very useful.  A less uniform but more useful thing would be to
  allow them to be type <emphasis>constructors</emphasis>.  But that gives trouble in export
  lists.  So for now we just exclude them.
  </para></listitem>

</itemizedlist>
</para>
</sect2>

867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
<sect2 id="sec-kinding">
<title>Explicitly-kinded quantification</title>

<para>
Haskell infers the kind of each type variable.  Sometimes it is nice to be able
to give the kind explicitly as (machine-checked) documentation, 
just as it is nice to give a type signature for a function.  On some occasions,
it is essential to do so.  For example, in his paper "Restricted Data Types in Haskell" (Haskell Workshop 1999)
John Hughes had to define the data type:
<Screen>
     data Set cxt a = Set [a]
                    | Unused (cxt a -> ())
</Screen>
The only use for the <literal>Unused</literal> constructor was to force the correct
kind for the type variable <literal>cxt</literal>.
</para>
<para>
GHC now instead allows you to specify the kind of a type variable directly, wherever
a type variable is explicitly bound.  Namely:
<itemizedlist>
<listitem><para><literal>data</literal> declarations:
<Screen>
  data Set (cxt :: * -> *) a = Set [a]
</Screen></para></listitem>
<listitem><para><literal>type</literal> declarations:
<Screen>
  type T (f :: * -> *) = f Int
</Screen></para></listitem>
<listitem><para><literal>class</literal> declarations:
<Screen>
  class (Eq a) => C (f :: * -> *) a where ...
</Screen></para></listitem>
<listitem><para><literal>forall</literal>'s in type signatures:
<Screen>
  f :: forall (cxt :: * -> *). Set cxt Int
</Screen></para></listitem>
</itemizedlist>
</para>

<para>
The parentheses are required.  Some of the spaces are required too, to
separate the lexemes.  If you write <literal>(f::*->*)</literal> you
will get a parse error, because "<literal>::*->*</literal>" is a
single lexeme in Haskell.
</para>

<para>
As part of the same extension, you can put kind annotations in types
as well.  Thus:
<Screen>
   f :: (Int :: *) -> Int
   g :: forall a. a -> (a :: *)
</Screen>
The syntax is
<Screen>
   atype ::= '(' ctype '::' kind ')
</Screen>
The parentheses are required.
</para>
</sect2>


929
<sect2 id="class-method-types">
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
<title>Class method types
</title>
<para>
Haskell 98 prohibits class method types to mention constraints on the
class type variable, thus:
<programlisting>
  class Seq s a where
    fromList :: [a] -> s a
    elem     :: Eq a => a -> s a -> Bool
</programlisting>
The type of <literal>elem</literal> is illegal in Haskell 98, because it
contains the constraint <literal>Eq a</literal>, constrains only the 
class type variable (in this case <literal>a</literal>).
</para>
<para>
With the <option>-fglasgow-exts</option> GHC lifts this restriction.
</para>

948
</sect2>
949

950
<sect2 id="multi-param-type-classes">
951
952
<title>Multi-parameter type classes
</title>
rrt's avatar
rrt committed
953

954
<para>
rrt's avatar
rrt committed
955
This section documents GHC's implementation of multi-parameter type
rrt's avatar
rrt committed
956
classes.  There's lots of background in the paper <ULink
957
958
959
URL="http://research.microsoft.com/~simonpj/multi.ps.gz" >Type
classes: exploring the design space</ULink > (Simon Peyton Jones, Mark
Jones, Erik Meijer).
960
</para>
rrt's avatar
rrt committed
961

962
<para>
rrt's avatar
rrt committed
963
964
965
966
967
I'd like to thank people who reported shorcomings in the GHC 3.02
implementation.  Our default decisions were all conservative ones, and
the experience of these heroic pioneers has given useful concrete
examples to support several generalisations.  (These appear below as
design choices not implemented in 3.02.)
968
</para>
rrt's avatar
rrt committed
969

970
<para>
rrt's avatar
rrt committed
971
972
973
974
I've discussed these notes with Mark Jones, and I believe that Hugs
will migrate towards the same design choices as I outline here.
Thanks to him, and to many others who have offered very useful
feedback.
975
</para>
rrt's avatar
rrt committed
976

977
<sect3>
978
<title>Types</title>
rrt's avatar
rrt committed
979

980
<para>
rrt's avatar
rrt committed
981
982
There are the following restrictions on the form of a qualified
type:
983
</para>
rrt's avatar
rrt committed
984

985
<para>
rrt's avatar
rrt committed
986

987
<programlisting>
988
  forall tv1..tvn (c1, ...,cn) => type
989
</programlisting>
rrt's avatar
rrt committed
990

991
</para>
rrt's avatar
rrt committed
992

993
<para>
rrt's avatar
rrt committed
994
995
996
997
(Here, I write the "foralls" explicitly, although the Haskell source
language omits them; in Haskell 1.4, all the free type variables of an
explicit source-language type signature are universally quantified,
except for the class type variables in a class declaration.  However,
998
999
in GHC, you can give the foralls if you want.  See <xref LinkEnd="universal-quantification">).
</para>
rrt's avatar
rrt committed
1000

1001
<para>
rrt's avatar
rrt committed
1002
1003

<OrderedList>
1004
<listitem>
rrt's avatar
rrt committed
1005

1006
1007
1008
<para>
 <emphasis>Each universally quantified type variable
<literal>tvi</literal> must be mentioned (i.e. appear free) in <literal>type</literal></emphasis>.
rrt's avatar
rrt committed
1009
1010
1011
1012
1013
1014

The reason for this is that a value with a type that does not obey
this restriction could not be used without introducing
ambiguity. Here, for example, is an illegal type:


1015
<programlisting>
1016
  forall a. Eq a => Int
1017
</programlisting>
rrt's avatar
rrt committed
1018
1019


1020
1021
When a value with this type was used, the constraint <literal>Eq tv</literal>
would be introduced where <literal>tv</literal> is a fresh type variable, and
rrt's avatar
rrt committed
1022
(in the dictionary-translation implementation) the value would be
1023
1024
1025
applied to a dictionary for <literal>Eq tv</literal>.  The difficulty is that we
can never know which instance of <literal>Eq</literal> to use because we never
get any more information about <literal>tv</literal>.
rrt's avatar
rrt committed
1026

1027
1028
1029
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1030

1031
1032
1033
<para>
 <emphasis>Every constraint <literal>ci</literal> must mention at least one of the
universally quantified type variables <literal>tvi</literal></emphasis>.
rrt's avatar
rrt committed
1034

1035
1036
For example, this type is OK because <literal>C a b</literal> mentions the
universally quantified type variable <literal>b</literal>:
rrt's avatar
rrt committed
1037
1038


1039
<programlisting>
1040
  forall a. C a b => burble
1041
</programlisting>
rrt's avatar
rrt committed
1042
1043


1044
1045
The next type is illegal because the constraint <literal>Eq b</literal> does not
mention <literal>a</literal>:
rrt's avatar
rrt committed
1046
1047


1048
<programlisting>
1049
  forall a. Eq b => burble
1050
</programlisting>
rrt's avatar
rrt committed
1051
1052
1053
1054
1055
1056
1057
1058
1059


The reason for this restriction is milder than the other one.  The
excluded types are never useful or necessary (because the offending
context doesn't need to be witnessed at this point; it can be floated
out).  Furthermore, floating them out increases sharing. Lastly,
excluding them is a conservative choice; it leaves a patch of
territory free in case we need it later.

1060
1061
</para>
</listitem>
rrt's avatar
rrt committed
1062
1063
1064

</OrderedList>

1065
</para>
rrt's avatar
rrt committed
1066

1067
<para>
rrt's avatar
rrt committed
1068
1069
These restrictions apply to all types, whether declared in a type signature
or inferred.
1070
</para>
rrt's avatar
rrt committed
1071

1072
1073
1074
<para>
Unlike Haskell 1.4, constraints in types do <emphasis>not</emphasis> have to be of
the form <emphasis>(class type-variables)</emphasis>.  Thus, these type signatures
rrt's avatar
rrt committed
1075
are perfectly OK
1076
</para>
rrt's avatar
rrt committed
1077

1078
<para>
rrt's avatar
rrt committed
1079

1080
<programlisting>
1081
1082
  f :: Eq (m a) => [m a] -> [m a]
  g :: Eq [a] => ...
1083
</programlisting>
rrt's avatar
rrt committed
1084

1085
</para>
rrt's avatar
rrt committed
1086

1087
<para>
rrt's avatar
rrt committed
1088
This choice recovers principal types, a property that Haskell 1.4 does not have.
1089
</para>
rrt's avatar
rrt committed
1090

1091
</sect3>
rrt's avatar
rrt committed
1092

1093
<sect3>
1094
<title>Class declarations</title>
rrt's avatar
rrt committed
1095

1096
<para>
rrt's avatar
rrt committed
1097
1098

<OrderedList>
1099
<listitem>
rrt's avatar
rrt committed
1100

1101
1102
<para>
 <emphasis>Multi-parameter type classes are permitted</emphasis>. For example:
rrt's avatar
rrt committed
1103
1104


1105
<programlisting>
rrt's avatar
rrt committed
1106
  class Collection c a where
1107
    union :: c a -> c a -> c a
rrt's avatar
rrt committed
1108
    ...etc.
1109
</programlisting>
rrt's avatar
rrt committed
1110
1111
1112



1113
1114
1115
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1116

1117
1118
<para>
 <emphasis>The class hierarchy must be acyclic</emphasis>.  However, the definition
rrt's avatar
rrt committed
1119
1120
1121
1122
of "acyclic" involves only the superclass relationships.  For example,
this is OK:


1123
<programlisting>
rrt's avatar
rrt committed
1124
  class C a where {
1125
    op :: D b => a -> b -> b
rrt's avatar
rrt committed
1126
1127
  }

1128
  class C a => D a where { ... }
1129
</programlisting>
rrt's avatar
rrt committed
1130
1131


1132
1133
1134
Here, <literal>C</literal> is a superclass of <literal>D</literal>, but it's OK for a
class operation <literal>op</literal> of <literal>C</literal> to mention <literal>D</literal>.  (It
would not be OK for <literal>D</literal> to be a superclass of <literal>C</literal>.)
rrt's avatar
rrt committed
1135

1136
1137
1138
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1139

1140
1141
<para>
 <emphasis>There are no restrictions on the context in a class declaration
rrt's avatar
rrt committed
1142
(which introduces superclasses), except that the class hierarchy must
1143
be acyclic</emphasis>.  So these class declarations are OK:
rrt's avatar
rrt committed
1144
1145


1146
<programlisting>
1147
  class Functor (m k) => FiniteMap m k where
rrt's avatar
rrt committed
1148
1149
    ...

1150
1151
  class (Monad m, Monad (t m)) => Transform t m where
    lift :: m a -> (t m) a
1152
</programlisting>
rrt's avatar
rrt committed
1153
1154


1155
1156
1157
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1158

1159
1160
<para>
 <emphasis>In the signature of a class operation, every constraint
rrt's avatar
rrt committed
1161
must mention at least one type variable that is not a class type
1162
variable</emphasis>.
rrt's avatar
rrt committed
1163
1164
1165
1166

Thus:


1167
<programlisting>
rrt's avatar
rrt committed
1168
  class Collection c a where
1169
    mapC :: Collection c b => (a->b) -> c a -> c b
1170
</programlisting>
rrt's avatar
rrt committed
1171
1172


1173
1174
1175
is OK because the constraint <literal>(Collection a b)</literal> mentions
<literal>b</literal>, even though it also mentions the class variable
<literal>a</literal>.  On the other hand:
rrt's avatar
rrt committed
1176
1177


1178
<programlisting>
rrt's avatar
rrt committed
1179
  class C a where
1180
    op :: Eq a => (a,b) -> (a,b)
1181
</programlisting>
rrt's avatar
rrt committed
1182
1183


1184
1185
is not OK because the constraint <literal>(Eq a)</literal> mentions on the class
type variable <literal>a</literal>, but not <literal>b</literal>.  However, any such
rrt's avatar
rrt committed
1186
1187
1188
1189
example is easily fixed by moving the offending context up to the
superclass context:


1190
<programlisting>
1191
1192
  class Eq a => C a where
    op ::(a,b) -> (a,b)
1193
</programlisting>
rrt's avatar
rrt committed
1194
1195
1196
1197
1198
1199


A yet more relaxed rule would allow the context of a class-op signature
to mention only class type variables.  However, that conflicts with
Rule 1(b) for types above.

1200
1201
1202
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1203

1204
1205
1206
<para>
 <emphasis>The type of each class operation must mention <emphasis>all</emphasis> of
the class type variables</emphasis>.  For example:
rrt's avatar
rrt committed
1207
1208


1209
<programlisting>
rrt's avatar
rrt committed
1210
1211
  class Coll s a where
    empty  :: s
1212
    insert :: s -> a -> s
1213
</programlisting>
rrt's avatar
rrt committed
1214
1215


1216
1217
is not OK, because the type of <literal>empty</literal> doesn't mention
<literal>a</literal>.  This rule is a consequence of Rule 1(a), above, for
rrt's avatar
rrt committed
1218
1219
1220
types, and has the same motivation.

Sometimes, offending class declarations exhibit misunderstandings.  For
1221
example, <literal>Coll</literal> might be rewritten
rrt's avatar
rrt committed
1222
1223


1224
<programlisting>
rrt's avatar
rrt committed
1225
1226
  class Coll s a where
    empty  :: s a
1227
    insert :: s a -> a -> s a
1228
</programlisting>
rrt's avatar
rrt committed
1229
1230
1231


which makes the connection between the type of a collection of
1232
<literal>a</literal>'s (namely <literal>(s a)</literal>) and the element type <literal>a</literal>.
rrt's avatar
rrt committed
1233
1234
1235
1236
Occasionally this really doesn't work, in which case you can split the
class like this:


1237
<programlisting>
rrt's avatar
rrt committed
1238
1239
1240
  class CollE s where
    empty  :: s

1241
1242
  class CollE s => Coll s a where
    insert :: s -> a -> s
1243
</programlisting>
rrt's avatar
rrt committed
1244
1245


1246
1247
</para>
</listitem>
rrt's avatar
rrt committed
1248
1249
1250

</OrderedList>

1251
</para>
rrt's avatar
rrt committed
1252

1253
</sect3>
rrt's avatar
rrt committed
1254

1255
<sect3 id="instance-decls">
1256
<title>Instance declarations</title>
rrt's avatar
rrt committed
1257

1258
<para>
rrt's avatar
rrt committed
1259
1260

<OrderedList>
1261
<listitem>
rrt's avatar
rrt committed
1262

1263
1264
<para>
 <emphasis>Instance declarations may not overlap</emphasis>.  The two instance
rrt's avatar
rrt committed
1265
1266
1267
declarations


1268
<programlisting>
1269
1270
  instance context1 => C type1 where ...
  instance context2 => C type2 where ...
1271
</programlisting>
rrt's avatar
rrt committed
1272
1273


1274
"overlap" if <literal>type1</literal> and <literal>type2</literal> unify
rrt's avatar
rrt committed
1275
1276

However, if you give the command line option
1277
<option>-fallow-overlapping-instances</option><indexterm><primary>-fallow-overlapping-instances
1278
1279
1280
option</primary></indexterm> then overlapping instance declarations are permitted.
However, GHC arranges never to commit to using an instance declaration
if another instance declaration also applies, either now or later.
rrt's avatar
rrt committed
1281

1282
1283
<itemizedlist>
<listitem>
rrt's avatar
rrt committed
1284

1285
1286
1287
1288
1289
<para>
 EITHER <literal>type1</literal> and <literal>type2</literal> do not unify
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1290

1291
1292
<para>
 OR <literal>type2</literal> is a substitution instance of <literal>type1</literal>
1293
(but not identical to <literal>type1</literal>), or vice versa.
1294
1295
1296
</para>
</listitem>
</itemizedlist>
rrt's avatar
rrt committed
1297
Notice that these rules
1298
1299
<itemizedlist>
<listitem>
rrt's avatar
rrt committed
1300

1301
<para>
rrt's avatar
rrt committed
1302
1303
1304
 make it clear which instance decl to use
(pick the most specific one that matches)

1305
1306
1307
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1308

1309
1310
<para>
 do not mention the contexts <literal>context1</literal>, <literal>context2</literal>
rrt's avatar
rrt committed
1311
1312
Reason: you can pick which instance decl
"matches" based on the type.
1313
1314
</para>
</listitem>
rrt's avatar
rrt committed
1315

1316
</itemizedlist>
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
However the rules are over-conservative.  Two instance declarations can overlap,
but it can still be clear in particular situations which to use.  For example:
<programlisting>
  instance C (Int,a) where ...
  instance C (a,Bool) where ...
</programlisting>
These are rejected by GHC's rules, but it is clear what to do when trying
to solve the constraint <literal>C (Int,Int)</literal> because the second instance
cannot apply.  Yell if this restriction bites you.
</para>
<para>
GHC is also conservative about committing to an overlapping instance.  For example:
<programlisting>
  class C a where { op :: a -> a }
  instance C [Int] where ...
  instance C a => C [a] where ...
  
  f :: C b => [b] -> [b]
  f x = op x
</programlisting>
From the RHS of f we get the constraint <literal>C [b]</literal>.  But
GHC does not commit to the second instance declaration, because in a paricular
call of f, b might be instantiate to Int, so the first instance declaration
would be appropriate.  So GHC rejects the program.  If you add <option>-fallow-incoherent-instances</option>
GHC will instead silently pick the second instance, without complaining about 
the problem of subsequent instantiations.
</para>
<para>
rrt's avatar
rrt committed
1345
1346
1347
1348
Regrettably, GHC doesn't guarantee to detect overlapping instance
declarations if they appear in different modules.  GHC can "see" the
instance declarations in the transitive closure of all the modules
imported by the one being compiled, so it can "see" all instance decls
1349
when it is compiling <literal>Main</literal>.  However, it currently chooses not
rrt's avatar
rrt committed
1350
1351
to look at ones that can't possibly be of use in the module currently
being compiled, in the interests of efficiency.  (Perhaps we should
1352
change that decision, at least for <literal>Main</literal>.)
rrt's avatar
rrt committed
1353

1354
1355
1356
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1357

1358
1359
1360
<para>
 <emphasis>There are no restrictions on the type in an instance
<emphasis>head</emphasis>, except that at least one must not be a type variable</emphasis>.
1361
The instance "head" is the bit after the "=>" in an instance decl. For
rrt's avatar
rrt committed
1362
1363
1364
example, these are OK:


1365
<programlisting>
rrt's avatar
rrt committed
1366
1367
1368
1369
1370
  instance C Int a where ...

  instance D (Int, Int) where ...

  instance E [[a]] where ...
1371
</programlisting>
rrt's avatar
rrt committed
1372
1373


1374
Note that instance heads <emphasis>may</emphasis> contain repeated type variables.
rrt's avatar
rrt committed
1375
1376
1377
For example, this is OK:


1378
<programlisting>
rrt's avatar
rrt committed
1379
  instance Stateful (ST s) (MutVar s) where ...
1380
</programlisting>
rrt's avatar
rrt committed
1381
1382
1383
1384
1385
1386
1387
1388


The "at least one not a type variable" restriction is to ensure that
context reduction terminates: each reduction step removes one type
constructor.  For example, the following would make the type checker
loop if it wasn't excluded:


1389
<programlisting>
1390
  instance C a => C a where ...
1391
</programlisting>
rrt's avatar
rrt committed
1392
1393
1394
1395
1396
1397
1398
1399


There are two situations in which the rule is a bit of a pain. First,
if one allows overlapping instance declarations then it's quite
convenient to have a "default instance" declaration that applies if
something more specific does not:


1400
<programlisting>
rrt's avatar
rrt committed
1401
1402
  instance C a where
    op = ... -- Default
1403
</programlisting>
rrt's avatar
rrt committed
1404
1405
1406
1407
1408
1409


Second, sometimes you might want to use the following to get the
effect of a "class synonym":


1410
<programlisting>
1411
  class (C1 a, C2 a, C3 a) => C a where { }
rrt's avatar
rrt committed
1412

1413
  instance (C1 a, C2 a, C3 a) => C a where { }
1414
</programlisting>
rrt's avatar
rrt committed
1415
1416
1417
1418
1419


This allows you to write shorter signatures:


1420
<programlisting>
1421
  f :: C a => ...
1422
</programlisting>
rrt's avatar
rrt committed
1423
1424
1425
1426
1427


instead of


1428
<programlisting>
1429
  f :: (C1 a, C2 a, C3 a) => ...
1430
</programlisting>
rrt's avatar
rrt committed
1431
1432
1433
1434


I'm on the lookout for a simple rule that preserves decidability while
allowing these idioms.  The experimental flag
1435
1436
<option>-fallow-undecidable-instances</option><indexterm><primary>-fallow-undecidable-instances
option</primary></indexterm> lifts this restriction, allowing all the types in an
rrt's avatar
rrt committed
1437
1438
instance head to be type variables.

1439
1440
1441
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1442

1443
1444
1445
<para>
 <emphasis>Unlike Haskell 1.4, instance heads may use type
synonyms</emphasis>.  As always, using a type synonym is just shorthand for
rrt's avatar
rrt committed
1446
1447
1448
writing the RHS of the type synonym definition.  For example:


1449
<programlisting>
rrt's avatar
rrt committed
1450
1451
1452
  type Point = (Int,Int)
  instance C Point   where ...
  instance C [Point] where ...
1453
</programlisting>
rrt's avatar
rrt committed
1454
1455
1456
1457
1458


is legal.  However, if you added


1459
<programlisting>
rrt's avatar
rrt committed
1460
  instance C (Int,Int) where ...
1461
</programlisting>
rrt's avatar
rrt committed
1462
1463
1464
1465
1466
1467
1468


as well, then the compiler will complain about the overlapping
(actually, identical) instance declarations.  As always, type synonyms
must be fully applied.  You cannot, for example, write:


1469
<programlisting>
rrt's avatar
rrt committed
1470
1471
  type P a = [[a]]
  instance Monad P where ...
1472
</programlisting>
rrt's avatar
rrt committed
1473
1474
1475
1476
1477


This design decision is independent of all the others, and easily
reversed, but it makes sense to me.

1478
1479
1480
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1481

1482
1483
1484
<para>
<emphasis>The types in an instance-declaration <emphasis>context</emphasis> must all
be type variables</emphasis>. Thus
rrt's avatar
rrt committed
1485
1486


1487
<programlisting>
1488
instance C a b => Eq (a,b) where ...
1489
</programlisting>
rrt's avatar
rrt committed
1490
1491
1492
1493
1494


is OK, but


1495
<programlisting>
1496
instance C Int b => Foo b where ...
1497
</programlisting>
rrt's avatar
rrt committed
1498
1499
1500
1501
1502
1503
1504


is not OK.  Again, the intent here is to make sure that context
reduction terminates.

Voluminous correspondence on the Haskell mailing list has convinced me
that it's worth experimenting with a more liberal rule.  If you use
1505
the flag <option>-fallow-undecidable-instances</option> can use arbitrary
rrt's avatar
rrt committed
1506
1507
1508
types in an instance context.  Termination is ensured by having a
fixed-depth recursion stack.  If you exceed the stack depth you get a
sort of backtrace, and the opportunity to increase the stack depth
1509
with <option>-fcontext-stack</option><emphasis>N</emphasis>.
rrt's avatar
rrt committed
1510

1511
1512
</para>
</listitem>
rrt's avatar
rrt committed
1513
1514
1515

</OrderedList>

1516
</para>
rrt's avatar
rrt committed
1517

1518
</sect3>
rrt's avatar
rrt committed
1519

1520
</sect2>
rrt's avatar
rrt committed
1521

1522
<sect2 id="implicit-parameters">
1523
1524
<title>Implicit parameters
</title>
1525

1526
<para> Implicit paramters are implemented as described in 
1527
1528
1529
1530
"Implicit parameters: dynamic scoping with static types", 
J Lewis, MB Shields, E Meijer, J Launchbury,
27th ACM Symposium on Principles of Programming Languages (POPL'00),
Boston, Jan 2000.
1531
</para>
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
<para>(Most of the following, stil rather incomplete, documentation is due to Jeff Lewis.)</para>
<para>
A variable is called <emphasis>dynamically bound</emphasis> when it is bound by the calling
context of a function and <emphasis>statically bound</emphasis> when bound by the callee's
context. In Haskell, all variables are statically bound. Dynamic
binding of variables is a notion that goes back to Lisp, but was later
discarded in more modern incarnations, such as Scheme. Dynamic binding
can be very confusing in an untyped language, and unfortunately, typed
languages, in particular Hindley-Milner typed languages like Haskell,
only support static scoping of variables.
</para>
<para>
However, by a simple extension to the type class system of Haskell, we
can support dynamic binding. Basically, we express the use of a
dynamically bound variable as a constraint on the type. These
constraints lead to types of the form <literal>(?x::t') => t</literal>, which says "this
function uses a dynamically-bound variable <literal>?x</literal> 
of type <literal>t'</literal>". For
example, the following expresses the type of a sort function,
implicitly parameterized by a comparison function named <literal>cmp</literal>.
<programlisting>
  sort :: (?cmp :: a -> a -> Bool) => [a] -> [a]
</programlisting>
The dynamic binding constraints are just a new form of predicate in the type class system.
</para>
<para>
1558
An implicit parameter occurs in an expression using the special form <literal>?x</literal>, 
1559
where <literal>x</literal> is
1560
1561
1562
1563
any valid identifier (e.g. <literal>ord ?x</literal> is a valid expression). 
Use of this construct also introduces a new
dynamic-binding constraint in the type of the expression. 
For example, the following definition
1564
1565
1566
1567
shows how we can define an implicitly parameterized sort function in
terms of an explicitly parameterized <literal>sortBy</literal> function:
<programlisting>
  sortBy :: (a -> a -> Bool) -> [a] -> [a]
1568

1569
1570
1571
  sort   :: (?cmp :: a -> a -> Bool) => [a] -> [a]
  sort    = sortBy ?cmp
</programlisting>
1572
1573
1574
1575
1576
</para>

<sect3>
<title>Implicit-parameter type constraints</title>
<para>
1577
1578
1579
1580
1581
1582
1583