glasgow_exts.xml 189 KB
Newer Older
1
<?xml version="1.0" encoding="iso-8859-1"?>
2
3
4
<para>
<indexterm><primary>language, GHC</primary></indexterm>
<indexterm><primary>extensions, GHC</primary></indexterm>
rrt's avatar
rrt committed
5
As with all known Haskell systems, GHC implements some extensions to
6
7
the language.  They are all enabled by options; by default GHC
understands only plain Haskell 98.
8
</para>
rrt's avatar
rrt committed
9

10
<para>
11
12
13
14
15
16
17
18
Some 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-portable
code at a more primitive level.  You need not be &ldquo;stuck&rdquo;
on performance because of the implementation costs of Haskell's
&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!
19
</para>
rrt's avatar
rrt committed
20

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

30
<!-- LANGUAGE OPTIONS -->
31
32
  <sect1 id="options-language">
    <title>Language options</title>
33

34
35
36
37
38
39
    <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>
40

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

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    <para>NB. turning on an option that enables special syntax
    <emphasis>might</emphasis> cause working Haskell 98 code to fail
    to compile, perhaps because it uses a variable name which has
    become a reserved word.  So, together with each option below, we
    list the special syntax which is enabled by this option.  We use
    notation and nonterminal names from the Haskell 98 lexical syntax
    (see the Haskell 98 Report).  There are two classes of special
    syntax:</para>

    <itemizedlist>
      <listitem>
	<para>New reserved words and symbols: character sequences
        which are no longer available for use as identifiers in the
        program.</para>
      </listitem>
      <listitem>
	<para>Other special syntax: sequences of characters that have
	a different meaning when this particular option is turned
	on.</para>
      </listitem>
    </itemizedlist>

    <para>We are only listing syntax changes here that might affect
    existing working programs (i.e. "stolen" syntax).  Many of these
    extensions will also enable new context-free syntax, but in all
    cases programs written to use the new syntax would not be
    compilable without the option enabled.</para>

73
    <variablelist>
74

75
      <varlistentry>
76
77
78
79
	<term>
          <option>-fglasgow-exts</option>:
          <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
        </term>
80
81
82
	<listitem>
	  <para>This simultaneously enables all of the extensions to
          Haskell 98 described in <xref
83
          linkend="ghc-language-features"/>, except where otherwise
84
          noted. </para>
