glasgow_exts.rst 480 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
.. index::
   single: language, GHC extensions

As with all known Haskell systems, GHC implements some extensions to the
standard Haskell language. They can all be enabled or disabled by command line
flags or language pragmas. By default GHC understands the most recent Haskell
version it supports, plus a handful of extensions.

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 stuck on performance because of
the implementation costs of Haskell's "high-level" features—you can
always code "under" them. In an extreme case, you can write all your
time-critical code in C, and then just glue it together with Haskell!

Before you get too carried away working at the lowest level (e.g.,
sloshing ``MutableByteArray#``\ s around your program), you may wish to
check if there are libraries that provide a "Haskellised veneer" over
the features you want. The separate
`libraries documentation <../libraries/index.html>`__ describes all the
libraries that come with GHC.

.. _options-language:

Language options
================

.. index::
   single: language; option
   single: options; language
   single: extensions; options controlling

The language option flags control what variation of the language are
permitted.

Language options can be controlled in two ways:

-  Every language option can switched on by a command-line flag
   "``-X...``" (e.g. ``-XTemplateHaskell``), and switched off by the
   flag "``-XNo...``"; (e.g. ``-XNoTemplateHaskell``).

-  Language options recognised by Cabal can also be enabled using the
   ``LANGUAGE`` pragma, thus ``{-# LANGUAGE TemplateHaskell #-}`` (see
   :ref:`language-pragma`).


48
49
Although not recommended, the deprecated :ghc-flag:`-fglasgow-exts` flag enables
a large swath of the extensions supported by GHC at once.
50

51
.. ghc-flag:: -fglasgow-exts
52

53
54
55
56
57
58
59
    The flag ``-fglasgow-exts`` is equivalent to enabling the following extensions:

    .. include:: what_glasgow_exts_does.gen.rst

    Enabling these options is the *only* effect of ``-fglasgow-exts``. We are trying
    to move away from this portmanteau flag, and towards enabling features
    individually.
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

.. _primitives:

Unboxed types and primitive operations
======================================

GHC is built on a raft of primitive data types and operations;
"primitive" in the sense that they cannot be defined in Haskell itself.
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.

All these primitive data types and operations are exported by the
library ``GHC.Prim``, for which there is
:ghc-prim-ref:`detailed online documentation <GHC-Prim.html>`. (This
documentation is generated from the file ``compiler/prelude/primops.txt.pp``.)

If you want to mention any of the primitive data types or operations in
your program, you must first import ``GHC.Prim`` to bring them into
scope. Many of them have names ending in ``#``, and to mention such names
82
you need the :ghc-flag:`-XMagicHash` extension (:ref:`magic-hash`).
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

The primops make extensive use of `unboxed types <#glasgow-unboxed>`__
and `unboxed tuples <#unboxed-tuples>`__, which we briefly summarise
here.

.. _glasgow-unboxed:

Unboxed types
-------------

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

Unboxed types correspond to the “raw machine” types you would use in C:
``Int#`` (long int), ``Double#`` (double), ``Addr#`` (void \*), etc. The
*primitive operations* (PrimOps) on these types are what you might
expect; e.g., ``(+#)`` is addition on ``Int#``\ s, and is the
machine-addition that we all know and love—usually one instruction.

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.
108
109
110
(Note: a "boxed" type means that a value is represented by a pointer to a heap
object; a "lifted" type means that terms of that type may be bottom. See
the next paragraph for an example.)
111
112
113
114
115
116
117
118
We use the convention (but it is only a convention) that primitive
types, values, and operations have a ``#`` suffix (see
:ref:`magic-hash`). For some primitive types we have special syntax for
literals, also described in the `same section <#magic-hash>`__.

Primitive values are often represented by a simple bit-pattern, such as
``Int#``, ``Float#``, ``Double#``. But this is not necessarily the case:
a primitive value might be represented by a pointer to a heap-allocated
119
120
object. Examples include ``Array#``, the type of primitive arrays. Thus,
``Array#`` is an unlifted, boxed type. A
121
122
123
124
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:
125
no unevaluated thunks, no indirections. Nothing can be at the other end
126
127
128
129
of the pointer than the primitive value. A numerically-intensive program
using unboxed types can go a *lot* faster than its “standard”
counterpart—we saw a threefold speedup on one example.

130
131
Unboxed type kinds
------------------
132

133
Because unboxed types are represented without the use of pointers, we
134
135
cannot store them in use a polymorphic datatype at an unboxed type.
For example, the ``Just`` node
136
137
138
139
140
141
142
143
144
145
146
147
148
of ``Just 42#`` would have to be different from the ``Just`` node of
``Just 42``; the former stores an integer directly, while the latter
stores a pointer. GHC currently does not support this variety of ``Just``
nodes (nor for any other datatype). Accordingly, the *kind* of an unboxed
type is different from the kind of a boxed type.

The Haskell Report describes that ``*`` is the kind of ordinary datatypes,
such as ``Int``. Furthermore, type constructors can have kinds with arrows;
for example, ``Maybe`` has kind ``* -> *``. Unboxed types have a kind that
specifies their runtime representation. For example, the type ``Int#`` has
kind ``TYPE 'IntRep`` and ``Double#`` has kind ``TYPE 'DoubleRep``. These
kinds say that the runtime representation of an ``Int#`` is a machine integer,
and the runtime representation of a ``Double#`` is a machine double-precision
149
150
floating point. In constrast, the kind ``*`` is actually just a synonym
for ``TYPE 'PtrRepLifted``. More details of the ``TYPE`` mechanisms appear in
151
152
the `section on runtime representation polymorphism <#runtime-rep>`__.

153
Given that ``Int#``'s kind is not ``*``, it then it follows that
154
155
156
157
158
159
160
161
``Maybe Int#`` is disallowed. Similarly, because type variables tend
to be of kind ``*`` (for example, in ``(.) :: (b -> c) -> (a -> b) -> a -> c``,
all the type variables have kind ``*``), polymorphism tends not to work
over primitive types. Stepping back, this makes some sense, because
a polymorphic function needs to manipulate the pointers to its data,
and most primitive types are unboxed.

There are some restrictions on the use of primitive types:
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

-  You cannot define a newtype whose representation type (the argument
   type of the data constructor) is an unboxed type. Thus, this is
   illegal:

   ::

         newtype A = MkA Int#

-  You cannot bind a variable with an unboxed type in a *top-level*
   binding.

-  You cannot bind a variable with an unboxed type in a *recursive*
   binding.

-  You may bind unboxed variables in a (non-recursive, non-top-level)
   pattern binding, but you must make any such pattern-match strict. For
   example, rather than:

   ::

         data Foo = Foo Int Int#

         f x = let (Foo a b, w) = ..rhs.. in ..body..

   you must write:

   ::

         data Foo = Foo Int Int#

         f x = let !(Foo a b, w) = ..rhs.. in ..body..

   since ``b`` has type ``Int#``.

.. _unboxed-tuples:

Unboxed tuples
--------------

202
.. ghc-flag:: -XUnboxedTuples
203

204
205
206
207
208
    Enable the use of unboxed tuple syntax.

Unboxed tuples aren't really exported by ``GHC.Exts``; they are a
syntactic extension enabled by the language flag :ghc-flag:`-XUnboxedTuples`. An
unboxed tuple looks like this: ::
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271

    (# e_1, ..., e_n #)

where ``e_1..e_n`` are expressions of any type (primitive or
non-primitive). The type of an unboxed tuple looks the same.

Note that when unboxed tuples are enabled, ``(#`` is a single lexeme, so
for example when using operators like ``#`` and ``#-`` you need to write
``( # )`` and ``( #- )`` rather than ``(#)`` and ``(#-)``.

Unboxed tuples are used for functions that need to return multiple
values, but they avoid the heap allocation normally associated with
using fully-fledged tuples. When an unboxed tuple is returned, the
components are put directly into registers or on the stack; the unboxed
tuple itself does not have a composite representation. Many of the
primitive operations listed in ``primops.txt.pp`` return unboxed tuples.
In particular, the ``IO`` and ``ST`` monads use unboxed tuples to avoid
unnecessary allocation during sequences of operations.

There are some restrictions on the use of unboxed tuples:

-  Values of unboxed tuple types are subject to the same restrictions as
   other unboxed types; i.e. they may not be stored in polymorphic data
   structures or passed to polymorphic functions.

-  The typical use of unboxed tuples is simply to return multiple
   values, binding those multiple results with a ``case`` expression,
   thus:

   ::

         f x y = (# x+1, y-1 #)
         g x = case f x x of { (# a, b #) -> a + b }

   You can have an unboxed tuple in a pattern binding, thus

   ::

         f x = let (# p,q #) = h x in ..body..

   If the types of ``p`` and ``q`` are not unboxed, the resulting
   binding is lazy like any other Haskell pattern binding. The above
   example desugars like this:

   ::

         f x = let t = case h x of { (# p,q #) -> (p,q) }
                   p = fst t
                   q = snd t
               in ..body..

   Indeed, the bindings can even be recursive.

.. _syntax-extns:

Syntactic extensions
====================

.. _unicode-syntax:

Unicode syntax
--------------

272
273
274
275
276
277
.. ghc-flag:: -XUnicodeSyntax

    Enable the use of Unicode characters in place of their equivalent ASCII
    sequences.

The language extension :ghc-flag:`-XUnicodeSyntax` enables
278
279
280
Unicode characters to be used to stand for certain ASCII character
sequences. The following alternatives are provided:

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
+--------------+---------------+-------------+-----------------------------------------+
| ASCII        | Unicode       | Code point  | Name                                    |
|              | alternative   |             |                                         |
+==============+===============+=============+=========================================+
| ``::``       |              | 0x2237      | PROPORTION                              |
+--------------+---------------+-------------+-----------------------------------------+
| ``=>``       |              | 0x21D2      | RIGHTWARDS DOUBLE ARROW                 |
+--------------+---------------+-------------+-----------------------------------------+
| ``->``       |              | 0x2192      | RIGHTWARDS ARROW                        |
+--------------+---------------+-------------+-----------------------------------------+
| ``<-``       |              | 0x2190      | LEFTWARDS ARROW                         |
+--------------+---------------+-------------+-----------------------------------------+
| ``>-``       |              | 0x291a      | RIGHTWARDS ARROW-TAIL                   |
+--------------+---------------+-------------+-----------------------------------------+
| ``-<``       |              | 0x2919      | LEFTWARDS ARROW-TAIL                    |
+--------------+---------------+-------------+-----------------------------------------+
| ``>>-``      |              | 0x291C      | RIGHTWARDS DOUBLE ARROW-TAIL            |
+--------------+---------------+-------------+-----------------------------------------+
| ``-<<``      |              | 0x291B      | LEFTWARDS DOUBLE ARROW-TAIL             |
+--------------+---------------+-------------+-----------------------------------------+
| ``*``        |              | 0x2605      | BLACK STAR                              |
+--------------+---------------+-------------+-----------------------------------------+
| ``forall``   |              | 0x2200      | FOR ALL                                 |
+--------------+---------------+-------------+-----------------------------------------+
| ``(|``       |              | 0x2987      | Z NOTATION LEFT IMAGE BRACKET           |
+--------------+---------------+-------------+-----------------------------------------+
| ``|)``       |              | 0x2988      | Z NOTATION RIGHT IMAGE BRACKET          |
+--------------+---------------+-------------+-----------------------------------------+
| ``[|``       |              | 0x27E6      | MATHEMATICAL LEFT WHITE SQUARE BRACKET  |
+--------------+---------------+-------------+-----------------------------------------+
| ``|]``       |              | 0x27E7      | MATHEMATICAL RIGHT WHITE SQUARE BRACKET |
+--------------+---------------+-------------+-----------------------------------------+
313
314
315
316
317
318

.. _magic-hash:

The magic hash
--------------

319
320
321
322
323
324
.. ghc-flag:: -XMagicHash

    Enable the use of the hash character (``#``) as an identifier suffix.

The language extension :ghc-flag:`-XMagicHash` allows ``#`` as a postfix modifier
to identifiers. Thus, ``x#`` is a valid variable, and ``T#`` is a valid type
325
326
327
328
329
constructor or data constructor.

The hash sign does not change semantics at all. We tend to use variable
names ending in "#" for unboxed values or types (e.g. ``Int#``), but
there is no requirement to do so; they are just plain ordinary
330
variables. Nor does the :ghc-flag:`-XMagicHash` extension bring anything into
331
scope. For example, to bring ``Int#`` into scope you must import
332
``GHC.Prim`` (see :ref:`primitives`); the :ghc-flag:`-XMagicHash` extension then
333
334
335
336
337
allows you to *refer* to the ``Int#`` that is now in scope. Note that
with this option, the meaning of ``x#y = 0`` is changed: it defines a
function ``x#`` taking a single argument ``y``; to define the operator
``#``, put a space: ``x # y = 0``.

338
The :ghc-flag:`-XMagicHash` also enables some new forms of literals (see
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
:ref:`glasgow-unboxed`):

-  ``'x'#`` has type ``Char#``

-  ``"foo"#`` has type ``Addr#``

-  ``3#`` has type ``Int#``. In general, any Haskell integer lexeme
   followed by a ``#`` is an ``Int#`` literal, e.g. ``-0x3A#`` as well as
   ``32#``.

-  ``3##`` has type ``Word#``. In general, any non-negative Haskell
   integer lexeme followed by ``##`` is a ``Word#``.

-  ``3.2#`` has type ``Float#``.

-  ``3.2##`` has type ``Double#``

.. _negative-literals:

Negative literals
-----------------

361
362
.. ghc-flag:: -XNegativeLiterals

363
364
    :since: 7.8.1

365
366
    Enable the use of un-parenthesized negative numeric literals.

367
368
The literal ``-123`` is, according to Haskell98 and Haskell 2010,
desugared as ``negate (fromInteger 123)``. The language extension
369
:ghc-flag:`-XNegativeLiterals` means that it is instead desugared as
370
371
372
373
374
375
376
377
378
379
380
381
``fromInteger (-123)``.

This can make a difference when the positive and negative range of a
numeric data type don't match up. For example, in 8-bit arithmetic -128
is representable, but +128 is not. So ``negate (fromInteger 128)`` will
elicit an unexpected integer-literal-overflow message.

.. _num-decimals:

Fractional looking integer literals
-----------------------------------

382
383
.. ghc-flag:: -XNumDecimals

384
385
    :since: 7.8.1

386
387
    Allow the use of floating-point literal syntax for integral types.

388
389
390
Haskell 2010 and Haskell 98 define floating literals with the syntax
``1.2e6``. These literals have the type ``Fractional a => a``.

391
The language extension :ghc-flag:`-XNumDecimals` allows you to also use the
392
393
394
395
396
397
398
399
floating literal syntax for instances of ``Integral``, and have values
like ``(1.2e6 :: Num a => a)``

.. _binary-literals:

Binary integer literals
-----------------------

400
401
.. ghc-flag:: -XBinaryLiterals

402
403
    :since: 7.10.1

404
405
    Allow the use of binary notation in integer literals.

406
407
408
409
Haskell 2010 and Haskell 98 allows for integer literals to be given in
decimal, octal (prefixed by ``0o`` or ``0O``), or hexadecimal notation
(prefixed by ``0x`` or ``0X``).

410
411
412
413
The language extension :ghc-flag:`-XBinaryLiterals` adds support for expressing
integer literals in binary notation with the prefix ``0b`` or ``0B``. For
instance, the binary integer literal ``0b11001001`` will be desugared into
``fromInteger 201`` when :ghc-flag:`-XBinaryLiterals` is enabled.
414
415
416
417
418
419

.. _pattern-guards:

Pattern guards
--------------

420
.. ghc-flag:: -XNoPatternGuards
421

422
423
424
425
426
427
    :implied by: :ghc-flag:`-XHaskell98`
    :since: 6.8.1

Disable `pattern guards 
<http://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-460003.13>`__.
   
428
429
430
431
432
.. _view-patterns:

View patterns
-------------

433
434
435
436
437
.. ghc-flag:: -XViewPatterns

    Allow use of view pattern syntax.

View patterns are enabled by the flag :ghc-flag:`-XViewPatterns`. More
438
439
440
441
442
443
444
information and examples of view patterns can be found on the
:ghc-wiki:`Wiki page <ViewPatterns>`.

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
445
language as follows: ::
446
447
448
449
450
451
452
453
454
455
456
457

    type Typ

    data TypView = Unit
                 | Arrow Typ Typ

    view :: Typ -> TypView

    -- additional operations for constructing Typ's ...

The representation of Typ is held abstract, permitting implementations
to use a fancy representation (e.g., hash-consing to manage sharing).
Rik Steenkamp's avatar
Rik Steenkamp committed
458
Without view patterns, using this signature is a little inconvenient: ::
459
460
461
462
463
464
465
466
467
468
469

    size :: Typ -> Integer
    size t = case view t of
      Unit -> 1
      Arrow t1 t2 -> size t1 + size t2

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

View patterns permit calling the view function inside the pattern and
470
matching against the result: ::
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491

    size (view -> Unit) = 1
    size (view -> Arrow t1 t2) = size t1 + size t2

That is, we add a new form of pattern, written expression ``->``
pattern 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.

The semantics of a pattern ``(`` exp ``->`` pat ``)`` are as
follows:

-  Scoping:
   The variables bound by the view pattern are the variables bound by
   pat.

   Any variables in exp 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 ``clunky`` from
492
   :ref:`pattern-guards` can be written using view patterns as follows: ::
493
494
495
496
497
498
499

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

   More precisely, the scoping rules are:

   -  In a single pattern, variables bound by patterns to the left of a
500
      view pattern expression are in scope. For example: ::
501
502
503
504
505
506

          example :: Maybe ((String -> Integer,Integer), String) -> Bool
          example Just ((f,_), f -> 4) = True

      Additionally, in function definitions, variables bound by matching
      earlier curried arguments may be used in view pattern expressions
507
      in later arguments: ::
508
509
510
511
512
513
514
515
516
517
518

          example :: (String -> Integer) -> String -> Bool
          example f (f -> 4) = True

      That is, the scoping is the same as it would be if the curried
      arguments were collected into a tuple.

   -  In mutually recursive bindings, such as ``let``, ``where``, 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
519
      allowed: ::
520
521
522
523
524
525
526
527
528
529

          let {(x -> y) = e1 ;
               (y -> x) = e2 } in x

   (For some amplification on this design choice see :ghc-ticket:`4061`.

-  Typing: If exp has type T1 ``->`` T2 and pat matches a T2,
   then the whole view pattern matches a T1.

-  Matching: To the equations in Section 3.17.3 of the `Haskell 98
530
   Report <http://www.haskell.org/onlinereport/>`__, add the following: ::
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565

       case v of { (e -> p) -> e1 ; _ -> e2 }
        =
       case (e v) of { p -> e1 ; _ -> e2 }

   That is, to match a variable v against a pattern ``(`` exp ``->``
   pat ``)``, evaluate ``(`` exp v ``)`` and match the result
   against pat.

-  Efficiency: When the same view function is applied in multiple
   branches of a function definition or a case expression (e.g., in
   ``size`` 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 `The Implementation of Functional
   Programming
   Languages <http://research.microsoft.com/~simonpj/Papers/slpj-book-1987/>`__.
   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

   ::

       f ((view -> A, p1), p2) = e1
       f ((view -> B, p3), p4) = e2

   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 ``view ("hi", "there")`` will be
   collected. However, the current implementation does not compare up to
   alpha-equivalence, so two instances of ``(x, view x -> y)`` will not
   be coalesced.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
566
.. _n-k-patterns:
567

Simon Peyton Jones's avatar
Simon Peyton Jones committed
568
569
n+k patterns
------------
570

Simon Peyton Jones's avatar
Simon Peyton Jones committed
571
.. ghc-flag:: -XNPlusKPatterns
572

573
    :implied by: :ghc-flag:`-XHaskell98`
Ben Gamari's avatar
Ben Gamari committed
574
575
    :since: 6.12

Simon Peyton Jones's avatar
Simon Peyton Jones committed
576
    Enable use of ``n+k`` patterns.
577

Simon Peyton Jones's avatar
Simon Peyton Jones committed
578
.. _recursive-do-notation:
579

Simon Peyton Jones's avatar
Simon Peyton Jones committed
580
581
The recursive do-notation
-------------------------
582

Simon Peyton Jones's avatar
Simon Peyton Jones committed
583
.. ghc-flag:: -XRecursiveDo
584

Simon Peyton Jones's avatar
Simon Peyton Jones committed
585
    Allow the use of recursive ``do`` notation.
586

Simon Peyton Jones's avatar
Simon Peyton Jones committed
587
588
589
590
The do-notation of Haskell 98 does not allow *recursive bindings*, 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.
591

Simon Peyton Jones's avatar
Simon Peyton Jones committed
592
593
594
595
596
It turns out that such recursive bindings do indeed make sense for a
variety of monads, but not all. In particular, recursion in this sense
requires a fixed-point operator for the underlying monad, captured by
the ``mfix`` method of the ``MonadFix`` class, defined in
``Control.Monad.Fix`` as follows: ::
597

Simon Peyton Jones's avatar
Simon Peyton Jones committed
598
599
    class Monad m => MonadFix m where
       mfix :: (a -> m a) -> m a
600

Simon Peyton Jones's avatar
Simon Peyton Jones committed
601
602
603
604
Haskell's ``Maybe``, ``[]`` (list), ``ST`` (both strict and lazy
versions), ``IO``, and many other monads have ``MonadFix`` instances. On
the negative side, the continuation monad, with the signature
``(a -> r) -> r``, does not.
605

Simon Peyton Jones's avatar
Simon Peyton Jones committed
606
607
608
609
610
611
612
613
For monads that do belong to the ``MonadFix`` class, GHC provides an
extended version of the do-notation that allows recursive bindings. The
:ghc-flag:`-XRecursiveDo` (language pragma: ``RecursiveDo``) provides the
necessary syntactic support, introducing the keywords ``mdo`` and
``rec`` for higher and lower levels of the notation respectively. Unlike
bindings in a ``do`` expression, those introduced by ``mdo`` and ``rec``
are recursively defined, much like in an ordinary let-expression. Due to
the new keyword ``mdo``, we also call this notation the *mdo-notation*.
614

Simon Peyton Jones's avatar
Simon Peyton Jones committed
615
Here is a simple (albeit contrived) example:
616

Simon Peyton Jones's avatar
Simon Peyton Jones committed
617
::
618

Simon Peyton Jones's avatar
Simon Peyton Jones committed
619
620
621
    {-# LANGUAGE RecursiveDo #-}
    justOnes = mdo { xs <- Just (1:xs)
                   ; return (map negate xs) }
622

Simon Peyton Jones's avatar
Simon Peyton Jones committed
623
or equivalently
624

Simon Peyton Jones's avatar
Simon Peyton Jones committed
625
::
626

Simon Peyton Jones's avatar
Simon Peyton Jones committed
627
628
629
    {-# LANGUAGE RecursiveDo #-}
    justOnes = do { rec { xs <- Just (1:xs) }
                  ; return (map negate xs) }
630

Simon Peyton Jones's avatar
Simon Peyton Jones committed
631
As you can guess ``justOnes`` will evaluate to ``Just [-1,-1,-1,...``.
632

Simon Peyton Jones's avatar
Simon Peyton Jones committed
633
634
GHC's implementation the mdo-notation closely follows the original
translation as described in the paper `A recursive do for
niteria's avatar
niteria committed
635
Haskell <http://leventerkok.github.io/papers/recdo.pdf>`__, which
Simon Peyton Jones's avatar
Simon Peyton Jones committed
636
in turn is based on the work `Value Recursion in Monadic
niteria's avatar
niteria committed
637
Computations <http://leventerkok.github.io/papers/erkok-thesis.pdf>`__.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
638
639
Furthermore, GHC extends the syntax described in the former paper with a
lower level syntax flagged by the ``rec`` keyword, as we describe next.
640

Simon Peyton Jones's avatar
Simon Peyton Jones committed
641
642
Recursive binding groups
~~~~~~~~~~~~~~~~~~~~~~~~
643

Simon Peyton Jones's avatar
Simon Peyton Jones committed
644
645
646
647
648
The flag :ghc-flag:`-XRecursiveDo` also introduces a new keyword ``rec``, which
wraps a mutually-recursive group of monadic statements inside a ``do``
expression, producing a single statement. Similar to a ``let`` statement
inside a ``do``, variables bound in the ``rec`` are visible throughout
the ``rec`` group, and below it. For example, compare
649

Simon Peyton Jones's avatar
Simon Peyton Jones committed
650
::
651

Simon Peyton Jones's avatar
Simon Peyton Jones committed
652
653
654
655
        do { a <- getChar            do { a <- getChar
           ; let { r1 = f a r2          ; rec { r1 <- f a r2
           ;     ; r2 = g r1 }          ;     ; r2 <- g r1 }
           ; return (r1 ++ r2) }        ; return (r1 ++ r2) }
656

Simon Peyton Jones's avatar
Simon Peyton Jones committed
657
658
659
660
In both cases, ``r1`` and ``r2`` are available both throughout the
``let`` or ``rec`` block, and in the statements that follow it. The
difference is that ``let`` is non-monadic, while ``rec`` is monadic. (In
Haskell ``let`` is really ``letrec``, of course.)
661

Simon Peyton Jones's avatar
Simon Peyton Jones committed
662
663
664
665
666
The semantics of ``rec`` is fairly straightforward. Whenever GHC finds a
``rec`` group, it will compute its set of bound variables, and will
introduce an appropriate call to the underlying monadic value-recursion
operator ``mfix``, belonging to the ``MonadFix`` class. Here is an
example:
667
668
669

::

Simon Peyton Jones's avatar
Simon Peyton Jones committed
670
671
672
    rec { b <- f a c     ===>    (b,c) <- mfix (\ ~(b,c) -> do { b <- f a c
        ; c <- f b a }                                         ; c <- f b a
                                                               ; return (b,c) })
673

Simon Peyton Jones's avatar
Simon Peyton Jones committed
674
675
676
As usual, the meta-variables ``b``, ``c`` etc., can be arbitrary
patterns. In general, the statement ``rec ss`` is desugared to the
statement
677
678
679

::

Simon Peyton Jones's avatar
Simon Peyton Jones committed
680
    vs <- mfix (\ ~vs -> do { ss; return vs })
681

Simon Peyton Jones's avatar
Simon Peyton Jones committed
682
where ``vs`` is a tuple of the variables bound by ``ss``.
683

Simon Peyton Jones's avatar
Simon Peyton Jones committed
684
685
686
687
Note in particular that the translation for a ``rec`` block only
involves wrapping a call to ``mfix``: it performs no other analysis on
the bindings. The latter is the task for the ``mdo`` notation, which is
described next.
688

Simon Peyton Jones's avatar
Simon Peyton Jones committed
689
690
The ``mdo`` notation
~~~~~~~~~~~~~~~~~~~~
691

Simon Peyton Jones's avatar
Simon Peyton Jones committed
692
693
694
695
696
697
A ``rec``-block tells the compiler where precisely the recursive knot
should be tied. It turns out that the placement of the recursive knots
can be rather delicate: in particular, we would like the knots to be
wrapped around as minimal groups as possible. This process is known as
*segmentation*, and is described in detail in Section 3.2 of `A
recursive do for
niteria's avatar
niteria committed
698
Haskell <http://leventerkok.github.io/papers/recdo.pdf>`__.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
699
700
701
702
703
704
705
706
Segmentation improves polymorphism and reduces the size of the recursive
knot. Most importantly, it avoids unnecessary interference caused by a
fundamental issue with the so-called *right-shrinking* axiom for monadic
recursion. In brief, most monads of interest (IO, strict state, etc.) do
*not* have recursion operators that satisfy this axiom, and thus not
performing segmentation can cause unnecessary interference, changing the
termination behavior of the resulting translation. (Details can be found
in Sections 3.1 and 7.2.2 of `Value Recursion in Monadic
niteria's avatar
niteria committed
707
Computations <http://leventerkok.github.io/papers/erkok-thesis.pdf>`__.)
708

Simon Peyton Jones's avatar
Simon Peyton Jones committed
709
710
711
712
713
714
715
The ``mdo`` notation removes the burden of placing explicit ``rec``
blocks in the code. Unlike an ordinary ``do`` expression, in which
variables bound by statements are only in scope for later statements,
variables bound in an ``mdo`` expression are in scope for all statements
of the expression. The compiler then automatically identifies minimal
mutually recursively dependent segments of statements, treating them as
if the user had wrapped a ``rec`` qualifier around them.
716

Simon Peyton Jones's avatar
Simon Peyton Jones committed
717
The definition is syntactic:
718

Simon Peyton Jones's avatar
Simon Peyton Jones committed
719
-  A generator g *depends* on a textually following generator g'⟩, if
720

Simon Peyton Jones's avatar
Simon Peyton Jones committed
721
   -  ⟨g' defines a variable that is used by g, or
722

Simon Peyton Jones's avatar
Simon Peyton Jones committed
723
724
   -  g'⟩ textually appears between ⟨g⟩ and ⟨g''⟩, where ⟨g⟩ depends on
      ⟨g''⟩.
725

Simon Peyton Jones's avatar
Simon Peyton Jones committed
726
727
728
729
730
-  A *segment* of a given ``mdo``-expression is a minimal sequence of
   generators such that no generator of the sequence depends on an
   outside generator. As a special case, although it is not a generator,
   the final expression in an ``mdo``-expression is considered to form a
   segment by itself.
731

Simon Peyton Jones's avatar
Simon Peyton Jones committed
732
733
734
Segments in this sense are related to *strongly-connected components*
analysis, with the exception that bindings in a segment cannot be
reordered and must be contiguous.
735

Simon Peyton Jones's avatar
Simon Peyton Jones committed
736
737
Here is an example ``mdo``-expression, and its translation to ``rec``
blocks:
738

Simon Peyton Jones's avatar
Simon Peyton Jones committed
739
::
740

Simon Peyton Jones's avatar
Simon Peyton Jones committed
741
742
743
744
745
746
747
    mdo { a <- getChar      ===> do { a <- getChar
        ; b <- f a c                ; rec { b <- f a c
        ; c <- f b a                ;     ; c <- f b a }
        ; z <- h a b                ; z <- h a b
        ; d <- g d e                ; rec { d <- g d e
        ; e <- g a z                ;     ; e <- g a z }
        ; putChar c }               ; putChar c }
748

Simon Peyton Jones's avatar
Simon Peyton Jones committed
749
750
751
752
Note that a given ``mdo`` expression can cause the creation of multiple
``rec`` blocks. If there are no recursive dependencies, ``mdo`` will
introduce no ``rec`` blocks. In this latter case an ``mdo`` expression
is precisely the same as a ``do`` expression, as one would expect.
753

Simon Peyton Jones's avatar
Simon Peyton Jones committed
754
755
756
757
758
759
In summary, given an ``mdo`` expression, GHC first performs
segmentation, introducing ``rec`` blocks to wrap over minimal recursive
groups. Then, each resulting ``rec`` is desugared, using a call to
``Control.Monad.Fix.mfix`` as described in the previous section. The
original ``mdo``-expression typechecks exactly when the desugared
version would do so.
760

Simon Peyton Jones's avatar
Simon Peyton Jones committed
761
Here are some other important points in using the recursive-do notation:
762

Simon Peyton Jones's avatar
Simon Peyton Jones committed
763
764
765
766
-  It is enabled with the flag :ghc-flag:`-XRecursiveDo`, or the
   ``LANGUAGE RecursiveDo`` pragma. (The same flag enables both
   ``mdo``-notation, and the use of ``rec`` blocks inside ``do``
   expressions.)
767

Simon Peyton Jones's avatar
Simon Peyton Jones committed
768
769
770
-  ``rec`` blocks can also be used inside ``mdo``-expressions, which
   will be treated as a single statement. However, it is good style to
   either use ``mdo`` or ``rec`` blocks in a single expression.
771

Simon Peyton Jones's avatar
Simon Peyton Jones committed
772
773
-  If recursive bindings are required for a monad, then that monad must
   be declared an instance of the ``MonadFix`` class.
774

Simon Peyton Jones's avatar
Simon Peyton Jones committed
775
776
777
778
779
-  The following instances of ``MonadFix`` 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).
780

Simon Peyton Jones's avatar
Simon Peyton Jones committed
781
782
783
784
-  Like ``let`` and ``where`` bindings, name shadowing is not allowed
   within an ``mdo``-expression or a ``rec``-block; that is, all the
   names bound in a single ``rec`` must be distinct. (GHC will complain
   if this is not the case.)
785

Simon Peyton Jones's avatar
Simon Peyton Jones committed
786
.. _applicative-do:
787

Simon Peyton Jones's avatar
Simon Peyton Jones committed
788
789
Applicative do-notation
-----------------------
790

Simon Peyton Jones's avatar
Simon Peyton Jones committed
791
792
793
.. index::
   single: Applicative do-notation
   single: do-notation; Applicative
794

Simon Peyton Jones's avatar
Simon Peyton Jones committed
795
.. ghc-flag:: -XApplicativeDo
796

Simon Peyton Jones's avatar
Simon Peyton Jones committed
797
    :since: 8.0.1
798

Simon Peyton Jones's avatar
Simon Peyton Jones committed
799
    Allow use of ``Applicative`` ``do`` notation.
800

Simon Peyton Jones's avatar
Simon Peyton Jones committed
801
802
803
The language option :ghc-flag:`-XApplicativeDo` enables an alternative translation for
the do-notation, which uses the operators ``<$>``, ``<*>``, along with ``join``
as far as possible. There are two main reasons for wanting to do this:
804

Simon Peyton Jones's avatar
Simon Peyton Jones committed
805
806
807
808
-  We can use do-notation with types that are an instance of ``Applicative`` and
   ``Functor``, but not ``Monad``
-  In some monads, using the applicative operators is more efficient than monadic
   bind. For example, it may enable more parallelism.
809

Simon Peyton Jones's avatar
Simon Peyton Jones committed
810
811
812
813
814
Applicative do-notation desugaring preserves the original semantics, provided
that the ``Applicative`` instance satisfies ``<*> = ap`` and ``pure = return``
(these are true of all the common monadic types). Thus, you can normally turn on
:ghc-flag:`-XApplicativeDo` without fear of breaking your program. There is one pitfall
to watch out for; see :ref:`applicative-do-pitfall`.
815

Simon Peyton Jones's avatar
Simon Peyton Jones committed
816
817
818
There are no syntactic changes with :ghc-flag:`-XApplicativeDo`. The only way it shows
up at the source level is that you can have a ``do`` expression that doesn't
require a ``Monad`` constraint. For example, in GHCi: ::
819

Simon Peyton Jones's avatar
Simon Peyton Jones committed
820
821
822
823
    Prelude> :set -XApplicativeDo
    Prelude> :t \m -> do { x <- m; return (not x) }
    \m -> do { x <- m; return (not x) }
      :: Functor f => f Bool -> f Bool
824

Simon Peyton Jones's avatar
Simon Peyton Jones committed
825
826
This example only requires ``Functor``, because it is translated into ``(\x ->
not x) <$> m``. A more complex example requires ``Applicative``, ::
827

Simon Peyton Jones's avatar
Simon Peyton Jones committed
828
829
830
    Prelude> :t \m -> do { x <- m 'a'; y <- m 'b'; return (x || y) }
    \m -> do { x <- m 'a'; y <- m 'b'; return (x || y) }
      :: Applicative f => (Char -> f Bool) -> f Bool
831

Simon Peyton Jones's avatar
Simon Peyton Jones committed
832
Here GHC has translated the expression into ::
833

Simon Peyton Jones's avatar
Simon Peyton Jones committed
834
    (\x y -> x || y) <$> m 'a' <*> m 'b'
835

Simon Peyton Jones's avatar
Simon Peyton Jones committed
836
837
It is possible to see the actual translation by using :ghc-flag:`-ddump-ds`, but be
warned, the output is quite verbose.
838

Simon Peyton Jones's avatar
Simon Peyton Jones committed
839
840
841
842
Note that if the expression can't be translated into uses of ``<$>``, ``<*>``
only, then it will incur a ``Monad`` constraint as usual. This happens when
there is a dependency on a value produced by an earlier statement in the
``do``-block: ::
843

Simon Peyton Jones's avatar
Simon Peyton Jones committed
844
845
846
    Prelude> :t \m -> do { x <- m True; y <- m x; return (x || y) }
    \m -> do { x <- m True; y <- m x; return (x || y) }
      :: Monad m => (Bool -> m Bool) -> m Bool
847

Simon Peyton Jones's avatar
Simon Peyton Jones committed
848
849
Here, ``m x`` depends on the value of ``x`` produced by the first statement, so
the expression cannot be translated using ``<*>``.
850

Simon Peyton Jones's avatar
Simon Peyton Jones committed
851
852
In general, the rule for when a ``do`` statement incurs a ``Monad`` constraint
is as follows. If the do-expression has the following form: ::
853

Simon Peyton Jones's avatar
Simon Peyton Jones committed
854
    do p1 <- E1; ...; pn <- En; return E
855

Simon Peyton Jones's avatar
Simon Peyton Jones committed
856
857
where none of the variables defined by ``p1...pn`` are mentioned in ``E1...En``,
then the expression will only require ``Applicative``. Otherwise, the expression
858
859
will require ``Monad``. The block may return a pure expression ``E`` depending
upon the results ``p1...pn`` with either ``return`` or ``pure``.
860

861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
Note: the final statement must match one of these patterns exactly:

- ``return E``
- ``return $ E``
- ``pure E``
- ``pure $ E``

otherwise GHC cannot recognise it as a ``return`` statement, and the
transformation to use ``<$>`` that we saw above does not apply.  In
particular, slight variations such as ``return . Just $ x`` or ``let x
= e in return x`` would not be recognised.

If the final statement is not of one of these forms, GHC falls back to
standard ``do`` desugaring, and the expression will require a
``Monad`` constraint.
876

Simon Marlow's avatar
Simon Marlow committed
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
When the statements of a ``do`` expression have dependencies between
them, and ``ApplicativeDo`` cannot infer an ``Applicative`` type, it
uses a heuristic algorithm to try to use ``<*>`` as much as possible.
This algorithm usually finds the best solution, but in rare complex
cases it might miss an opportunity.  There is an algorithm that finds
the optimal solution, provided as an option:

.. ghc-flag:: -foptimal-applicative-do

    :since: 8.0.1

    Enables an alternative algorithm for choosing where to use ``<*>``
    in conjunction with the ``ApplicativeDo`` language extension.
    This algorithm always finds the optimal solution, but it is
    expensive: ``O(n^3)``, so this option can lead to long compile
    times when there are very large ``do`` expressions (over 100
    statements).  The default ``ApplicativeDo`` algorithm is ``O(n^2)``.
894

Simon Peyton Jones's avatar
Simon Peyton Jones committed
895
.. _applicative-do-pitfall:
896

Simon Peyton Jones's avatar
Simon Peyton Jones committed
897
898
Things to watch out for
~~~~~~~~~~~~~~~~~~~~~~~
899

Simon Peyton Jones's avatar
Simon Peyton Jones committed
900
901
902
903
Your code should just work as before when :ghc-flag:`-XApplicativeDo` is enabled,
provided you use conventional ``Applicative`` instances. However, if you define
a ``Functor`` or ``Applicative`` instance using do-notation, then it will likely
get turned into an infinite loop by GHC. For example, if you do this: ::
904

Simon Peyton Jones's avatar
Simon Peyton Jones committed
905
906
    instance Functor MyType where
        fmap f m = do x <- m; return (f x)
907

Simon Peyton Jones's avatar
Simon Peyton Jones committed
908
Then applicative desugaring will turn it into ::
909

Simon Peyton Jones's avatar
Simon Peyton Jones committed
910
911
    instance Functor MyType where
        fmap f m = fmap (\x -> f x) m
912

Simon Peyton Jones's avatar
Simon Peyton Jones committed
913
914
And the program will loop at runtime. Similarly, an ``Applicative`` instance
like this ::
915

Simon Peyton Jones's avatar
Simon Peyton Jones committed
916
917
918
    instance Applicative MyType where
        pure = return
        x <*> y = do f <- x; a <- y; return (f a)
919

Simon Peyton Jones's avatar
Simon Peyton Jones committed
920
will result in an infinte loop when ``<*>`` is called.
921

Simon Peyton Jones's avatar
Simon Peyton Jones committed
922
923
924
925
Just as you wouldn't define a ``Monad`` instance using the do-notation, you
shouldn't define ``Functor`` or ``Applicative`` instance using do-notation (when
using ``ApplicativeDo``) either. The correct way to define these instances in
terms of ``Monad`` is to use the ``Monad`` operations directly, e.g. ::
926

Simon Peyton Jones's avatar
Simon Peyton Jones committed
927
928
    instance Functor MyType where
        fmap f m = m >>= return . f
929

Simon Peyton Jones's avatar
Simon Peyton Jones committed
930
931
932
    instance Applicative MyType where
        pure = return
        (<*>) = ap
933
934


Simon Peyton Jones's avatar
Simon Peyton Jones committed
935
.. _parallel-list-comprehensions:
936

Simon Peyton Jones's avatar
Simon Peyton Jones committed
937
938
Parallel List Comprehensions
----------------------------
939

Simon Peyton Jones's avatar
Simon Peyton Jones committed
940
941
942
.. index::
   single: list comprehensions; parallel
   single: parallel list comprehensions
943

Simon Peyton Jones's avatar
Simon Peyton Jones committed
944
.. ghc-flag:: -XParallelListComp
945

Simon Peyton Jones's avatar
Simon Peyton Jones committed
946
    Allow parallel list comprehension syntax.
947

Simon Peyton Jones's avatar
Simon Peyton Jones committed
948
949
950
951
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.
952

Simon Peyton Jones's avatar
Simon Peyton Jones committed
953
954
955
A parallel list comprehension has multiple independent branches of
qualifier lists, each separated by a ``|`` symbol. For example, the
following zips together two lists: ::
956

Simon Peyton Jones's avatar
Simon Peyton Jones committed
957
       [ (x, y) | x <- xs | y <- ys ]
958

Simon Peyton Jones's avatar
Simon Peyton Jones committed
959
960
961
The behaviour of parallel list comprehensions follows that of zip, in
that the resulting list will have the same length as the shortest
branch.
962

Simon Peyton Jones's avatar
Simon Peyton Jones committed
963
964
We can define parallel list comprehensions by translation to regular
comprehensions. Here's the basic idea:
965

Simon Peyton Jones's avatar
Simon Peyton Jones committed
966
Given a parallel comprehension of the form: ::
967

Simon Peyton Jones's avatar
Simon Peyton Jones committed
968
969
970
971
       [ e | p1 <- e11, p2 <- e12, ...
           | q1 <- e21, q2 <- e22, ...
           ...
       ]
972

Simon Peyton Jones's avatar
Simon Peyton Jones committed
973
This will be translated to: ::
974

Simon Peyton Jones's avatar
Simon Peyton Jones committed
975
976
977
978
       [ e | ((p1,p2), (q1,q2), ...) <- zipN [(p1,p2) | p1 <- e11, p2 <- e12, ...]
                                             [(q1,q2) | q1 <- e21, q2 <- e22, ...]
                                             ...
       ]
979

Simon Peyton Jones's avatar
Simon Peyton Jones committed
980
where ``zipN`` is the appropriate zip for the given number of branches.
981

Simon Peyton Jones's avatar
Simon Peyton Jones committed
982
.. _generalised-list-comprehensions:
983

Simon Peyton Jones's avatar
Simon Peyton Jones committed
984
985
Generalised (SQL-like) List Comprehensions
------------------------------------------
986

Simon Peyton Jones's avatar
Simon Peyton Jones committed
987
988
989
990
991
.. index::
   single: list comprehensions; generalised
   single: extended list comprehensions
   single: group
   single: SQL
992

Simon Peyton Jones's avatar
Simon Peyton Jones committed
993
.. ghc-flag:: -XTransformListComp
994

Simon Peyton Jones's avatar
Simon Peyton Jones committed
995
996
    Allow use of generalised list (SQL-like) comprehension syntax. This
    introduces the ``group``, ``by``, and ``using`` keywords.
997

Simon Peyton Jones's avatar
Simon Peyton Jones committed
998
999
1000
1001
1002
1003
Generalised list comprehensions are a further enhancement to the list
comprehension syntactic sugar to allow operations such as sorting and
grouping which are familiar from SQL. They are fully described in the
paper `Comprehensive comprehensions: comprehensions with "order by" and
"group by" <http://research.microsoft.com/~simonpj/papers/list-comp>`__,
except that the syntax we use differs slightly from the paper.
1004

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1005
The extension is enabled with the flag :ghc-flag:`-XTransformListComp`.
1006

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1007
Here is an example:
1008

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1009
::
1010

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1011
1012
1013
1014
1015
    employees = [ ("Simon", "MS", 80)
                , ("Erik", "MS", 100)
                , ("Phil", "Ed", 40)
                , ("Gordon", "Ed", 45)
                , ("Paul", "Yale", 60) ]
1016

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1017
1018
1019
1020
1021
    output = [ (the dept, sum salary)
             | (name, dept, salary) <- employees
             , then group by dept using groupWith
             , then sortWith by (sum salary)
             , then take 5 ]
1022

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1023
In this example, the list ``output`` would take on the value:
1024

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1025
::
1026

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1027
    [("Yale", 60), ("Ed", 85), ("MS", 180)]
1028

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1029
1030
1031
There are three new keywords: ``group``, ``by``, and ``using``. (The
functions ``sortWith`` and ``groupWith`` are not keywords; they are
ordinary functions that are exported by ``GHC.Exts``.)
1032

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1033
1034
There are five new forms of comprehension qualifier, all introduced by
the (existing) keyword ``then``:
1035

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1036
-  ::
1037

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1038
       then f
1039

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1040
1041
1042
1043
1044
1045
1046
1047
1048
   This statement requires that
   f
   have the type
   forall a. [a] -> [a]
   . You can see an example of its use in the motivating example, as
   this form is used to apply
   take 5
   .
-  ::
1049

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1050
       then f by e
1051

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1052
1053
1054
1055
1056
1057
   This form is similar to the previous one, but allows you to create a
   function which will be passed as the first argument to f. As a
   consequence f must have the type
   ``forall a. (a -> t) -> [a] -> [a]``. As you can see from the type,
   this function lets f "project out" some information from the elements
   of the list it is transforming.
1058

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1059
1060
1061
   An example is shown in the opening example, where ``sortWith`` is
   supplied with a function that lets it find out the ``sum salary`` for
   any item in the list comprehension it transforms.
1062

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1063
-  ::
1064

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1065
       then group by e using f
1066

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
   This is the most general of the grouping-type statements. In this
   form, f is required to have type
   ``forall a. (a -> t) -> [a] -> [[a]]``. As with the ``then f by e``
   case above, the first argument is a function supplied to f by the
   compiler which lets it compute e on every element of the list being
   transformed. However, unlike the non-grouping case, f additionally
   partitions the list into a number of sublists: this means that at
   every point after this statement, binders occurring before it in the
   comprehension refer to *lists* of possible values, not single values.
   To help understand this, let's look at an example:
1077

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1078
   ::
1079

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1080
1081
1082
       -- This works similarly to groupWith in GHC.Exts, but doesn't sort its input first
       groupRuns :: Eq b => (a -> b) -> [a] -> [[a]]
       groupRuns f = groupBy (\x y -> f x == f y)
1083

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1084
1085
1086
1087
       output = [ (the x, y)
       | x <- ([1..3] ++ [1..2])
       , y <- [4..6]
       , then group by x using groupRuns ]
1088

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1089
   This results in the variable ``output`` taking on the value below:
1090

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1091
   ::
1092

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1093
       [(1, [4, 5, 6]), (2, [4, 5, 6]), (3, [4, 5, 6]), (1, [4, 5, 6]), (2, [4, 5, 6])]
1094

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1095
1096
1097
1098
   Note that we have used the ``the`` function to change the type of x
   from a list to its original numeric type. The variable y, in
   contrast, is left unchanged from the list form introduced by the
   grouping.
1099

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1100
-  ::
1101

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1102
       then group using f
1103

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1104
1105
1106
1107
   With this form of the group statement, f is required to simply have
   the type ``forall a. [a] -> [[a]]``, which will be used to group up
   the comprehension so far directly. An example of this form is as
   follows:
1108

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1109
   ::
1110

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1111
1112
1113
1114
       output = [ x
       | y <- [1..5]
       , x <- "hello"
       , then group using inits]
1115

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1116
1117
   This will yield a list containing every prefix of the word "hello"
   written out 5 times:
1118

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1119
   ::
1120

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1121
       ["","h","he","hel","hell","hello","helloh","hellohe","hellohel","hellohell","hellohello","hellohelloh",...]
1122

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1123
.. _monad-comprehensions:
1124

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1125
1126
Monad comprehensions
--------------------
1127

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1128
1129
.. index::
   single: monad comprehensions
1130

Ben Gamari's avatar
Ben Gamari committed
1131
1132
1133
1134
1135
1136
.. ghc-flag:: -XMonadComprehensions

    :since: 7.2

    Enable list comprehension syntax for arbitrary monads.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1137
1138
1139
1140
Monad comprehensions generalise the list comprehension notation,
including parallel comprehensions (:ref:`parallel-list-comprehensions`)
and transform comprehensions (:ref:`generalised-list-comprehensions`) to
work for any monad.
1141

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1142
Monad comprehensions support:
1143

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1144
-  Bindings: ::
1145

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1146
       [ x + y | x <- Just 1, y <- Just 2 ]
1147

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1148
1149
   Bindings are translated with the ``(>>=)`` and ``return`` functions
   to the usual do-notation: ::
1150

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1151
1152
1153
       do x <- Just 1
          y <- Just 2
          return (x+y)
1154

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1155
-  Guards: ::
1156

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1157
       [ x | x <- [1..10], x <= 5 ]
1158

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1159
1160
   Guards are translated with the ``guard`` function, which requires a
   ``MonadPlus`` instance: ::
1161

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1162
1163
1164
       do x <- [1..10]
          guard (x <= 5)
          return x
1165

Simon Peyton Jones's avatar