glasgow_exts.sgml 121 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
&primitives;
rrt's avatar
rrt committed
156
157


158
159
160
<!-- TYPE SYSTEM EXTENSIONS -->
<sect1 id="type-extensions">
<title>Type system extensions</title>
rrt's avatar
rrt committed
161

162
<sect2 id="nullary-types">
163
164
<title>Data types with no constructors</title>

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

168
169
170
171
<programlisting>
  data S      -- S :: *
  data T a    -- T :: * -> *
</programlisting>
172

173
<para>Syntactically, the declaration lacks the "= constrs" part.  The 
174
175
176
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>
177
178
179

<para>Such data types have only one value, namely bottom.
Nevertheless, they can be useful when defining "phantom types".</para>
180
</sect2>
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
<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>

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
<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>


297
<sect2 id="class-method-types">
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<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>

316
</sect2>
317

318
<sect2 id="multi-param-type-classes">
319
320
<title>Multi-parameter type classes
</title>
rrt's avatar
rrt committed
321

322
<para>
rrt's avatar
rrt committed
323
This section documents GHC's implementation of multi-parameter type
rrt's avatar
rrt committed
324
classes.  There's lots of background in the paper <ULink
325
326
327
URL="http://research.microsoft.com/~simonpj/multi.ps.gz" >Type
classes: exploring the design space</ULink > (Simon Peyton Jones, Mark
Jones, Erik Meijer).
328
</para>
rrt's avatar
rrt committed
329

330
<para>
rrt's avatar
rrt committed
331
332
333
334
335
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.)
336
</para>
rrt's avatar
rrt committed
337

338
<para>
rrt's avatar
rrt committed
339
340
341
342
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.
343
</para>
rrt's avatar
rrt committed
344

345
<sect3>
346
<title>Types</title>
rrt's avatar
rrt committed
347

348
<para>
rrt's avatar
rrt committed
349
350
There are the following restrictions on the form of a qualified
type:
351
</para>
rrt's avatar
rrt committed
352

353
<para>
rrt's avatar
rrt committed
354

355
<programlisting>
356
  forall tv1..tvn (c1, ...,cn) => type
357
</programlisting>
rrt's avatar
rrt committed
358

359
</para>
rrt's avatar
rrt committed
360

361
<para>
rrt's avatar
rrt committed
362
363
364
365
(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,
366
367
in GHC, you can give the foralls if you want.  See <xref LinkEnd="universal-quantification">).
</para>
rrt's avatar
rrt committed
368

369
<para>
rrt's avatar
rrt committed
370
371

<OrderedList>
372
<listitem>
rrt's avatar
rrt committed
373

374
375
376
<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
377
378
379
380
381
382

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:


383
<programlisting>
384
  forall a. Eq a => Int
385
</programlisting>
rrt's avatar
rrt committed
386
387


388
389
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
390
(in the dictionary-translation implementation) the value would be
391
392
393
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
394

395
396
397
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
398

399
400
401
<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
402

403
404
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
405
406


407
<programlisting>
408
  forall a. C a b => burble
409
</programlisting>
rrt's avatar
rrt committed
410
411


412
413
The next type is illegal because the constraint <literal>Eq b</literal> does not
mention <literal>a</literal>:
rrt's avatar
rrt committed
414
415


416
<programlisting>
417
  forall a. Eq b => burble
418
</programlisting>
rrt's avatar
rrt committed
419
420
421
422
423
424
425
426
427


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.

428
429
</para>
</listitem>
rrt's avatar
rrt committed
430
431
432

</OrderedList>

433
</para>
rrt's avatar
rrt committed
434

435
<para>
rrt's avatar
rrt committed
436
437
These restrictions apply to all types, whether declared in a type signature
or inferred.
438
</para>
rrt's avatar
rrt committed
439

440
441
442
<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
443
are perfectly OK
444
</para>
rrt's avatar
rrt committed
445

446
<para>
rrt's avatar
rrt committed
447

448
<programlisting>
449
450
  f :: Eq (m a) => [m a] -> [m a]
  g :: Eq [a] => ...
451
</programlisting>
rrt's avatar
rrt committed
452

453
</para>
rrt's avatar
rrt committed
454

455
<para>
rrt's avatar
rrt committed
456
This choice recovers principal types, a property that Haskell 1.4 does not have.
457
</para>
rrt's avatar
rrt committed
458

459
</sect3>
rrt's avatar
rrt committed
460

461
<sect3>
462
<title>Class declarations</title>
rrt's avatar
rrt committed
463