85
86
87
88
89
90
91
92
93
94
95
96
97

	  <para>New reserved words: <literal>forall</literal> (only in
	  types), <literal>mdo</literal>.</para>

	  <para>Other syntax stolen:
	      <replaceable>varid</replaceable>{<literal>&num;</literal>},
	      <replaceable>char</replaceable><literal>&num;</literal>,	    
	      <replaceable>string</replaceable><literal>&num;</literal>,    
	      <replaceable>integer</replaceable><literal>&num;</literal>,    
	      <replaceable>float</replaceable><literal>&num;</literal>,    
	      <replaceable>float</replaceable><literal>&num;&num;</literal>,    
	      <literal>(&num;</literal>, <literal>&num;)</literal>,	    
	      <literal>|)</literal>, <literal>{|</literal>.</para>
98
99
	</listitem>
      </varlistentry>
100

chak's avatar
chak committed
101
      <varlistentry>
102
103
104
105
106
	<term>
          <option>-ffi</option> and <option>-fffi</option>:
          <indexterm><primary><option>-ffi</option></primary></indexterm>
          <indexterm><primary><option>-fffi</option></primary></indexterm>
        </term>
chak's avatar
chak committed
107
108
109
110
111
	<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> 
112
113

	  <para>New reserved words: <literal>foreign</literal>.</para>
chak's avatar
chak committed
114
115
116
117
	</listitem>
      </varlistentry>

      <varlistentry>
118
119
120
121
	<term>
          <option>-fno-monomorphism-restriction</option>:
          <indexterm><primary><option>-fno-monomorphism-restriction</option></primary></indexterm>
        </term>
122
123
	<listitem>
	  <para> Switch off the Haskell 98 monomorphism restriction.
124
          Independent of the <option>-fglasgow-exts</option>
125
126
127
          flag. </para>
	</listitem>
      </varlistentry>
128

129
      <varlistentry>
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
	<term>
          <option>-fallow-overlapping-instances</option>
          <indexterm><primary><option>-fallow-overlapping-instances</option></primary></indexterm>
        </term>
	<term>
          <option>-fallow-undecidable-instances</option>
          <indexterm><primary><option>-fallow-undecidable-instances</option></primary></indexterm>
        </term>
	<term>
          <option>-fallow-incoherent-instances</option>
          <indexterm><primary><option>-fallow-incoherent-instances</option></primary></indexterm>
        </term>
	<term>
          <option>-fcontext-stack</option>
          <indexterm><primary><option>-fcontext-stack</option></primary></indexterm>
        </term>
146
	<listitem>
147
	  <para> See <xref linkend="instance-decls"/>.  Only relevant
148
149
150
          if you also use <option>-fglasgow-exts</option>.</para>
	</listitem>
      </varlistentry>
151

152
      <varlistentry>
153
154
155
156
	<term>
          <option>-finline-phase</option>
          <indexterm><primary><option>-finline-phase</option></primary></indexterm>
        </term>
157
	<listitem>
158
	  <para>See <xref linkend="rewrite-rules"/>.  Only relevant if
159
          you also use <option>-fglasgow-exts</option>.</para>
160
161
	</listitem>
      </varlistentry>
162

ross's avatar
ross committed
163
      <varlistentry>
164
165
166
167
	<term>
          <option>-farrows</option>
          <indexterm><primary><option>-farrows</option></primary></indexterm>
        </term>
ross's avatar
ross committed
168
	<listitem>
169
	  <para>See <xref linkend="arrow-notation"/>.  Independent of
ross's avatar
ross committed
170
          <option>-fglasgow-exts</option>.</para>
171
172
173
174
175
176
177
178

	  <para>New reserved words/symbols: <literal>rec</literal>,
	  <literal>proc</literal>, <literal>-&lt;</literal>,
	  <literal>&gt;-</literal>, <literal>-&lt;&lt;</literal>,
	  <literal>&gt;&gt;-</literal>.</para>

	  <para>Other syntax stolen: <literal>(|</literal>,
	  <literal>|)</literal>.</para>
ross's avatar
ross committed
179
180
181
	</listitem>
      </varlistentry>

182
      <varlistentry>
183
184
185
186
	<term>
          <option>-fgenerics</option>
          <indexterm><primary><option>-fgenerics</option></primary></indexterm>
        </term>
187
	<listitem>
188
	  <para>See <xref linkend="generic-classes"/>.  Independent of
189
          <option>-fglasgow-exts</option>.</para>
190
191
192
	</listitem>
      </varlistentry>

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
      <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>

	  <para>Even though you have not imported the Prelude, most of
          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>

	  <para>However, <option>-fno-implicit-prelude</option> does
	  change the handling of certain built-in syntax: see <xref
217
	  linkend="rebindable-syntax"/>.</para>
218
219
220
	</listitem>
      </varlistentry>

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
      <varlistentry>
	<term><option>-fimplicit-params</option></term>
	<listitem>
	  <para>Enables implicit parameters (see <xref
	  linkend="implicit-parameters"/>).  Currently also implied by 
	  <option>-fglasgow-exts</option>.</para>

	  <para>Syntax stolen:
	  <literal>?<replaceable>varid</replaceable></literal>,
	  <literal>%<replaceable>varid</replaceable></literal>.</para>
	</listitem>
      </varlistentry>

      <varlistentry>
	<term><option>-fscoped-type-variables</option></term>
	<listitem>
	  <para>Enables lexically-scoped type variables (see <xref
	  linkend="scoped-type-variables"/>).  Implied by
	  <option>-fglasgow-exts</option>.</para>
	</listitem>
      </varlistentry>

243
244
245
246
      <varlistentry>
	<term><option>-fth</option></term>
	<listitem>
	  <para>Enables Template Haskell (see <xref
247
	  linkend="template-haskell"/>).  Currently also implied by
248
	  <option>-fglasgow-exts</option>.</para>
249
250
251
252
253
254

	  <para>Syntax stolen: <literal>[|</literal>,
	  <literal>[e|</literal>, <literal>[p|</literal>,
	  <literal>[d|</literal>, <literal>[t|</literal>,
	  <literal>$(</literal>,
	  <literal>$<replaceable>varid</replaceable></literal>.</para>
255
256
257
	</listitem>
      </varlistentry>

258
    </variablelist>
259
  </sect1>
260

261
<!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS -->
262
<!--    included from primitives.sgml  -->
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<!-- &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
282
<filename>fptools/ghc/compiler/prelude/primops.txt.pp</filename>.
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
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.
346
347
348
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.
349
350
351
</para>

<para>
352
353
354
355
There are some restrictions on the use of primitive types:
<itemizedlist>
<listitem><para>The main restriction
is that you can't pass a primitive value to a polymorphic
356
357
358
359
360
361
362
363
364
365
366
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>
367
368
369
370
371
372
373
374
375
376
377
378
379
</listitem>
<listitem><para> You cannot bind a variable with an unboxed type
in a <emphasis>top-level</emphasis> binding.
</para></listitem>
<listitem><para> You cannot bind a variable with an unboxed type
in a <emphasis>recursive</emphasis> binding.
</para></listitem>
<listitem><para> You may bind unboxed variables in a (non-recursive,
non-top-level) pattern binding, but any such variable causes the entire
pattern-match
to become strict.  For example:
<programlisting>
  data Foo = Foo Int Int#
380

381
382
383
384
385
386
387
388
389
390
391
392
393
  f x = let (Foo a b, w) = ..rhs.. in ..body..
</programlisting>
Since <literal>b</literal> has type <literal>Int#</literal>, the entire pattern
match
is strict, and the program behaves as if you had written
<programlisting>
  data Foo = Foo Int Int#

  f x = case ..rhs.. of { (Foo a b, w) -> ..body.. }
</programlisting>
</para>
</listitem>
</itemizedlist>
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
</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
428
of the primitive operations listed in <literal>primops.txt.pp</literal> return unboxed
429
tuples.
430
431
In particular, the <literal>IO</literal> and <literal>ST</literal> monads use unboxed
tuples to avoid unnecessary allocation during sequences of operations.
432
433
434
435
436
437
438
439
</para>

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

<para>
440
Values of unboxed tuple types are subject to the same restrictions as
441
442
443
444
445
446
447
448
other unboxed types; i.e. they may not be stored in polymorphic data
structures or passed to polymorphic functions.

</para>
</listitem>
<listitem>

<para>
449
450
No variable can have an unboxed tuple type, nor may a constructor or function
argument have an unboxed tuple type.  The following are all illegal:
451
452
453


<programlisting>
454
  data Foo = Foo (# Int, Int #)
455

456
457
  f :: (# Int, Int #) -&#62; (# Int, Int #)
  f x = x
458

459
460
  g :: (# Int, Int #) -&#62; Int
  g (# a,b #) = a
461

462
  h x = let y = (# x,x #) in ...
463
464
465
466
467
468
</programlisting>
</para>
</listitem>
</itemizedlist>
</para>
<para>
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
The typical use of unboxed tuples is simply to return multiple values,
binding those multiple results with a <literal>case</literal> expression, thus:
<programlisting>
  f x y = (# x+1, y-1 #)
  g x = case f x x of { (# a, b #) -&#62; a + b }
</programlisting>
You can have an unboxed tuple in a pattern binding, thus
<programlisting>
  f x = let (# p,q #) = h x in ..body..
</programlisting>
If the types of <literal>p</literal> and <literal>q</literal> are not unboxed,
the resulting binding is lazy like any other Haskell pattern binding.  The 
above example desugars like this:
<programlisting>
  f x = let t = case h x o f{ (# p,q #) -> (p,q)
            p = fst t
            q = snd t
        in ..body..
</programlisting>
Indeed, the bindings can even be recursive.
489
490
491
492
493
</para>

</sect2>
</sect1>

rrt's avatar
rrt committed
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
<!-- ====================== 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>

532
533
      <para>For details on how GHC searches for source and interface
      files in the presence of hierarchical modules, see <xref
534
      linkend="search-path"/>.</para>
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553

      <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>
554
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.)
555
556
557
558
559
560
561
562
563
564
565
</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,
566
where <varname>v</varname> is the value that the key maps to.  Now consider the following definition:
567
568
569
</para>

<programlisting>
570
clunky env var1 var2 | ok1 &amp;&amp; ok2 = val1 + val2
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
| 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>
596
What is <function>clunky</function> doing? The guard <literal>ok1 &amp;&amp;
597
598
599
600
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
601
returned values to <varname>val1</varname> and <varname>val2</varname>
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
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>
ross's avatar
ross committed
646
The semantics should be clear enough.  The qualifiers are matched in order. 
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
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>
664
f x | [y] &lt;- x
665
    , y > 3
666
    , Just z &lt;- h y
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
    = ...
</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>
698
699
import Control.Monad.Fix

700
justOnes = mdo xs &lt;- Just (1:xs)
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
               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>
721
722
723
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).
724
725
726
727
728
729
730
731
732
733
</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>
734
735
736
737
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.)
738
739
740
741
742
743
744
745
746
</para></listitem>

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

<para>
747
748
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.
749
750
751
</para>

<para>
752
753
754
755
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.
756
757
</para>

758
759
760
</sect2>


761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
   <!-- ===================== 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>
780
   [ (x, y) | x &lt;- xs | y &lt;- ys ] 
781
782
783
784
785
786
787
788
789
790
791
792
</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>
793
794
   [ e | p1 &lt;- e11, p2 &lt;- e12, ... 
       | q1 &lt;- e21, q2 &lt;- e22, ... 
795
796
797
798
799
800
801
       ... 
   ] 
</programlisting>

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

<programlisting>
802
803
   [ e | ((p1,p2), (q1,q2), ...) &lt;- zipN [(p1,p2) | p1 &lt;- e11, p2 &lt;- e12, ...] 
                                         [(q1,q2) | q1 &lt;- e21, q2 &lt;- e22, ...] 
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
                                         ... 
   ] 
</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
828
            versions:
829
830
831

	    <itemizedlist>
	      <listitem>
832
833
834
835
		<para>An integer literal <literal>368</literal> means
                "<literal>fromInteger (368::Integer)</literal>", rather than
                "<literal>Prelude.fromInteger (368::Integer)</literal>".
</para> </listitem>	    
836

837
838
839
840
841
842
843
844
845
846
847
848
849
      <listitem><para>Fractional literals are handed in just the same way,
	  except that the translation is 
	      <literal>fromRational (3.68::Rational)</literal>.
</para> </listitem>	    

	  <listitem><para>The equality test in an overloaded numeric pattern
	      uses whatever <literal>(==)</literal> is in scope.
</para> </listitem>	    

	  <listitem><para>The subtraction operation, and the
	  greater-than-or-equal test, in <literal>n+k</literal> patterns
	      use whatever <literal>(-)</literal> and <literal>(>=)</literal> are in scope.
	      </para></listitem>
850
851

	      <listitem>
852
853
854
855
		<para>Negation (e.g. "<literal>- (f x)</literal>")
		means "<literal>negate (f x)</literal>", both in numeric
		patterns, and expressions.
	      </para></listitem>
856
857
858
859

	      <listitem>
	  <para>"Do" notation is translated using whatever
	      functions <literal>(>>=)</literal>,
860
861
862
	      <literal>(>>)</literal>, and <literal>fail</literal>,
	      are in scope (not the Prelude
	      versions).  List comprehensions, mdo (<xref linkend="mdo-notation"/>), and parallel array
863
	      comprehensions, are unaffected.  </para></listitem>
ross's avatar
ross committed
864
865

	      <listitem>
866
		<para>Arrow
ross's avatar
ross committed
867
868
869
870
		notation (see <xref linkend="arrow-notation"/>)
		uses whatever <literal>arr</literal>,
		<literal>(>>>)</literal>, <literal>first</literal>,
		<literal>app</literal>, <literal>(|||)</literal> and
871
872
873
874
875
		<literal>loop</literal> functions are in scope. But unlike the
		other constructs, the types of these functions must match the
		Prelude types very closely.  Details are in flux; if you want
		to use this, ask!
	      </para></listitem>
876
	    </itemizedlist>
877
878
879
880
881
882
883
884
885
886
887
888
889
In all cases (apart from arrow notation), the static semantics should be that of the desugared form,
even if that is a little unexpected. For emample, the 
static semantics of the literal <literal>368</literal>
is exactly that of <literal>fromInteger (368::Integer)</literal>; it's fine for
<literal>fromInteger</literal> to have any of the types:
<programlisting>
fromInteger :: Integer -> Integer
fromInteger :: forall a. Foo a => Integer -> a
fromInteger :: Num a => a -> Integer
fromInteger :: Integer -> Bool -> Bool
</programlisting>
</para>
	        
ross's avatar
ross committed
890
891
892
893
	     <para>Be warned: this is an experimental facility, with
	     fewer checks than usual.  Use <literal>-dcore-lint</literal>
	     to typecheck the desugared program.  If Core Lint is happy
	     you should be all right.</para>
894
895
896
897

</sect2>
</sect1>

rrt's avatar
rrt committed
898

899
900
901
<!-- TYPE SYSTEM EXTENSIONS -->
<sect1 id="type-extensions">
<title>Type system extensions</title>
rrt's avatar
rrt committed
902

903
904
905
906
907

<sect2>
<title>Data types and type synonyms</title>

<sect3 id="nullary-types">
908
909
<title>Data types with no constructors</title>

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

913
914
915
916
<programlisting>
  data S      -- S :: *
  data T a    -- T :: * -> *
</programlisting>
917

918
<para>Syntactically, the declaration lacks the "= constrs" part.  The 
919
920
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
921
(see <xref linkend="sec-kinding"/>).</para>
922
923
924

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

927
<sect3 id="infix-tycons">
928
<title>Infix type constructors, classes, and type variables</title>
929
930

<para>
931
932
GHC allows type constructors, classes, and type variables to be operators, and
to be written infix, very much like expressions.  More specifically:
933
934
<itemizedlist>
<listitem><para>
935
  A type constructor or class can be an operator, beginning with a colon; e.g. <literal>:*:</literal>.
936
937
938
  The lexical syntax is the same as that for data constructors.
  </para></listitem>
<listitem><para>
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
  Data type and type-synonym declarations can be written infix, parenthesised
  if you want further arguments.  E.g.
<screen>
  data a :*: b = Foo a b
  type a :+: b = Either a b
  class a :=: b where ...

  data (a :**: b) x = Baz a b x
  type (a :++: b) y = Either (a,b) y
</screen>
  </para></listitem>
<listitem><para>
  Types, and class constraints, can be written infix.  For example
  <screen>
	x :: Int :*: Bool
        f :: (a :=: b) => a -> b
  </screen>
956
  </para></listitem>
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
<listitem><para>
  A type variable can be an (unqualified) operator e.g. <literal>+</literal>.
  The lexical syntax is the same as that for variable operators, excluding "(.)",
  "(!)", and "(*)".  In a binding position, the operator must be
  parenthesised.  For example:
<programlisting>
   type T (+) = Int + Int
   f :: T Either
   f = Left 3
 
   liftA2 :: Arrow (~>)
	  => (a -> b -> c) -> (e ~> a) -> (e ~> b) -> (e ~> c)
   liftA2 = ...
</programlisting>
  </para></listitem>
972
973
974
975
976
977
<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>
978
  Fixities may be declared for type constructors, or classes, just as for data constructors.  However,
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
  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>

</itemizedlist>
</para>
994
</sect3>
995

996
997
<sect3 id="type-synonyms">
<title>Liberalised type synonyms</title>
998
999

<para>
ross's avatar
ross committed
1000
Type synonyms are like macros at the type level, and
1001
1002
GHC does validity checking on types <emphasis>only after expanding type synonyms</emphasis>.
That means that GHC can be very much more liberal about type synonyms than Haskell 98:
1003
<itemizedlist>
1004
1005
1006
1007
<listitem> <para>You can write a <literal>forall</literal> (including overloading)
in a type synonym, thus:
<programlisting>
  type Discard a = forall b. Show b => a -> b -> (a, String)
1008

1009
1010
  f :: Discard a
  f x y = (x, show y)
1011

1012
1013
1014
  g :: Discard Int -> (Int,Bool)    -- A rank-2 type
  g f = f Int True
</programlisting>
1015
</para>
1016
</listitem>
1017

1018
1019
1020
1021
<listitem><para>
You can write an unboxed tuple in a type synonym:
<programlisting>
  type Pr = (# Int, Int #)
1022

1023
1024
1025
1026
1027
1028
1029
  h :: Int -> Pr
  h x = (# x, x #)
</programlisting>
</para></listitem>

<listitem><para>
You can apply a type synonym to a forall type:
1030
<programlisting>
1031
1032
1033
  type Foo a = a -> a -> Bool
 
  f :: Foo (forall b. b->b)
1034
</programlisting>
1035
1036
1037
1038
1039
After expanding the synonym, <literal>f</literal> has the legal (in GHC) type:
<programlisting>
  f :: (forall b. b->b) -> (forall b. b->b) -> Bool
</programlisting>
</para></listitem>
1040

1041
1042
1043
1044
1045
1046
1047
1048
<listitem><para>
You can apply a type synonym to a partially applied type synonym:
<programlisting>
  type Generic i o = forall x. i x -> o x
  type Id x = x
  
  foo :: Generic Id []
</programlisting>
ross's avatar
ross committed
1049
After expanding the synonym, <literal>foo</literal> has the legal (in GHC) type:
1050
1051
1052
1053
<programlisting>
  foo :: forall x. x -> [x]
</programlisting>
</para></listitem>
1054

1055
1056
</itemizedlist>
</para>
rrt's avatar
rrt committed
1057

1058
<para>
1059
1060
GHC currently does kind checking before expanding synonyms (though even that
could be changed.)
1061
1062
</para>
<para>
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
After expanding type synonyms, GHC does validity checking on types, looking for
the following mal-formedness which isn't detected simply by kind checking:
<itemizedlist>
<listitem><para>
Type constructor applied to a type involving for-alls.
</para></listitem>
<listitem><para>
Unboxed tuple on left of an arrow.
</para></listitem>
<listitem><para>
Partially-applied type synonym.
</para></listitem>
</itemizedlist>
So, for example,
this will be rejected:
1078
<programlisting>
1079
  type Pr = (# Int, Int #)
rrt's avatar
rrt committed
1080

1081
1082
1083
1084
  h :: Pr -> Int
  h x = ...
</programlisting>
because GHC does not allow  unboxed tuples on the left of a function arrow.
1085
</para>
1086
</sect3>
rrt's avatar
rrt committed
1087
1088


1089
1090
1091
<sect3 id="existential-quantification">
<title>Existentially quantified data constructors
</title>
rrt's avatar
rrt committed
1092

1093
<para>
1094
The idea of using existential quantification in data type declarations
1095
1096
1097
1098
1099
1100
was suggested by Perry, and implemented in Hope+ (Nigel Perry, <emphasis>The Implementation
of Practical Functional Programming Languages</emphasis>, PhD Thesis, University of
London, 1991). It was later formalised by Laufer and Odersky
(<emphasis>Polymorphic type inference and abstract data types</emphasis>,
TOPLAS, 16(5), pp1411-1430, 1994).
It's been in Lennart
1101
Augustsson's <command>hbc</command> Haskell compiler for several years, and
1102
1103
proved very useful.  Here's the idea.  Consider the declaration:
</para>
rrt's avatar
rrt committed
1104

1105
<para>
rrt's avatar
rrt committed
1106

1107
<programlisting>
1108
1109
  data Foo = forall a. MkFoo a (a -> Bool)
           | Nil
1110
</programlisting>
rrt's avatar
rrt committed
1111

1112
</para>
rrt's avatar
rrt committed
1113

1114
<para>
1115
1116
The data type <literal>Foo</literal> has two constructors with types:
</para>
rrt's avatar
rrt committed
1117

1118
<para>
rrt's avatar
rrt committed
1119

1120
<programlisting>
1121
1122
  MkFoo :: forall a. a -> (a -> Bool) -> Foo
  Nil   :: Foo
1123
</programlisting>
rrt's avatar
rrt committed
1124

1125
</para>
rrt's avatar
rrt committed
1126

1127
1128
1129
1130
1131
<para>
Notice that the type variable <literal>a</literal> in the type of <function>MkFoo</function>
does not appear in the data type itself, which is plain <literal>Foo</literal>.
For example, the following expression is fine:
</para>
rrt's avatar
rrt committed
1132

1133
<para>
rrt's avatar
rrt committed
1134

1135
<programlisting>
1136
  [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
1137
</programlisting>
rrt's avatar
rrt committed
1138

1139
</para>
rrt's avatar
rrt committed
1140

1141
1142
1143
1144
1145
<para>
Here, <literal>(MkFoo 3 even)</literal> packages an integer with a function
<function>even</function> that maps an integer to <literal>Bool</literal>; and <function>MkFoo 'c'
isUpper</function> packages a character with a compatible function.  These
two things are each of type <literal>Foo</literal> and can be put in a list.
1146
</para>
rrt's avatar
rrt committed
1147

1148
<para>
1149
1150
What can we do with a value of type <literal>Foo</literal>?.  In particular,
what happens when we pattern-match on <function>MkFoo</function>?
1151
</para>
rrt's avatar
rrt committed
1152

1153
<para>
rrt's avatar
rrt committed
1154

1155
<programlisting>
1156
  f (MkFoo val fn) = ???
1157
</programlisting>
rrt's avatar
rrt committed
1158

1159
</para>
rrt's avatar
rrt committed
1160

1161
<para>
1162
1163
1164
Since all we know about <literal>val</literal> and <function>fn</function> is that they
are compatible, the only (useful) thing we can do with them is to
apply <function>fn</function> to <literal>val</literal> to get a boolean.  For example:
1165
</para>
rrt's avatar
rrt committed
1166

1167
<para>
rrt's avatar
rrt committed
1168

1169
<programlisting>
1170
1171
  f :: Foo -> Bool
  f (MkFoo val fn) = fn val
1172
</programlisting>
rrt's avatar
rrt committed
1173

1174
</para>
rrt's avatar
rrt committed
1175

1176
<para>
1177
1178
1179
1180
1181
What this allows us to do is to package heterogenous values
together with a bunch of functions that manipulate them, and then treat
that collection of packages in a uniform manner.  You can express
quite a bit of object-oriented-like programming this way.
</para>
rrt's avatar
rrt committed
1182

1183
1184
1185
<sect4 id="existential">
<title>Why existential?
</title>
rrt's avatar
rrt committed
1186

1187
1188
1189
<para>
What has this to do with <emphasis>existential</emphasis> quantification?
Simply that <function>MkFoo</function> has the (nearly) isomorphic type
1190
</para>
rrt's avatar
rrt committed
1191

1192
<para>
rrt's avatar
rrt committed
1193

1194
<programlisting>
1195
  MkFoo :: (exists a . (a, a -> Bool)) -> Foo
1196
</programlisting>
rrt's avatar
rrt committed
1197

1198
</para>
rrt's avatar
rrt committed
1199

1200
<para>
1201
1202
1203
1204
But Haskell programmers can safely think of the ordinary
<emphasis>universally</emphasis> quantified type given above, thereby avoiding
adding a new existential quantification construct.
</para>
rrt's avatar
rrt committed
1205

1206
</sect4>
rrt's avatar
rrt committed
1207

1208
1209
<sect4>
<title>Type classes</title>
rrt's avatar
rrt committed
1210

1211
<para>
1212
An easy extension (implemented in <command>hbc</command>) is to allow
1213
1214
arbitrary contexts before the constructor.  For example:
</para>
rrt's avatar
rrt committed
1215

1216
<para>
rrt's avatar
rrt committed
1217

1218
<programlisting>
1219
1220
data Baz = forall a. Eq a => Baz1 a a
         | forall b. Show b => Baz2 b (b -> b)
1221
</programlisting>
rrt's avatar
rrt committed
1222

1223
</para>
rrt's avatar
rrt committed
1224

1225
1226
1227
<para>
The two constructors have the types you'd expect:
</para>
rrt's avatar
rrt committed
1228

1229
<para>
rrt's avatar
rrt committed
1230

1231
<programlisting>
1232
1233
Baz1 :: forall a. Eq a => a -> a -> Baz
Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
1234
</programlisting>
rrt's avatar
rrt committed
1235

1236
</para>
rrt's avatar
rrt committed
1237

1238
<para>
1239
1240
1241
1242
1243
But when pattern matching on <function>Baz1</function> the matched values can be compared
for equality, and when pattern matching on <function>Baz2</function> the first matched
value can be converted to a string (as well as applying the function to it).
So this program is legal:
</para>
rrt's avatar
rrt committed
1244

1245
<para>
rrt's avatar
rrt committed
1246

1247
<programlisting>
1248
1249
1250
1251
  f :: Baz -> String
  f (Baz1 p q) | p == q    = "Yes"
               | otherwise = "No"
  f (Baz2 v fn)            = show (fn v)
1252
</programlisting>
rrt's avatar
rrt committed
1253

1254
</para>
rrt's avatar
rrt committed
1255

1256
<para>
1257
1258
1259
1260
Operationally, in a dictionary-passing implementation, the
constructors <function>Baz1</function> and <function>Baz2</function> must store the
dictionaries for <literal>Eq</literal> and <literal>Show</literal> respectively, and
extract it on pattern matching.
1261
</para>
rrt's avatar
rrt committed
1262

1263
<para>
1264
1265
Notice the way that the syntax fits smoothly with that used for
universal quantification earlier.
1266
</para>
rrt's avatar
rrt committed
1267

1268
</sect4>
rrt's avatar
rrt committed
1269

1270
1271
<sect4>
<title>Restrictions</title>
rrt's avatar
rrt committed
1272

1273
<para>
1274
1275
There are several restrictions on the ways in which existentially-quantified
constructors can be use.
1276
</para>
rrt's avatar
rrt committed
1277

1278
<para>
rrt's avatar
rrt committed
1279

1280
<itemizedlist>
1281
<listitem>
rrt's avatar
rrt committed
1282

1283
<para>
1284
1285
1286
1287
 When pattern matching, each pattern match introduces a new,
distinct, type for each existential type variable.  These types cannot
be unified with any other type, nor can they escape from the scope of
the pattern match.  For example, these fragments are incorrect:
rrt's avatar
rrt committed
1288
1289


1290
<programlisting>
1291
f1 (MkFoo a f) = a
1292
</programlisting>
rrt's avatar
rrt committed
1293
1294


1295
1296
1297
Here, the type bound by <function>MkFoo</function> "escapes", because <literal>a</literal>
is the result of <function>f1</function>.  One way to see why this is wrong is to
ask what type <function>f1</function> has:
rrt's avatar
rrt committed
1298
1299


1300
<programlisting>
1301
  f1 :: Foo -> a             -- Weird!
1302
</programlisting>
rrt's avatar
rrt committed
1303
1304


1305
1306
What is this "<literal>a</literal>" in the result type? Clearly we don't mean
this:
rrt's avatar
rrt committed
1307
1308


1309
<programlisting>
1310
  f1 :: forall a. Foo -> a   -- Wrong!
1311
</programlisting>
rrt's avatar
rrt committed
1312
1313


1314
The original program is just plain wrong.  Here's another sort of error
rrt's avatar
rrt committed
1315
1316


1317
<programlisting>
1318
  f2 (Baz1 a b) (Baz1 p q) = a==q
1319
</programlisting>
rrt's avatar
rrt committed
1320
1321


1322
1323
1324
It's ok to say <literal>a==b</literal> or <literal>p==q</literal>, but
<literal>a==q</literal> is wrong because it equates the two distinct types arising
from the two <function>Baz1</function> constructors.
rrt's avatar
rrt committed
1325
1326


1327
1328
1329
</para>
</listitem>
<listitem>
rrt's avatar
rrt committed
1330

1331
<para>
1332
1333
1334
You can't pattern-match on an existentially quantified
constructor in a <literal>let</literal> or <literal>where</literal> group of
bindings. So this is illegal:
rrt's avatar
rrt committed
1335
1336


1337
<programlisting>
1338
  f3 x = a==b where { Baz1 a b = x }
1339
</programlisting>
rrt's avatar
rrt committed
1340

1341
Instead, use a <literal>case</literal> expression:
rrt's avatar
rrt committed
1342

1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
<programlisting>
  f3 x = case x of Baz1 a b -> a==b
</programlisting>

In general, you can only pattern-match
on an existentially-quantified constructor in a <literal>case</literal> expression or
in the patterns of a function definition.

The reason for this restriction is really an implementation one.
Type-checking binding groups is already a nightmare without
existentials complicating the picture.  Also an existential pattern
binding at the top level of a module doesn't make sense, because it's
not clear how to prevent the existentially-quantified type "escaping".
So for now, there's a simple-to-state restriction.  We'll see how
annoying it is.

</para>
</listitem>
<listitem>

<para>
You can't use existential quantification for <literal>newtype</literal>
declarations.  So this is illegal:
rrt's avatar
rrt committed
1366
1367


1368
<programlisting>
1369
  newtype T = forall a. Ord a => MkT a
1370
</programlisting>
rrt's avatar
rrt committed
1371
1372


1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
Reason: a value of type <literal>T</literal> must be represented as a
pair of a dictionary for <literal>Ord t</literal> and a value of type
<literal>t</literal>.  That contradicts the idea that
<literal>newtype</literal> should have no concrete representation.
You can get just the same efficiency and effect by using
<literal>data</literal> instead of <literal>newtype</literal>.  If
there is no overloading involved, then there is more of a case for
allowing an existentially-quantified <literal>newtype</literal>,
because the <literal>data</literal> version does carry an
implementation cost, but single-field existentially quantified
constructors aren't much use.  So the simple restriction (no
existential stuff on <literal>newtype</literal>) stands, unless there
are convincing reasons to change it.
1386
1387
1388
1389
1390


</para>
</listitem>
<listitem>
1391

1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
<para>
 You can't use <literal>deriving</literal> to define instances of a
data type with existentially quantified data constructors.

Reason: in most cases it would not make sense. For example:&num;

<programlisting>
data T = forall a. MkT [a] deriving( Eq )
</programlisting>

To derive <literal>Eq</literal> in the standard way we would need to have equality
between the single component of two <function>MkT</function> constructors:
rrt's avatar
rrt committed
1404

1405
1406
1407
1408
<programlisting>
instance Eq T where
  (MkT a) == (MkT b) = ???
</