glasgow_exts.xml 349 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
Ian Lynagh's avatar
Ian Lynagh committed
6
7
8
the language.  They can all be enabled or disabled by commandline flags
or language pragmas. By default GHC understands the most recent Haskell
version it supports, plus a handful of extensions.
9
</para>
rrt's avatar
rrt committed
10

11
<para>
12
13
14
15
16
17
18
19
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!
20
</para>
rrt's avatar
rrt committed
21

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

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

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

42
    <para>The language option flags control what variation of the language are
Ian Lynagh's avatar
Ian Lynagh committed
43
    permitted.</para>
44

45
46
    <para>Language options can be controlled in two ways:
    <itemizedlist>
47
48
      <listitem><para>Every language option can switched on by a command-line flag "<option>-X...</option>"
        (e.g. <option>-XTemplateHaskell</option>), and switched off by the flag "<option>-XNo...</option>";
49
50
51
52
53
54
        (e.g. <option>-XNoTemplateHaskell</option>).</para></listitem>
      <listitem><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>
          </listitem>
      </itemizedlist></para>
55

56
    <para>The flag <option>-fglasgow-exts</option>
57
          <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
58
	  is equivalent to enabling the following extensions:
59
          &what_glasgow_exts_does;
60
	    Enabling these options is the <emphasis>only</emphasis>
Simon Marlow's avatar
Simon Marlow committed
61
	    effect of <option>-fglasgow-exts</option>.
62
          We are trying to move away from this portmanteau flag,
63
	  and towards enabling features individually.</para>
64

65
  </sect1>
66

67
<!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS -->
68
69
70
<sect1 id="primitives">
  <title>Unboxed types and primitive operations</title>

71
72
<para>GHC is built on a raft of primitive data types and operations;
"primitive" in the sense that they cannot be defined in Haskell itself.
73
74
75
76
77
78
79
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>

80
81
<para>All these primitive data types and operations are exported by the
library <literal>GHC.Prim</literal>, for which there is
82
<ulink url="&libraryGhcPrimLocation;/GHC-Prim.html">detailed online documentation</ulink>.
83
84
85
86
87
88
89
90
91
(This documentation is generated from the file <filename>compiler/prelude/primops.txt.pp</filename>.)
</para>
<para>
If you want to mention any of the primitive data types or operations in your
program, you must first import <literal>GHC.Prim</literal> to bring them
into scope.  Many of them have names ending in "&num;", and to mention such
names you need the <option>-XMagicHash</option> extension (<xref linkend="magic-hash"/>).
</para>

92
<para>The primops make extensive use of <link linkend="glasgow-unboxed">unboxed types</link>
93
94
and <link linkend="unboxed-tuples">unboxed tuples</link>, which
we briefly summarise here. </para>
95

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<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
127
bottom.  We use the convention (but it is only a convention)
128
129
130
131
that primitive types, values, and
operations have a <literal>&num;</literal> suffix (see <xref linkend="magic-hash"/>).
For some primitive types we have special syntax for literals, also
described in the <link linkend="magic-hash">same section</link>.
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
</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.
147
148
149
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.
150
151
152
</para>

<para>
153
154
155
156
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
157
158
159
160
161
162
163
164
165
166
167
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>
168
</listitem>
169
170
171
172
173
174
175
<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>
176
177
178
179
180
181
182
<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,
183
184
non-top-level) pattern binding, but you must make any such pattern-match
strict.  For example, rather than:
185
186
<programlisting>
  data Foo = Foo Int Int#
187

188
189
  f x = let (Foo a b, w) = ..rhs.. in ..body..
</programlisting>
190
you must write:
191
192
193
<programlisting>
  data Foo = Foo Int Int#

194
  f x = let !(Foo a b, w) = ..rhs.. in ..body..
195
</programlisting>
196
since <literal>b</literal> has type <literal>Int#</literal>.
197
198
199
</para>
</listitem>
</itemizedlist>
200
201
202
203
204
205
206
207
208
</para>