464
<para>
rrt's avatar
rrt committed
465
466

<OrderedList>
467
<listitem>
rrt's avatar
rrt committed
468

469
470
<para>
 <emphasis>Multi-parameter type classes are permitted</emphasis>. For example:
rrt's avatar
rrt committed
471
472


473
<programlisting>
rrt's avatar
rrt committed
474
  class Collection c a where
475
    union :: c a -> c a -> c a
rrt's avatar
rrt committed
476
    ...etc.
477
</programlisting>
rrt's avatar
rrt committed
478
479
480



481
482
483
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
484

485
486
<para>
 <emphasis>The class hierarchy must be acyclic</emphasis>.  However, the definition
rrt's avatar
rrt committed
487
488
489
490
of "acyclic" involves only the superclass relationships.  For example,
this is OK:


491
<programlisting>
rrt's avatar
rrt committed
492
  class C a where {
493
    op :: D b => a -> b -> b
rrt's avatar
rrt committed
494
495
  }

496
  class C a => D a where { ... }
497
</programlisting>
rrt's avatar
rrt committed
498
499


500
501
502
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
503

504
505
506
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
507

508
509
<para>
 <emphasis>There are no restrictions on the context in a class declaration
rrt's avatar
rrt committed
510
(which introduces superclasses), except that the class hierarchy must
511
be acyclic</emphasis>.  So these class declarations are OK:
rrt's avatar
rrt committed
512
513


514
<programlisting>
515
  class Functor (m k) => FiniteMap m k where
rrt's avatar
rrt committed
516
517
    ...

518
519
  class (Monad m, Monad (t m)) => Transform t m where
    lift :: m a -> (t m) a
520
</programlisting>
rrt's avatar
rrt committed
521
522


523
524
525
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
526

527
528
<para>
 <emphasis>In the signature of a class operation, every constraint
rrt's avatar
rrt committed
529
must mention at least one type variable that is not a class type
530
variable</emphasis>.
rrt's avatar
rrt committed
531
532
533
534

Thus:


535
<programlisting>
rrt's avatar
rrt committed
536
  class Collection c a where
537
    mapC :: Collection c b => (a->b) -> c a -> c b
538
</programlisting>
rrt's avatar
rrt committed
539
540


541
542
543
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
544
545


546
<programlisting>
rrt's avatar
rrt committed
547
  class C a where
548
    op :: Eq a => (a,b) -> (a,b)
549
</programlisting>
rrt's avatar
rrt committed
550
551


552
553
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
554
555
556
557
example is easily fixed by moving the offending context up to the
superclass context:


558
<programlisting>
559
560
  class Eq a => C a where
    op ::(a,b) -> (a,b)
561
</programlisting>
rrt's avatar
rrt committed
562
563
564
565
566
567


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.

568
569
570
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
571

572
573
574
<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
575
576


577
<programlisting>
rrt's avatar
rrt committed
578
579
  class Coll s a where
    empty  :: s
580
    insert :: s -> a -> s
581
</programlisting>
rrt's avatar
rrt committed
582
583


584
585
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
586
587
588
types, and has the same motivation.

Sometimes, offending class declarations exhibit misunderstandings.  For
589
example, <literal>Coll</literal> might be rewritten
rrt's avatar
rrt committed
590
591


592
<programlisting>
rrt's avatar
rrt committed
593
594
  class Coll s a where
    empty  :: s a
595
    insert :: s a -> a -> s a
596
</programlisting>
rrt's avatar
rrt committed
597
598
599


which makes the connection between the type of a collection of
600
<literal>a</literal>'s (namely <literal>(s a)</literal>) and the element type <literal>a</literal>.
rrt's avatar
rrt committed
601
602
603
604
Occasionally this really doesn't work, in which case you can split the
class like this:


605
<programlisting>
rrt's avatar
rrt committed
606
607
608
  class CollE s where
    empty  :: s

609
610
  class CollE s => Coll s a where
    insert :: s -> a -> s
611
</programlisting>
rrt's avatar
rrt committed
612
613


614
615
</para>
</listitem>
rrt's avatar
rrt committed
616
617
618

</OrderedList>

619
</para>
rrt's avatar
rrt committed
620

621
</sect3>
rrt's avatar
rrt committed
622

623
<sect3 id="instance-decls">
624
<title>Instance declarations</title>
rrt's avatar
rrt committed
625

626
<para>
rrt's avatar
rrt committed
627
628

<OrderedList>
629
<listitem>
rrt's avatar
rrt committed
630

