glasgow_exts.xml 260 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>The language option flag control what variation of the language are
42
    permitted.  Leaving out all of them gives you standard Haskell
43
    98.</para>
44

45
46
    <para>Generally speaking, all the language options are introduced by "<option>-X</option>", 
    e.g. <option>-XTemplateHaskell</option>.
47
48
49
    </para>

   <para> All the language options can be turned off by using the prefix "<option>No</option>"; 
50
      e.g. "<option>-XNoTemplateHaskell</option>".</para>
51
52
53
54
55

   <para> Language options recognised by Cabal can also be enabled using the <literal>LANGUAGE</literal> pragma,
   thus <literal>{-# LANGUAGE TemplateHaskell #-}</literal> (see <xref linkend="language-pragma"/>>). </para>

    <para>Turning on an option that enables special syntax
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    <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>

83
    <variablelist>
84

85
      <varlistentry>
86
87
88
89
	<term>
          <option>-fglasgow-exts</option>:
          <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
        </term>
90
91
92
	<listitem>
	  <para>This simultaneously enables all of the extensions to
          Haskell 98 described in <xref
93
          linkend="ghc-language-features"/>, except where otherwise
94
95
          noted. We are trying to move away from this portmanteau flag, 
	  and towards enabling features individaully.</para>
96
97
98
99
100
101
102
103
104
105
106
107
108

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

	  <para>Implies these specific language options: 
111
112
113
114
115
	    <option>-XForeignFunctionInterface</option>,
	    <option>-XImplicitParams</option>,
	    <option>-XScopedTypeVariables</option>,
	    <option>-XGADTs</option>, 
	    <option>-XTypeFamilies</option>. </para>
116
117
	</listitem>
      </varlistentry>
118

chak's avatar
chak committed
119
      <varlistentry>
120
	<term>
121
122
          <option>-XForeignFunctionInterface</option>:
          <indexterm><primary><option>-XForeignFunctionInterface</option></primary></indexterm>
123
        </term>
chak's avatar
chak committed
124
125
	<listitem>
	  <para>This option enables the language extension defined in the
Ian Lynagh's avatar
Ian Lynagh committed
126
	  Haskell 98 Foreign Function Interface Addendum.</para>
127
128

	  <para>New reserved words: <literal>foreign</literal>.</para>
chak's avatar
chak committed
129
130
131
132
	</listitem>
      </varlistentry>

      <varlistentry>
133
	<term>
134
          <option>-XMonomorphismRestriction</option>,<option>-XMonoPatBinds</option>:
135
136
        </term>
	<listitem>
Ian Lynagh's avatar
Ian Lynagh committed
137
	  <para> These two flags control how generalisation is done.
138
	    See <xref linkend="monomorphism"/>.
139
140
141
142
143
144
          </para>
	</listitem>
      </varlistentry>

      <varlistentry>
	<term>
145
146
          <option>-XExtendedDefaultRules</option>:
          <indexterm><primary><option>-XExtendedDefaultRules</option></primary></indexterm>
147
148
149
150
151
152
153
154
        </term>
	<listitem>
	  <para> Use GHCi's extended default rules in a regular module (<xref linkend="extended-default-rules"/>).
          Independent of the <option>-fglasgow-exts</option>
          flag. </para>
	</listitem>
      </varlistentry>

155
      <varlistentry>
156
	<term>
157
158
          <option>-XOverlappingInstances</option>
          <indexterm><primary><option>-XOverlappingInstances</option></primary></indexterm>
159
160
        </term>
	<term>
161
162
          <option>-XUndecidableInstances</option>
          <indexterm><primary><option>-XUndecidableInstances</option></primary></indexterm>
163
164
        </term>
	<term>
165
166
          <option>-XIncoherentInstances</option>
          <indexterm><primary><option>-XIncoherentInstances</option></primary></indexterm>
167
168
        </term>
	<term>
169
          <option>-fcontext-stack=N</option>
170
171
          <indexterm><primary><option>-fcontext-stack</option></primary></indexterm>
        </term>
172
	<listitem>
173
	  <para> See <xref linkend="instance-decls"/>.  Only relevant
174
175
176
          if you also use <option>-fglasgow-exts</option>.</para>
	</listitem>
      </varlistentry>
177

178
      <varlistentry>
179
180
181
182
	<term>
          <option>-finline-phase</option>
          <indexterm><primary><option>-finline-phase</option></primary></indexterm>
        </term>
183
	<listitem>
184
	  <para>See <xref linkend="rewrite-rules"/>.  Only relevant if
185
          you also use <option>-fglasgow-exts</option>.</para>
186
187
	</listitem>
      </varlistentry>
188

ross's avatar
ross committed
189
      <varlistentry>
190
	<term>
191
192
          <option>-XArrows</option>
          <indexterm><primary><option>-XArrows</option></primary></indexterm>
193
        </term>
ross's avatar
ross committed
194
	<listitem>
195
	  <para>See <xref linkend="arrow-notation"/>.  Independent of
ross's avatar
ross committed
196
          <option>-fglasgow-exts</option>.</para>
197
198
199
200
201
202
203
204

	  <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
205
206
207
	</listitem>
      </varlistentry>

208
      <varlistentry>
209
	<term>
210
211
          <option>-XGenerics</option>
          <indexterm><primary><option>-XGenerics</option></primary></indexterm>
212
        </term>
213
	<listitem>
214
	  <para>See <xref linkend="generic-classes"/>.  Independent of
215
          <option>-fglasgow-exts</option>.</para>
216
217
218
	</listitem>
      </varlistentry>

219
      <varlistentry>
220
	<term><option>-XNoImplicitPrelude</option></term>
221
	<listitem>
222
	  <para><indexterm><primary>-XNoImplicitPrelude
223
224
225
          option</primary></indexterm> GHC normally imports
          <filename>Prelude.hi</filename> files for you.  If you'd
          rather it didn't, then give it a
226
          <option>-XNoImplicitPrelude</option> option.  The idea is
227
228
229
230
231
232
233
234
235
236
237
238
239
240
          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>

241
	  <para>However, <option>-XNoImplicitPrelude</option> does
242
	  change the handling of certain built-in syntax: see <xref
243
	  linkend="rebindable-syntax"/>.</para>
244
245
246
	</listitem>
      </varlistentry>

247
      <varlistentry>
248
	<term><option>-XImplicitParams</option></term>
249
250
251
252
253
254
255
256
257
258
259
	<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>

260
      <varlistentry>
261
	<term><option>-XOverloadedStrings</option></term>
262
263
264
265
266
267
	<listitem>
	  <para>Enables overloaded string literals (see <xref
	  linkend="overloaded-strings"/>).</para>
	</listitem>
      </varlistentry>

268
      <varlistentry>
269
	<term><option>-XScopedTypeVariables</option></term>
270
271
272
273
274
275
276
	<listitem>
	  <para>Enables lexically-scoped type variables (see <xref
	  linkend="scoped-type-variables"/>).  Implied by
	  <option>-fglasgow-exts</option>.</para>
	</listitem>
      </varlistentry>

277
      <varlistentry>
278
	<term><option>-XTemplateHaskell</option></term>
279
280
	<listitem>
	  <para>Enables Template Haskell (see <xref
281
282
	  linkend="template-haskell"/>).  This flag must
	  be given explicitly; it is no longer implied by
283
	  <option>-fglasgow-exts</option>.</para>
284
285
286
287
288
289

	  <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>
290
291
292
	</listitem>
      </varlistentry>

293
294
295
296
297
298
299
300
301
302
303
      <varlistentry>
	<term><option>-XQuasiQuotes</option></term>
	<listitem>
	  <para>Enables quasiquotation (see <xref
	  linkend="th-quasiquotation"/>).</para>

	  <para>Syntax stolen:
	  <literal>[:<replaceable>varid</replaceable>|</literal>.</para>
	</listitem>
      </varlistentry>

304
    </variablelist>
305
  </sect1>
306

307
<!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS -->
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
<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
326
<filename>fptools/ghc/compiler/prelude/primops.txt.pp</filename>.
327
328
329
330
331
332
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
333
      url="http://www.haskell.org/ghc/docs/papers/core.ps.gz">External
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
	 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.
390
391
392
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.
393
394
395
</para>

<para>
396
397
398
399
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
400
401
402
403
404
405
406
407
408
409
410
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>
411
</listitem>
412
413
414
415
416
417
418
<listitem><para> You cannot define a newtype whose representation type
(the argument type of the data constructor) is an unboxed type.  Thus,
this is illegal:
<programlisting>
  newtype A = MkA Int#
</programlisting>
</para></listitem>
419
420
421
422
423
424
425
426
427
428
429
430
<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#
431

432
433
434
435
436
437
438
439
440
441
442
443
444
  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>
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
</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
479
of the primitive operations listed in <literal>primops.txt.pp</literal> return unboxed
480
tuples.
481
482
In particular, the <literal>IO</literal> and <literal>ST</literal> monads use unboxed
tuples to avoid unnecessary allocation during sequences of operations.
483
484
485
486
487
488
489
490
</para>

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

<para>
491
Values of unboxed tuple types are subject to the same restrictions as
492
493
494
495
496
497
498
499
other unboxed types; i.e. they may not be stored in polymorphic data
structures or passed to polymorphic functions.

</para>
</listitem>
<listitem>

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


<programlisting>
505
  data Foo = Foo (# Int, Int #)
506

507
508
  f :: (# Int, Int #) -&#62; (# Int, Int #)
  f x = x
509

510
511
  g :: (# Int, Int #) -&#62; Int
  g (# a,b #) = a
512

513
  h x = let y = (# x,x #) in ...
514
515
516
517
518
519
</programlisting>
</para>
</listitem>
</itemizedlist>
</para>
<para>
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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.
540
541
542
543
544
</para>

</sect2>
</sect1>

rrt's avatar
rrt committed
545

546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
<!-- ====================== 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>

583
584
      <para>For details on how GHC searches for source and interface
      files in the presence of hierarchical modules, see <xref
585
      linkend="search-path"/>.</para>
586
587

      <para>GHC comes with a large collection of libraries arranged
588
589
590
591
592
      hierarchically; see the accompanying <ulink
      url="../libraries/index.html">library
      documentation</ulink>.  More libraries to install are available
      from <ulink
      url="http://hackage.haskell.org/packages/hackage.html">HackageDB</ulink>.</para>
593
594
595
596
597
598
599
600
601
    </sect2>

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

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

<para>
<indexterm><primary>Pattern guards (Glasgow extension)</primary></indexterm>
602
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.)
603
604
605
606
607
608
609
610
611
612
613
</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,
614
where <varname>v</varname> is the value that the key maps to.  Now consider the following definition:
615
616
617
</para>

<programlisting>
618
clunky env var1 var2 | ok1 &amp;&amp; ok2 = val1 + val2
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
| 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>
644
What is <function>clunky</function> doing? The guard <literal>ok1 &amp;&amp;
645
646
647
648
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
649
returned values to <varname>val1</varname> and <varname>val2</varname>
650
651
652
653
654
655
656
657
658
659
660
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>
661
clunky env var1 var2 = case lookup env var1 of
662
663
664
665
666
  Nothing -&gt; fail
  Just val1 -&gt; case lookup env var2 of
    Nothing -&gt; fail
    Just val2 -&gt; val1 + val2
where
Simon Marlow's avatar
Simon Marlow committed
667
  fail = var1 + var2
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
</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>
686
clunky env var1 var2
687
688
689
690
691
692
693
  | 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
694
The semantics should be clear enough.  The qualifiers are matched in order. 
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
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>
712
f x | [y] &lt;- x
713
    , y > 3
714
    , Just z &lt;- h y
715
716
717
718
719
720
721
    = ...
</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>
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
</sect2>

    <!-- ===================== View patterns ===================  -->

<sect2 id="view-patterns">
<title>View patterns
</title>

<para>
View patterns are enabled by the flag <literal>-XViewPatterns</literal>.
More information and examples of view patterns can be found on the
<ulink url="http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns">Wiki
page</ulink>.
</para>

<para>
View patterns are somewhat like pattern guards that can be nested inside
of other patterns.  They are a convenient way of pattern-matching
against values of abstract types. For example, in a programming language
implementation, we might represent the syntax of the types of the
language as follows:

<programlisting>
type Typ
 
data TypView = Unit
             | Arrow Typ Typ

view :: Type -> TypeView

-- additional operations for constructing Typ's ...
</programlisting>

The representation of Typ is held abstract, permitting implementations
to use a fancy representation (e.g., hash-consing to managage sharing).

Without view patterns, using this signature a little inconvenient: 
<programlisting>
size :: Typ -> Integer
size t = case view t of
  Unit -> 1
  Arrow t1 t2 -> size t1 + size t2
</programlisting>

It is necessary to iterate the case, rather than using an equational
function definition. And the situation is even worse when the matching
against <literal>t</literal> is buried deep inside another pattern.
</para>

<para>
View patterns permit calling the view function inside the pattern and
matching against the result: 
<programlisting>
size (view -> Unit) = 1
size (view -> Arrow t1 t2) = size t1 + size t2
</programlisting>

That is, we add a new form of pattern, written
<replaceable>expression</replaceable> <literal>-></literal>
<replaceable>pattern</replaceable> that means "apply the expression to
whatever we're trying to match against, and then match the result of
that application against the pattern". The expression can be any Haskell
expression of function type, and view patterns can be used wherever
patterns are used.
</para>

<para>
The semantics of a pattern <literal>(</literal>
<replaceable>exp</replaceable> <literal>-></literal>
<replaceable>pat</replaceable> <literal>)</literal> are as follows:

<itemizedlist>

<listitem> Scoping:

<para>The variables bound by the view pattern are the variables bound by
<replaceable>pat</replaceable>.
</para>

<para>
Any variables in <replaceable>exp</replaceable> are bound occurrences,
but variables bound "to the left" in a pattern are in scope.  This
feature permits, for example, one argument to a function to be used in
the view of another argument.  For example, the function
<literal>clunky</literal> from <xref linkend="pattern-guards" /> can be
written using view patterns as follows:

<programlisting>
clunky env (lookup env -> Just val1) (lookup env -> Just val2) = val1 + val2
...other equations for clunky...
</programlisting>
</para>

<para>
More precisely, the scoping rules are: 
<itemizedlist>
<listitem>
<para>
In a single pattern, variables bound by patterns to the left of a view
pattern expression are in scope. For example:
<programlisting>
example :: Maybe ((String -> Integer,Integer), String) -> Bool
example Just ((f,_), f -> 4) = True
</programlisting>

Additionally, in function definitions, variables bound by matching earlier curried
arguments may be used in view pattern expressions in later arguments:
<programlisting>
example :: (String -> Integer) -> String -> Bool
example f (f -> 4) = True
</programlisting>
That is, the scoping is the same as it would be if the curried arguments
were collected into a tuple.  
</para>
</listitem>

<listitem>
<para>
In mutually recursive bindings, such as <literal>let</literal>,
<literal>where</literal>, or the top level, view patterns in one
declaration may not mention variables bound by other declarations.  That
is, each declaration must be self-contained.  For example, the following
program is not allowed:
<programlisting>
let {(x -> y) = e1 ;
     (y -> x) = e2 } in x
</programlisting>

(We may lift this
restriction in the future; the only cost is that type checking patterns
would get a little more complicated.)  


</para>
</listitem>
</itemizedlist>

</para>
</listitem>

<listitem><para> Typing: If <replaceable>exp</replaceable> has type
<replaceable>T1</replaceable> <literal>-></literal>
<replaceable>T2</replaceable> and <replaceable>pat</replaceable> matches
a <replaceable>T2</replaceable>, then the whole view pattern matches a
<replaceable>T1</replaceable>.
</para></listitem>

<listitem><para> Matching: To the equations in Section 3.17.3 of the
<ulink url="http://www.haskell.org/onlinereport/">Haskell 98
Report</ulink>, add the following:
<programlisting>
case v of { (e -> p) -> e1 ; _ -> e2 } 
 = 
case (e v) of { p -> e1 ; _ -> e2 }
</programlisting>
That is, to match a variable <replaceable>v</replaceable> against a pattern
<literal>(</literal> <replaceable>exp</replaceable>
<literal>-></literal> <replaceable>pat</replaceable>
<literal>)</literal>, evaluate <literal>(</literal>
<replaceable>exp</replaceable> <replaceable> v</replaceable>
<literal>)</literal> and match the result against
<replaceable>pat</replaceable>.  
</para></listitem>

<listitem><para> Efficiency: When the same view function is applied in
multiple branches of a function definition or a case expression (e.g.,
in <literal>size</literal> above), GHC makes an attempt to collect these
applications into a single nested case expression, so that the view
function is only applied once.  Pattern compilation in GHC follows the
matrix algorithm described in Chapter 4 of <ulink
url="http://research.microsoft.com/~simonpj/Papers/slpj-book-1987/">The
Implementation of Functional Programming Languages</ulink>.  When the
top rows of the first column of a matrix are all view patterns with the
"same" expression, these patterns are transformed into a single nested
case.  This includes, for example, adjacent view patterns that line up
in a tuple, as in
<programlisting>
f ((view -> A, p1), p2) = e1
f ((view -> B, p3), p4) = e2
</programlisting>
</para>

<para> The current notion of when two view pattern expressions are "the
same" is very restricted: it is not even full syntactic equality.
However, it does include variables, literals, applications, and tuples;
e.g., two instances of <literal>view ("hi", "there")</literal> will be
collected.  However, the current implementation does not compare up to
alpha-equivalence, so two instances of <literal>(x, view x ->
y)</literal> will not be coalesced.
</para>

</listitem>

</itemizedlist>
</para>

918
919
920
921
922
923
924
925
926
</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
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
927
928
<ulink url="http://citeseer.ist.psu.edu/erk02recursive.html">A recursive do for Haskell</ulink>,
by Levent Erkok, John Launchbury,
929
Haskell Workshop 2002, pages: 29-37. Pittsburgh, Pennsylvania. 
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
930
931
This paper is essential reading for anyone making non-trivial use of mdo-notation,
and we do not repeat it here.
932
933
934
935
936
937
938
939
940
941
942
943
</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>
944
945
import Control.Monad.Fix

946
justOnes = mdo xs &lt;- Just (1:xs)
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
               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>
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
962
963
964
965
966
967
968
969
dictates how the required recursion operation should be performed.  For example, 
<literal>justOnes</literal> desugars as follows:
<programlisting>
justOnes = mfix (\xs' -&gt; do { xs &lt;- Just (1:xs'); return xs }
</programlisting>
For full details of the way in which mdo is typechecked and desugared, see 
the paper <ulink url="http://citeseer.ist.psu.edu/erk02recursive.html">A recursive do for Haskell</ulink>.
In particular, GHC implements the segmentation technique described in Section 3.2 of the paper.
970
971
</para>
<para>
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
972
973
If recursive bindings are required for a monad,
then that monad must be declared an instance of the <literal>MonadFix</literal> class.
974
975
976
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).
977
978
</para>
<para>
979
Here are some important points in using the recursive-do notation:
980
981
982
983
984
985
986
<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>
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
It is enabled with the flag <literal>-XRecursiveDo</literal>, which is in turn implied by
<literal>-fglasgow-exts</literal>.
</para></listitem>

<listitem><para>
Unlike ordinary do-notation, but like <literal>let</literal> and <literal>where</literal> bindings,
name shadowing is not allowed; that is, all the names bound in a single <literal>mdo</literal> must
be distinct (Section 3.3 of the paper).
</para></listitem>

<listitem><para>
Variables bound by a <literal>let</literal> statement in an <literal>mdo</literal>
are monomorphic in the <literal>mdo</literal> (Section 3.1 of the paper).  However
GHC breaks the <literal>mdo</literal> into segments to enhance polymorphism,
For faster browsing, not all history is shown. View entire blame