</sect2>

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

<para>
209
210
Unboxed tuples aren't really exported by <literal>GHC.Exts</literal>;
they are a syntactic extension enabled by the language flag <option>-XUnboxedTuples</option>.  An
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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
234
of the primitive operations listed in <literal>primops.txt.pp</literal> return unboxed
235
tuples.
236
237
In particular, the <literal>IO</literal> and <literal>ST</literal> monads use unboxed
tuples to avoid unnecessary allocation during sequences of operations.
238
239
240
241
242
243
244
245
</para>

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

<para>
246
Values of unboxed tuple types are subject to the same restrictions as
247
248
249
250
251
252
253
254
other unboxed types; i.e. they may not be stored in polymorphic data
structures or passed to polymorphic functions.

</para>
</listitem>
<listitem>

<para>
255
256
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:
257
<programlisting>
258
  data Foo = Foo (# Int, Int #)
259

260
261
  f :: (# Int, Int #) -&#62; (# Int, Int #)
  f x = x
262

263
264
  g :: (# Int, Int #) -&#62; Int
  g (# a,b #) = a
265

266
  h x = let y = (# x,x #) in ...
267
268
269
</programlisting>
</para>
</listitem>
270
271
272
273
274
275
276
277
<listitem>
<para>
Unboxed tuples may not be nested. So this is illegal:
<programlisting>
f :: (# Int, (# Int, Int #), Bool #)
</programlisting>
</para>
</listitem>
278
279
280
</itemizedlist>
</para>
<para>
281
282
283
284
285
286
287
288
289
290
291
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,
292
the resulting binding is lazy like any other Haskell pattern binding.  The
293
294
295
296
297
298
299
300
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.
301
302
303
304
305
</para>

</sect2>
</sect1>

rrt's avatar
rrt committed
306

307
308
309
310
<!-- ====================== SYNTACTIC EXTENSIONS =======================  -->

<sect1 id="syntax-extns">
<title>Syntactic extensions</title>
311

Simon Marlow's avatar
Simon Marlow committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    <sect2 id="unicode-syntax">
      <title>Unicode syntax</title>
      <para>The language
      extension <option>-XUnicodeSyntax</option><indexterm><primary><option>-XUnicodeSyntax</option></primary></indexterm>
      enables Unicode characters to be used to stand for certain ASCII
      character sequences.  The following alternatives are provided:</para>

      <informaltable>
	<tgroup cols="2" align="left" colsep="1" rowsep="1">
	  <thead>
	    <row>
	      <entry>ASCII</entry>
              <entry>Unicode alternative</entry>
	      <entry>Code point</entry>
	      <entry>Name</entry>
	    </row>
	  </thead>
329
330
331
332
333
334
335
336
337

<!--
               to find the DocBook entities for these characters, find
               the Unicode code point (e.g. 0x2237), and grep for it in
               /usr/share/sgml/docbook/xml-dtd-*/ent/* (or equivalent on
               your system.  Some of these Unicode code points don't have
               equivalent DocBook entities.
            -->

Simon Marlow's avatar
Simon Marlow committed
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
	  <tbody>
	    <row>
	      <entry><literal>::</literal></entry>
	      <entry>::</entry> <!-- no special char, apparently -->
              <entry>0x2237</entry>
	      <entry>PROPORTION</entry>
	    </row>
          </tbody>
	  <tbody>
	    <row>
	      <entry><literal>=&gt;</literal></entry>
	      <entry>&rArr;</entry>
	      <entry>0x21D2</entry>
              <entry>RIGHTWARDS DOUBLE ARROW</entry>
	    </row>
          </tbody>
	  <tbody>
	    <row>
	      <entry><literal>forall</literal></entry>
	      <entry>&forall;</entry>
	      <entry>0x2200</entry>
              <entry>FOR ALL</entry>
	    </row>
          </tbody>
	  <tbody>
	    <row>
	      <entry><literal>-&gt;</literal></entry>
	      <entry>&rarr;</entry>
	      <entry>0x2192</entry>
              <entry>RIGHTWARDS ARROW</entry>
	    </row>
          </tbody>
	  <tbody>
	    <row>
	      <entry><literal>&lt;-</literal></entry>
	      <entry>&larr;</entry>
	      <entry>0x2190</entry>
              <entry>LEFTWARDS ARROW</entry>
	    </row>
          </tbody>
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423

	  <tbody>
	    <row>
	      <entry>-&lt;</entry>
	      <entry>&larrtl;</entry>
	      <entry>0x2919</entry>
	      <entry>LEFTWARDS ARROW-TAIL</entry>
	    </row>
          </tbody>

	  <tbody>
	    <row>
	      <entry>&gt;-</entry>
	      <entry>&rarrtl;</entry>
	      <entry>0x291A</entry>
	      <entry>RIGHTWARDS ARROW-TAIL</entry>
	    </row>
          </tbody>

	  <tbody>
	    <row>
	      <entry>-&lt;&lt;</entry>
	      <entry></entry>
	      <entry>0x291B</entry>
	      <entry>LEFTWARDS DOUBLE ARROW-TAIL</entry>
	    </row>
          </tbody>

	  <tbody>
	    <row>
	      <entry>&gt;&gt;-</entry>
	      <entry></entry>
	      <entry>0x291C</entry>
	      <entry>RIGHTWARDS DOUBLE ARROW-TAIL</entry>
	    </row>
          </tbody>

	  <tbody>
	    <row>
	      <entry>*</entry>
	      <entry>&starf;</entry>
	      <entry>0x2605</entry>
	      <entry>BLACK STAR</entry>
	    </row>
          </tbody>

Simon Marlow's avatar
Simon Marlow committed
424
425
426
427
        </tgroup>
      </informaltable>
    </sect2>

428
429
430
431
432
433
    <sect2 id="magic-hash">
      <title>The magic hash</title>
      <para>The language extension <option>-XMagicHash</option> allows "&num;" as a
	postfix modifier to identifiers.  Thus, "x&num;" is a valid variable, and "T&num;" is
	a valid type constructor or data constructor.</para>

434
435
      <para>The hash sign does not change semantics at all.  We tend to use variable
	names ending in "&num;" for unboxed values or types (e.g. <literal>Int&num;</literal>),
436
        but there is no requirement to do so; they are just plain ordinary variables.
437
	Nor does the <option>-XMagicHash</option> extension bring anything into scope.
438
439
	For example, to bring <literal>Int&num;</literal> into scope you must
	import <literal>GHC.Prim</literal> (see <xref linkend="primitives"/>);
440
441
442
443
	the <option>-XMagicHash</option> extension
	then allows you to <emphasis>refer</emphasis> to the <literal>Int&num;</literal>
	that is now in scope.</para>
      <para> The <option>-XMagicHash</option> also enables some new forms of literals (see <xref linkend="glasgow-unboxed"/>):
444
	<itemizedlist>
445
446
447
	  <listitem><para> <literal>'x'&num;</literal> has type <literal>Char&num;</literal></para> </listitem>
	  <listitem><para> <literal>&quot;foo&quot;&num;</literal> has type <literal>Addr&num;</literal></para> </listitem>
	  <listitem><para> <literal>3&num;</literal> has type <literal>Int&num;</literal>. In general,
Ian Lynagh's avatar
Ian Lynagh committed
448
	  any Haskell integer lexeme followed by a <literal>&num;</literal> is an <literal>Int&num;</literal> literal, e.g.
449
450
            <literal>-0x3A&num;</literal> as well as <literal>32&num;</literal></para>.</listitem>
	  <listitem><para> <literal>3&num;&num;</literal> has type <literal>Word&num;</literal>. In general,
Ian Lynagh's avatar
Ian Lynagh committed
451
	  any non-negative Haskell integer lexeme followed by <literal>&num;&num;</literal>
452
453
454
455
456
457
458
	      is a <literal>Word&num;</literal>. </para> </listitem>
	  <listitem><para> <literal>3.2&num;</literal> has type <literal>Float&num;</literal>.</para> </listitem>
	  <listitem><para> <literal>3.2&num;&num;</literal> has type <literal>Double&num;</literal></para> </listitem>
	  </itemizedlist>
      </para>
   </sect2>

459
460
    <!-- ====================== HIERARCHICAL MODULES =======================  -->

461

462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
    <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>

492
493
      <para>For details on how GHC searches for source and interface
      files in the presence of hierarchical modules, see <xref
494
      linkend="search-path"/>.</para>
495
496

      <para>GHC comes with a large collection of libraries arranged
497
498
499
500
501
      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>
502
503
504
505
506
507
508
509
510
    </sect2>

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

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

<para>
<indexterm><primary>Pattern guards (Glasgow extension)</primary></indexterm>
511
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.)
512
513
514
515
516
517
518
519
520
521
522
</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,
523
where <varname>v</varname> is the value that the key maps to.  Now consider the following definition:
524
525
526
</para>

<programlisting>
527
clunky env var1 var2 | ok1 &amp;&amp; ok2 = val1 + val2
528
529
530
531
532
533
534
535
536
537
538
| 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>
539
The auxiliary functions are
540
541
542
543
544
545
546
547
548
549
550
551
552
</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>
553
What is <function>clunky</function> doing? The guard <literal>ok1 &amp;&amp;
554
555
556
557
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
558
returned values to <varname>val1</varname> and <varname>val2</varname>
559
560
561
562
563
564
565
566
567
568
569
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>
570
clunky env var1 var2 = case lookup env var1 of
571
572
573
574
575
  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
576
  fail = var1 + var2
577
578
579
580
581
582
583
</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
584
the cases we want to consider, one at a time, independently of each other.
585
586
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
587
tends to become more and more indented.
588
589
590
591
592
593
594
</para>

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

<programlisting>
595
clunky env var1 var2
596
597
598
599
600
601
602
  | Just val1 &lt;- lookup env var1
  , Just val2 &lt;- lookup env var2
  = val1 + val2
...other equations for clunky...
</programlisting>

<para>
603
The semantics should be clear enough.  The qualifiers are matched in order.
604
For a <literal>&lt;-</literal> qualifier, which I call a pattern guard, the
605
right hand side is evaluated and matched against the pattern on the left.
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
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>
621
f x | [y] &lt;- x
622
    , y > 3
623
    , Just z &lt;- h y
624
625
626
627
628
629
630
    = ...
</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>
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
</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
655

656
657
658
659
660
661
662
663
664
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
665
to use a fancy representation (e.g., hash-consing to manage sharing).
666

667
Without view patterns, using this signature a little inconvenient:
668
669
670
671
672
673
674
675
676
677
678
679
680
681
<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
682
matching against the result:
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
<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>
725
More precisely, the scoping rules are:
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
<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
743
were collected into a tuple.
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
</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>

759
(For some amplification on this design choice see
760
<ulink url="http://hackage.haskell.org/trac/ghc/ticket/4061">Trac #4061</ulink>.)
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779

</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>
780
781
case v of { (e -> p) -> e1 ; _ -> e2 }
 =
782
783
784
785
786
787
788
789
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
790
<replaceable>pat</replaceable>.
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
</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>

825
826
827
828
829
830
</sect2>

    <!-- ===================== n+k patterns ===================  -->

<sect2 id="n-k-patterns">
<title>n+k patterns</title>
831
<indexterm><primary><option>-XNPlusKPatterns</option></primary></indexterm>
832
833

<para>
834
835
<literal>n+k</literal> pattern support is disabled by default. To enable
it, you can use the <option>-XNPlusKPatterns</option> flag.
836
837
</para>

Ian Lynagh's avatar
Ian Lynagh committed
838
839
840
841
842
843
844
845
846
847
848
849
850
</sect2>

    <!-- ===================== Traditional record syntax ===================  -->

<sect2 id="traditional-record-syntax">
<title>Traditional record syntax</title>
<indexterm><primary><option>-XNoTraditionalRecordSyntax</option></primary></indexterm>

<para>
Traditional record syntax, such as <literal>C {f = x}</literal>, is enabled by default.
To disable it, you can use the <option>-XNoTraditionalRecordSyntax</option> flag.
</para>

851
852
853
854
</sect2>

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

855
<sect2 id="recursive-do-notation">
856
857
858
859
<title>The recursive do-notation
</title>

<para>
860
The do-notation of Haskell 98 does not allow <emphasis>recursive bindings</emphasis>,
861
that is, the variables bound in a do-expression are visible only in the textually following
862
863
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
864
the do-notation.  The <option>-XDoRec</option> flag provides the necessary syntactic support.
865
866
</para>
<para>
867
Here is a simple (albeit contrived) example:
868
<programlisting>
869
870
871
{-# LANGUAGE DoRec #-}
justOnes = do { rec { xs &lt;- Just (1:xs) }
              ; return (map negate xs) }
872
</programlisting>
873
874
As you can guess <literal>justOnes</literal> will evaluate to <literal>Just [-1,-1,-1,...</literal>.
</para>
875
<para>
Ian Lynagh's avatar
Ian Lynagh committed
876
The background and motivation for recursive do-notation is described in
877
<ulink url="http://sites.google.com/site/leventerkok/">A recursive do for Haskell</ulink>,
878
by Levent Erkok, John Launchbury,
879
Haskell Workshop 2002, pages: 29-37. Pittsburgh, Pennsylvania.
880
881
882
The theory behind monadic value recursion is explained further in Erkok's thesis
<ulink url="http://sites.google.com/site/leventerkok/erkok-thesis.pdf">Value Recursion in Monadic Computations</ulink>.
However, note that GHC uses a different syntax than the one described in these documents.
883
884
</para>

885
886
887
888
889
<sect3>
<title>Details of recursive do-notation</title>
<para>
The recursive do-notation is enabled with the flag <option>-XDoRec</option> or, equivalently,
the LANGUAGE pragma <option>DoRec</option>.  It introduces the single new keyword "<literal>rec</literal>",
890
891
892
893
which wraps a mutually-recursive group of monadic statements,
producing a single statement.
</para>
<para>Similar to a <literal>let</literal>
894
statement, the variables bound in the <literal>rec</literal> are
895
visible throughout the <literal>rec</literal> group, and below it.
896
897
For example, compare
<programlisting>
898
899
900
do { a &lt;- getChar              do { a &lt;- getChar
   ; let { r1 = f a r2	           ; rec { r1 &lt;- f a r2
         ; r2 = g r1 }	                 ; r2 &lt;- g r1 }
901
902
   ; return (r1 ++ r2) }          ; return (r1 ++ r2) }
</programlisting>
903
In both cases, <literal>r1</literal> and <literal>r2</literal> are
904
905
available both throughout the <literal>let</literal> or <literal>rec</literal> block, and
in the statements that follow it.  The difference is that <literal>let</literal> is non-monadic,
906
while <literal>rec</literal> is monadic.  (In Haskell <literal>let</literal> is
907
really <literal>letrec</literal>, of course.)
908
</para>
909
<para>
910
The static and dynamic semantics of <literal>rec</literal> can be described as follows:
911
912
913
<itemizedlist>
<listitem><para>
First,
914
similar to let-bindings, the <literal>rec</literal> is broken into
915
916
minimal recursive groups, a process known as <emphasis>segmentation</emphasis>.
For example:
917
<programlisting>
918
919
920
rec { a &lt;- getChar      ===>     a &lt;- getChar
    ; b &lt;- f a c                 rec { b &lt;- f a c
    ; c &lt;- f b a                     ; c &lt;- f b a }
921
    ; putChar c }                putChar c
922
</programlisting>
923
924
The details of segmentation are described in Section 3.2 of
<ulink url="http://sites.google.com/site/leventerkok/">A recursive do for Haskell</ulink>.
925
Segmentation improves polymorphism, reduces the size of the recursive "knot", and, as the paper
926
927
928
929
930
describes, also has a semantic effect (unless the monad satisfies the right-shrinking law).
</para></listitem>
<listitem><para>
Then each resulting <literal>rec</literal> is desugared, using a call to <literal>Control.Monad.Fix.mfix</literal>.
For example, the <literal>rec</literal> group in the preceding example is desugared like this:
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
931
<programlisting>
932
933
934
rec { b &lt;- f a c     ===>    (b,c) &lt;- mfix (\~(b,c) -> do { b &lt;- f a c
    ; c &lt;- f b a }                                        ; c &lt;- f b a
                                                          ; return (b,c) })
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
935
</programlisting>
daniel.is.fischer's avatar
daniel.is.fischer committed
936
In general, the statement <literal>rec <replaceable>ss</replaceable></literal>
937
938
is desugared to the statement
<programlisting>
939
<replaceable>vs</replaceable> &lt;- mfix (\~<replaceable>vs</replaceable> -&gt; do { <replaceable>ss</replaceable>; return <replaceable>vs</replaceable> })
940
</programlisting>
941
where <replaceable>vs</replaceable> is a tuple of the variables bound by <replaceable>ss</replaceable>.
942
</para><para>
943
944
The original <literal>rec</literal> typechecks exactly
when the above desugared version would do so.  For example, this means that
945
the variables <replaceable>vs</replaceable> are all monomorphic in the statements
946
947
948
following the <literal>rec</literal>, because they are bound by a lambda.
</para>
<para>
949
The <literal>mfix</literal> function is defined in the <literal>MonadFix</literal>
950
951
952
953
954
955
956
957
class, in <literal>Control.Monad.Fix</literal>, thus:
<programlisting>
class Monad m => MonadFix m where
   mfix :: (a -> m a) -> m a
</programlisting>
</para>
</listitem>
</itemizedlist>
958
959
</para>
<para>
960
Here are some other important points in using the recursive-do notation:
961
962
<itemizedlist>
<listitem><para>
963
It is enabled with the flag <literal>-XDoRec</literal>.
964
965
966
</para></listitem>

<listitem><para>
967
968
If recursive bindings are required for a monad,
then that monad must be declared an instance of the <literal>MonadFix</literal> class.
969
970
971
</para></listitem>

<listitem><para>
972
973
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
974
for Haskell's internal state monad (strict and lazy, respectively).
975
976
977
</para></listitem>

<listitem><para>
978
Like <literal>let</literal> and <literal>where</literal> bindings,
979
name shadowing is not allowed within a <literal>rec</literal>;
980
that is, all the names bound in a single <literal>rec</literal> must
981
982
983
be distinct (Section 3.3 of the paper).
</para></listitem>
<listitem><para>
984
It supports rebindable syntax (see <xref linkend="rebindable-syntax"/>).
985
986
987
</para></listitem>
</itemizedlist>
</para>
988
989
</sect3>

990
<sect3 id="mdo-notation"> <title> Mdo-notation (deprecated) </title>
991

Ian Lynagh's avatar
Ian Lynagh committed
992
<para> GHC used to support the flag <option>-XRecursiveDo</option>,
993
which enabled the keyword <literal>mdo</literal>, precisely as described in
994
<ulink url="http://sites.google.com/site/leventerkok/">A recursive do for Haskell</ulink>,
995
996
997
but this is now deprecated.  Instead of <literal>mdo { Q; e }</literal>, write
<literal>do { rec Q; e }</literal>.
</para>
998
<para>
999
1000
Historical note: The old implementation of the mdo-notation (and most
of the existing documents) used the name