631
632
<para>
 <emphasis>Instance declarations may not overlap</emphasis>.  The two instance
rrt's avatar
rrt committed
633
634
635
declarations


636
<programlisting>
637
638
  instance context1 => C type1 where ...
  instance context2 => C type2 where ...
639
</programlisting>
rrt's avatar
rrt committed
640
641


642
"overlap" if <literal>type1</literal> and <literal>type2</literal> unify
rrt's avatar
rrt committed
643
644

However, if you give the command line option
645
<option>-fallow-overlapping-instances</option><indexterm><primary>-fallow-overlapping-instances
646
647
648
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
649

650
651
<itemizedlist>
<listitem>
rrt's avatar
rrt committed
652

653
654
655
656
657
<para>
 EITHER <literal>type1</literal> and <literal>type2</literal> do not unify
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
658

659
660
<para>
 OR <literal>type2</literal> is a substitution instance of <literal>type1</literal>
661
(but not identical to <literal>type1</literal>), or vice versa.
662
663
664
</para>
</listitem>
</itemizedlist>
rrt's avatar
rrt committed
665
Notice that these rules
666
667
<itemizedlist>
<listitem>
rrt's avatar
rrt committed
668

669
<para>
rrt's avatar
rrt committed
670
671
672
 make it clear which instance decl to use
(pick the most specific one that matches)

673
674
675
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
676

677
678
<para>
 do not mention the contexts <literal>context1</literal>, <literal>context2</literal>
rrt's avatar
rrt committed
679
680
Reason: you can pick which instance decl
"matches" based on the type.
681
682
</para>
</listitem>
rrt's avatar
rrt committed
683

684
</itemizedlist>
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
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
713
714
715
716
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
717
when it is compiling <literal>Main</literal>.  However, it currently chooses not
rrt's avatar
rrt committed
718
719
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
720
change that decision, at least for <literal>Main</literal>.)
rrt's avatar
rrt committed
721

722
723
724
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
725

726
727
728
<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>.
729
The instance "head" is the bit after the "=>" in an instance decl. For
rrt's avatar
rrt committed
730
731
732
example, these are OK:


733
<programlisting>
rrt's avatar
rrt committed
734
735
736
737
738
  instance C Int a where ...

  instance D (Int, Int) where ...

  instance E [[a]] where ...
739
</programlisting>
rrt's avatar
rrt committed
740
741


742
Note that instance heads <emphasis>may</emphasis> contain repeated type variables.
rrt's avatar
rrt committed
743
744
745
For example, this is OK:


746
<programlisting>
rrt's avatar
rrt committed
747
  instance Stateful (ST s) (MutVar s) where ...
748
</programlisting>
rrt's avatar
rrt committed
749
750
751
752
753
754
755
756


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:


757
<programlisting>
758
  instance C a => C a where ...
759
</programlisting>
rrt's avatar
rrt committed
760
761
762
763
764
765
766
767


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:


768
<programlisting>
rrt's avatar
rrt committed
769
770
  instance C a where
    op = ... -- Default
771
</programlisting>
rrt's avatar
rrt committed
772
773
774
775
776
777


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


778
<programlisting>
779
  class (C1 a, C2 a, C3 a) => C a where { }
rrt's avatar
rrt committed
780

781
  instance (C1 a, C2 a, C3 a) => C a where { }
782
</programlisting>
rrt's avatar
rrt committed
783
784
785
786
787


This allows you to write shorter signatures:


788
<programlisting>
789
  f :: C a => ...
790
</programlisting>
rrt's avatar
rrt committed
791
792
793
794
795


instead of


796
<programlisting>
797
  f :: (C1 a, C2 a, C3 a) => ...
798
</programlisting>
rrt's avatar
rrt committed
799
800
801
802


I'm on the lookout for a simple rule that preserves decidability while
allowing these idioms.  The experimental flag
803
804
<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
805
806
instance head to be type variables.

807
808
809
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
810

811
812
813
<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
814
815
816
writing the RHS of the type synonym definition.  For example:


817
<programlisting>
rrt's avatar
rrt committed
818
819
820
  type Point = (Int,Int)
  instance C Point   where ...
  instance C [Point] where ...
821
</programlisting>
rrt's avatar
rrt committed
822
823
824
825
826


is legal.  However, if you added


827
<programlisting>
rrt's avatar
rrt committed
828
  instance C (Int,Int) where ...
829
</programlisting>
rrt's avatar
rrt committed
830
831
832
833
834
835
836


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:


837
<programlisting>
rrt's avatar
rrt committed
838
839
  type P a = [[a]]
  instance Monad P where ...
840
</programlisting>
rrt's avatar
rrt committed
841
842
843
844
845


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

846
847
848
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
849

850
851
852
<para>
<emphasis>The types in an instance-declaration <emphasis>context</emphasis> must all
be type variables</emphasis>. Thus
rrt's avatar
rrt committed
853
854


855
<programlisting>
856
instance C a b => Eq (a,b) where ...
857
</programlisting>
rrt's avatar
rrt committed
858
859
860
861
862


is OK, but


863
<programlisting>
864
instance C Int b => Foo b where ...
865
</programlisting>
rrt's avatar
rrt committed
866
867
868
869
870
871
872


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
873
the flag <option>-fallow-undecidable-instances</option> can use arbitrary
rrt's avatar
rrt committed
874
875
876
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
877
with <option>-fcontext-stack</option><emphasis>N</emphasis>.
rrt's avatar
rrt committed
878

879
880
</para>
</listitem>
rrt's avatar
rrt committed
881
882
883

</OrderedList>

884
</para>
rrt's avatar
rrt committed
885

886
</sect3>
rrt's avatar
rrt committed
887

888
</sect2>
rrt's avatar
rrt committed
889

890
<sect2 id="implicit-parameters">
891
892
<title>Implicit parameters
</title>
893

894
<para> Implicit paramters are implemented as described in 
895
896
897
898
"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.
899
</para>
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
929
930
931
932
933
<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>
An implicit parameter is introduced by the special form <literal>?x</literal>, 
where <literal>x</literal> is
any valid identifier. Use if this construct also introduces new
dynamic binding constraints. For example, the following definition
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]
934

935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
  sort   :: (?cmp :: a -> a -> Bool) => [a] -> [a]
  sort    = sortBy ?cmp
</programlisting>
Dynamic binding constraints behave just like other type class
constraints in that they are automatically propagated. Thus, when a
function is used, its implicit parameters are inherited by the
function that called it. For example, our <literal>sort</literal> function might be used
to pick out the least value in a list:
<programlisting>
  least   :: (?cmp :: a -> a -> Bool) => [a] -> a
  least xs = fst (sort xs)
</programlisting>
Without lifting a finger, the <literal>?cmp</literal> parameter is
propagated to become a parameter of <literal>least</literal> as well. With explicit
parameters, the default is that parameters must always be explicit
propagated. With implicit parameters, the default is to always
propagate them.
</para>
953
<para>
954
955
956
957
958
959
An implicit parameter differs from other type class constraints in the
following way: All uses of a particular implicit parameter must have
the same type. This means that the type of <literal>(?x, ?x)</literal> 
is <literal>(?x::a) => (a,a)</literal>, and not 
<literal>(?x::a, ?x::b) => (a, b)</literal>, as would be the case for type
class constraints.
960
</para>
961
<para>
962
963
964
965
966
967
968
969
970
An implicit parameter is bound using the standard
<literal>let</literal> binding form, where the bindings must be a
collection of simple bindings to implicit-style variables (no
function-style bindings, and no type signatures); these bindings are
neither polymorphic or recursive. This form binds the implicit
parameters arising in the body, not the free variables as a
<literal>let</literal> or <literal>where</literal> would do. For
example, we define the <literal>min</literal> function by binding
<literal>cmp</literal>.</para>
971
972
<programlisting>
  min :: [a] -> a
973
  min  = let ?cmp = (<=) in least
974
975
</programlisting>
<para>
976
Note the following points:
977
<itemizedlist>
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<listitem><para>
You may not mix implicit-parameter bindings with ordinary bindings in a 
single <literal>let</literal>
expression; use two nested <literal>let</literal>s instead.
</para></listitem>

<listitem><para>
You may put multiple implicit-parameter bindings in a
single <literal>let</literal> expression; they are <emphasis>not</emphasis> treated
as a mutually recursive group (as ordinary <literal>let</literal> bindings are).
Instead they are treated as a non-recursive group, each scoping over the bindings that
follow.  For example, consider:
<programlisting>
  f y = let { ?x = y; ?x = ?x+1 } in ?x
</programlisting>
This function adds one to its argument.
</para></listitem>

<listitem><para>
You may not have an implicit-parameter binding in a <literal>where</literal> clause,
only in a <literal>let</literal> binding.
</para></listitem>

For faster browsing, not all history is shown. View entire blame