glasgow_exts.rst 606 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
.. 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

34
The language extensions control what variation of the language are
35 36 37 38 39 40 41 42 43 44 45 46
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`).

47 48 49 50
GHC supports these language options:

.. extension-print::
    :type: table
51

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

55
.. ghc-flag:: -fglasgow-exts
56 57 58 59
    :shortdesc: Deprecated. Enable most language extensions;
        see :ref:`options-language` for exactly which ones.
    :type: dynamic
    :reverse: -fno-glasgow-exts
60
    :category: misc
61

62 63
    The flag ``-fglasgow-exts`` is equivalent to enabling the following extensions:

64
    .. include:: what_glasgow_exts_does.rst
65 66 67 68

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

70 71 72 73 74 75 76 77 78 79 80 81 82 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 108

.. extension:: Haskell2010
    :shortdesc: Use the Haskell 2010 language variant.

    Compile Haskell 2010 language variant. Enables the
    following language extensions:

    .. hlist::

     * :extension:`ImplicitPrelude`
     * :extension:`StarIsType`
     * :extension:`CUSKs`
     * :extension:`MonomorphismRestriction`
     * :extension:`DatatypeContexts`
     * :extension:`TraditionalRecordSyntax`
     * :extension:`EmptyDataDecls`
     * :extension:`ForeignFunctionInterface`
     * :extension:`PatternGuards`
     * :extension:`DoAndIfThenElse`
     * :extension:`RelaxedPolyRec`


.. extension:: Haskell98
    :shortdesc: Use the Haskell 2010 language variant.

    Compile using Haskell 98 language variant. Enables the
    following language extensions:

    .. hlist::

     * :extension:`ImplicitPrelude`
     * :extension:`StarIsType`
     * :extension:`CUSKs`
     * :extension:`MonomorphismRestriction`
     * :extension:`NPlusKPatterns`
     * :extension:`DatatypeContexts`
     * :extension:`TraditionalRecordSyntax`
     * :extension:`NondecreasingIndentation`

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
.. _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
124
:ghc-prim-ref:`detailed online documentation <GHC.Prim.>`. (This
125 126 127 128 129
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
130
you need the :extension:`MagicHash` extension.
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

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.
156 157 158
(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.)
159 160 161 162 163 164 165 166
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
167 168
object. Examples include ``Array#``, the type of primitive arrays. Thus,
``Array#`` is an unlifted, boxed type. A
169 170 171 172
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:
173
no unevaluated thunks, no indirections. Nothing can be at the other end
174 175 176 177
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.

178 179
Unboxed type kinds
------------------
180

181
Because unboxed types are represented without the use of pointers, we
182 183
cannot store them in use a polymorphic datatype at an unboxed type.
For example, the ``Just`` node
184 185 186 187 188 189
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.

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
The Haskell Report describes that ``*`` (spelled ``Type`` and imported from
``Data.Kind`` in the GHC dialect of Haskell) is the kind of ordinary datatypes,
such as ``Int``. Furthermore, type constructors can have kinds with arrows; for
example, ``Maybe`` has kind ``Type -> Type``. 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 floating
point. In contrast, the kind ``Type`` is actually just a synonym for ``TYPE
'LiftedRep``. More details of the ``TYPE`` mechanisms appear in the `section
on runtime representation polymorphism <#runtime-rep>`__.

Given that ``Int#``'s kind is not ``Type``, it then it follows that ``Maybe
Int#`` is disallowed. Similarly, because type variables tend to be of kind
``Type`` (for example, in ``(.) :: (b -> c) -> (a -> b) -> a -> c``, all the
type variables have kind ``Type``), 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.
209 210

There are some restrictions on the use of primitive types:
211 212 213 214 215 216 217 218 219

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

220
   However, this restriction can be relaxed by enabling
221
   :extension:`UnliftedNewtypes`.  The `section on unlifted newtypes
222 223
   <#unlifted-newtypes>`__ details the behavior of such types.

224 225 226 227 228 229 230
-  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)
Richard Eisenberg's avatar
Richard Eisenberg committed
231 232 233
   pattern binding, but you must make any such pattern-match strict.
   (Failing to do so emits a warning :ghc-flag:`-Wunbanged-strict-patterns`.)
   For example, rather than:
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

   ::

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

256 257
.. extension:: UnboxedTuples
    :shortdesc: Enable the use of unboxed tuple syntax.
258 259

    :since: 6.8.1
260

261 262

Unboxed tuples aren't really exported by ``GHC.Exts``; they are a
263
syntactic extension (:extension:`UnboxedTuples`). An
264
unboxed tuple looks like this: ::
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

    (# 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:

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

314 315 316 317 318
.. _unboxed-sums:

Unboxed sums
------------

319 320
.. extension:: UnboxedSums
    :shortdesc: Enable unboxed sums.
321 322

    :since: 8.2.1
323 324 325 326 327 328 329 330

    Enable the use of unboxed sum syntax.

`-XUnboxedSums` enables new syntax for anonymous, unboxed sum types. The syntax
for an unboxed sum type with N alternatives is ::

    (# t_1 | t_2 | ... | t_N #)

331 332
where ``t_1`` ... ``t_N`` are types (which can be unlifted, including unboxed
tuples and sums).
333 334 335 336 337

Unboxed tuples can be used for multi-arity alternatives. For example: ::

    (# (# Int, String #) | Bool #)

338 339
The term level syntax is similar. Leading and preceding bars (`|`) indicate which
alternative it is. Here are two terms of the type shown above: ::
340 341 342 343 344

    (# (# 1, "foo" #) | #) -- first alternative

    (# | True #) -- second alternative

345
The pattern syntax reflects the term syntax: ::
346 347 348 349 350 351 352 353

    case x of
      (# (# i, str #) | #) -> ...
      (# | bool #) -> ...

Unboxed sums are "unboxed" in the sense that, instead of allocating sums in the
heap and representing values as pointers, unboxed sums are represented as their
components, just like unboxed tuples. These "components" depend on alternatives
354 355 356 357 358 359 360
of a sum type. Like unboxed tuples, unboxed sums are lazy in their lifted
components.

The code generator tries to generate as compact layout as possible for each
unboxed sum. In the best case, size of an unboxed sum is size of its biggest
alternative plus one word (for a tag). The algorithm for generating the memory
layout for a sum type works like this:
361 362 363 364 365

- All types are classified as one of these classes: 32bit word, 64bit word,
  32bit float, 64bit float, pointer.

- For each alternative of the sum type, a layout that consists of these fields
366 367 368
  is generated. For example, if an alternative has ``Int``, ``Float#`` and
  ``String`` fields, the layout will have an 32bit word, 32bit float and
  pointer fields.
369 370

- Layout fields are then overlapped so that the final layout will be as compact
371
  as possible. For example, suppose we have the unboxed sum: ::
372

373 374
    (# (# Word32#, String, Float# #)
    |  (# Float#, Float#, Maybe Int #) #)
375

376
  The final layout will be something like ::
377 378 379

    Int32, Float32, Float32, Word32, Pointer

380 381 382 383 384 385
  The first ``Int32`` is for the tag. There are two ``Float32`` fields because
  floating point types can't overlap with other types, because of limitations of
  the code generator that we're hoping to overcome in the future. The second
  alternative needs two ``Float32`` fields: The ``Word32`` field is for the
  ``Word32#`` in the first alternative. The ``Pointer`` field is shared between
  ``String`` and ``Maybe Int`` values of the alternatives.
386

387 388
  As another example, this is the layout for the unboxed version of ``Maybe a``
  type, ``(# (# #) | a #)``: ::
389 390 391

    Int32, Pointer

392 393 394 395 396 397 398 399 400 401 402 403
  The ``Pointer`` field is not used when tag says that it's ``Nothing``.
  Otherwise ``Pointer`` points to the value in ``Just``. As mentioned
  above, this type is lazy in its lifted field. Therefore, the type ::

    data Maybe' a = Maybe' (# (# #) | a #)

  is *precisely* isomorphic to the type ``Maybe a``, although its memory
  representation is different.

  In the degenerate case where all the alternatives have zero width, such
  as the ``Bool``-like ``(# (# #) | (# #) #)``, the unboxed sum layout only
  has an ``Int32`` tag field (i.e., the whole thing is represented by an integer).
404

405 406 407 408 409 410 411 412 413 414 415 416
.. _unlifted-newtypes:

Unlifted Newtypes
-----------------

.. extension:: UnliftedNewtypes
    :shortdesc: Enable unlifted newtypes.

    :since: 8.10.1

    Enable the use of newtypes over types with non-lifted runtime representations.

417 418 419
GHC implements an :extension:`UnliftedNewtypes` extension as specified in
`this GHC proposal <https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0013-unlifted-newtypes.rst>`_.
:extension:`UnliftedNewtypes` relaxes the restrictions around what types can appear inside
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
of a `newtype`. For example, the type ::

    newtype A = MkA Int#

is accepted when this extension is enabled. This creates a type
``A :: TYPE 'IntRep`` and a data constructor ``MkA :: Int# -> A``.
Although the kind of ``A`` is inferred by GHC, there is nothing visually
distictive about this type that indicated that is it not of kind ``Type``
like newtypes typically are. `GADTSyntax <#gadt-style>`__ can be used to
provide a kind signature for additional clarity ::

    newtype A :: TYPE 'IntRep where
      MkA :: Int# -> A

The ``Coercible`` machinery works with unlifted newtypes just like it does with
lifted types. In either of the equivalent formulations of ``A`` given above,
users would additionally have access to a coercion between ``A`` and ``Int#``.

As a consequence of the
`levity-polymorphic binder restriction <#levity-polymorphic-restrictions>`__,
levity-polymorphic fields are disallowed in data constructors
of data types declared using ``data``. However, since ``newtype`` data
constructor application is implemented as a coercion instead of as function
application, this restriction does not apply to the field inside a ``newtype``
data constructor. Thus, the type checker accepts ::

    newtype Identity# :: forall (r :: RuntimeRep). TYPE r -> TYPE r where
      MkIdentity# :: forall (r :: RuntimeRep) (a :: TYPE r). a -> Identity# a

And with `UnboxedSums <#unboxed-sums>`__ enabled ::

    newtype Maybe# :: forall (r :: RuntimeRep). TYPE r -> TYPE (SumRep '[r, TupleRep '[]]) where
      MkMaybe# :: forall (r :: RuntimeRep) (a :: TYPE r). (# a | (# #) #) -> Maybe# a

454 455 456 457 458
This extension also relaxes some of the restrictions around data family
instances. In particular, :extension:`UnliftedNewtypes` permits a
``newtype instance`` to be given a return kind of ``TYPE r``, not just
``Type``. For example, the following ``newtype instance`` declarations would be
permitted: ::
459

460 461 462 463 464 465 466 467 468 469
     class Foo a where
       data FooKey a :: TYPE 'IntRep
     class Bar (r :: RuntimeRep) where
       data BarType r :: TYPE r

     instance Foo Bool where
       newtype FooKey Bool = FooKeyBoolC Int#
     instance Bar 'WordRep where
       newtype BarType 'WordRep = BarTypeWordRepC Word#

470 471 472 473 474 475
It is worth noting that :extension:`UnliftedNewtypes` is *not* required to give
the data families themselves return kinds involving ``TYPE``, such as the
``FooKey`` and ``BarType`` examples above. The extension is
only required for ``newtype instance`` declarations, such as ``FooKeyBoolC``
and ``BarTypeWorkRepC`` above.

476 477 478 479
This extension impacts the determination of whether or not a newtype has
a Complete User-Specified Kind Signature (CUSK). The exact impact is specified
`the section on CUSKs <#complete-kind-signatures>`__.

480 481 482 483 484 485 486 487 488 489
.. _syntax-extns:

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

.. _unicode-syntax:

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

490 491
.. extension:: UnicodeSyntax
    :shortdesc: Enable unicode syntax.
492 493

    :since: 6.8.1
494 495 496 497

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

498
The language extension :extension:`UnicodeSyntax` enables
499 500 501
Unicode characters to be used to stand for certain ASCII character
sequences. The following alternatives are provided:

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
+--------------+---------------+-------------+-----------------------------------------+
| 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 |
+--------------+---------------+-------------+-----------------------------------------+
534 535 536 537 538 539

.. _magic-hash:

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

540 541
.. extension:: MagicHash
    :shortdesc: Allow ``#`` as a postfix modifier on identifiers.
542 543

    :since: 6.8.1
544

545
    Enables the use of the hash character (``#``) as an identifier suffix.
546

547
The language extension :extension:`MagicHash` allows ``#`` as a postfix modifier
548
to identifiers. Thus, ``x#`` is a valid variable, and ``T#`` is a valid type
549 550 551 552 553
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
554
variables. Nor does the :extension:`MagicHash` extension bring anything into
555
scope. For example, to bring ``Int#`` into scope you must import
556
``GHC.Prim`` (see :ref:`primitives`); the :extension:`MagicHash` extension then
557 558 559 560 561
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``.

562
The :extension:`MagicHash` also enables some new forms of literals (see
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
: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
-----------------

585 586
.. extension:: NegativeLiterals
    :shortdesc: Enable support for negative literals.
587

588 589
    :since: 7.8.1

590 591
    Enable the use of un-parenthesized negative numeric literals.

592 593
The literal ``-123`` is, according to Haskell98 and Haskell 2010,
desugared as ``negate (fromInteger 123)``. The language extension
594
:extension:`NegativeLiterals` means that it is instead desugared as
595 596 597 598 599 600 601 602 603 604 605 606
``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
-----------------------------------

607
.. extension:: NumDecimals
608
    :shortdesc: Enable support for 'fractional' integer literals.
609

610 611
    :since: 7.8.1

612 613
    Allow the use of floating-point literal syntax for integral types.

614 615 616
Haskell 2010 and Haskell 98 define floating literals with the syntax
``1.2e6``. These literals have the type ``Fractional a => a``.

617
The language extension :extension:`NumDecimals` allows you to also use the
618 619 620 621 622 623 624 625
floating literal syntax for instances of ``Integral``, and have values
like ``(1.2e6 :: Num a => a)``

.. _binary-literals:

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

626 627
.. extension:: BinaryLiterals
    :shortdesc: Enable support for binary literals.
628

629 630
    :since: 7.10.1

631 632
    Allow the use of binary notation in integer literals.

633 634 635 636
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``).

637
The language extension :extension:`BinaryLiterals` adds support for expressing
638 639
integer literals in binary notation with the prefix ``0b`` or ``0B``. For
instance, the binary integer literal ``0b11001001`` will be desugared into
640
``fromInteger 201`` when :extension:`BinaryLiterals` is enabled.
641

642 643 644 645 646
.. _hex-float-literals:

Hexadecimal floating point literals
-----------------------------------

647
.. extension:: HexFloatLiterals
Douglas Wilson's avatar
Douglas Wilson committed
648
    :shortdesc: Enable support for :ref:`hexadecimal floating point literals <hex-float-literals>`.
649 650 651 652 653 654 655 656 657 658 659 660

    :since: 8.4.1

    Allow writing floating point literals using hexadecimal notation.

The hexadecimal notation for floating point literals is useful when you
need to specify floating point constants precisely, as the literal notation
corresponds closely to the underlying bit-encoding of the number.

In this notation floating point numbers are written using hexadecimal digits,
and so the digits are interpreted using base 16, rather then the usual 10.
This means that digits left of the decimal point correspond to positive
661
powers of 16, while the ones to the right correspond to negative ones.
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682

You may also write an explicit exponent, which is similar to the exponent
in decimal notation with the following differences:
- the exponent begins with ``p`` instead of ``e``
- the exponent is written in base ``10`` (**not** 16)
- the base of the exponent is ``2`` (**not** 16).

In terms of the underlying bit encoding, each hexadecimal digit corresponds
to 4 bits, and you may think of the exponent as "moving" the floating point
by one bit left (negative) or right (positive).  Here are some examples:

-  ``0x0.1``     is the same as ``1/16``
-  ``0x0.01``    is the same as ``1/256``
-  ``0xF.FF``    is the same as ``15 + 15/16 + 15/256``
-  ``0x0.1p4``   is the same as ``1``
-  ``0x0.1p-4``  is the same as ``1/256``
-  ``0x0.1p12``  is the same as ``256``




683 684 685 686 687
.. _numeric-underscores:

Numeric underscores
-------------------

688
.. extension:: NumericUnderscores
689 690 691 692 693 694 695 696 697
    :shortdesc: Enable support for :ref:`numeric underscores <numeric-underscores>`.

    :since: 8.6.1

    Allow the use of underscores in numeric literals.

GHC allows for numeric literals to be given in decimal, octal, hexadecimal,
binary, or float notation.

698
The language extension :extension:`NumericUnderscores` adds support for expressing
699 700
underscores in numeric literals.
For instance, the numeric literal ``1_000_000`` will be parsed into
701
``1000000`` when :extension:`NumericUnderscores` is enabled.
702
That is, underscores in numeric literals are ignored when
703
:extension:`NumericUnderscores` is enabled.
704 705
See also :ghc-ticket:`14473`.

706 707 708
For example:

.. code-block:: none
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739

    -- decimal
    million    = 1_000_000
    billion    = 1_000_000_000
    lightspeed = 299_792_458
    version    = 8_04_1
    date       = 2017_12_31

    -- hexadecimal
    red_mask = 0xff_00_00
    size1G   = 0x3fff_ffff

    -- binary
    bit8th   = 0b01_0000_0000
    packbits = 0b1_11_01_0000_0_111
    bigbits  = 0b1100_1011__1110_1111__0101_0011

    -- float
    pi       = 3.141_592_653_589_793
    faraday  = 96_485.332_89
    avogadro = 6.022_140_857e+23

    -- function
    isUnderMillion = (< 1_000_000)

    clip64M x
        | x > 0x3ff_ffff = 0x3ff_ffff
        | otherwise = x

    test8bit x = (0b01_0000_0000 .&. x) /= 0

740 741 742
About validity:

.. code-block:: none
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770

    x0 = 1_000_000   -- valid
    x1 = 1__000000   -- valid
    x2 = 1000000_    -- invalid
    x3 = _1000000    -- invalid

    e0 = 0.0001      -- valid
    e1 = 0.000_1     -- valid
    e2 = 0_.0001     -- invalid
    e3 = _0.0001     -- invalid
    e4 = 0._0001     -- invalid
    e5 = 0.0001_     -- invalid

    f0 = 1e+23       -- valid
    f1 = 1_e+23      -- valid
    f2 = 1__e+23     -- valid
    f3 = 1e_+23      -- invalid

    g0 = 1e+23       -- valid
    g1 = 1e+_23      -- invalid
    g2 = 1e+23_      -- invalid

    h0 = 0xffff      -- valid
    h1 = 0xff_ff     -- valid
    h2 = 0x_ffff     -- valid
    h3 = 0x__ffff    -- valid
    h4 = _0xffff     -- invalid

771 772 773 774 775
.. _pattern-guards:

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

776 777 778
.. extension:: NoPatternGuards
    :shortdesc: Disable pattern guards.
        Implied by :extension:`Haskell98`.
779

780
    :implied by: :extension:`Haskell98`
781 782
    :since: 6.8.1

783
Disable `pattern guards
784
<http://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-460003.13>`__.
785

786 787 788 789 790
.. _view-patterns:

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

791 792
.. extension:: ViewPatterns
    :shortdesc: Enable view patterns.
793 794

    :since: 6.10.1
795 796 797

    Allow use of view pattern syntax.

798
View patterns are enabled by the language extension :extension:`ViewPatterns`. More
799
information and examples of view patterns can be found on the
800
:ghc-wiki:`Wiki page <view-patterns>`.
801 802 803 804 805

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
806
language as follows: ::
807 808 809 810 811 812 813 814 815 816 817 818

    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
819
Without view patterns, using this signature is a little inconvenient: ::
820 821 822 823 824 825 826 827 828 829 830

    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
831
matching against the result: ::
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

    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
853
   :ref:`pattern-guards` can be written using view patterns as follows: ::
854 855 856 857 858 859 860

       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
861
      view pattern expression are in scope. For example: ::
862 863

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

      Additionally, in function definitions, variables bound by matching
      earlier curried arguments may be used in view pattern expressions
868
      in later arguments: ::
869 870 871 872 873 874 875 876 877 878 879

          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
880
      allowed: ::
881 882 883 884 885 886 887 888 889 890

          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
891
   Report <http://www.haskell.org/onlinereport/>`__, add the following: ::
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926

       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
927
.. _n-k-patterns:
928

Simon Peyton Jones's avatar
Simon Peyton Jones committed
929 930
n+k patterns
------------
931

932
.. extension:: NPlusKPatterns
933
    :shortdesc: Enable support for ``n+k`` patterns.
934
        Implied by :extension:`Haskell98`.
935

936
    :implied by: :extension:`Haskell98`
937
    :since: 6.12.1
Ben Gamari's avatar
Ben Gamari committed
938

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
941
.. _recursive-do-notation:
942

Simon Peyton Jones's avatar
Simon Peyton Jones committed
943 944
The recursive do-notation
-------------------------
945

946 947
.. extension:: RecursiveDo
    :shortdesc: Enable recursive do (mdo) notation.
948 949

    :since: 6.8.1
950

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
953 954 955 956
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.
957

Simon Peyton Jones's avatar
Simon Peyton Jones committed
958 959 960 961 962
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: ::
963

Simon Peyton Jones's avatar
Simon Peyton Jones committed
964 965
    class Monad m => MonadFix m where
       mfix :: (a -> m a) -> m a
966

Simon Peyton Jones's avatar
Simon Peyton Jones committed
967 968 969 970
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.
971

Simon Peyton Jones's avatar
Simon Peyton Jones committed
972 973
For monads that do belong to the ``MonadFix`` class, GHC provides an
extended version of the do-notation that allows recursive bindings. The
974
:extension:`RecursiveDo` (language pragma: ``RecursiveDo``) provides the
Simon Peyton Jones's avatar
Simon Peyton Jones committed
975 976 977 978 979
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*.
980

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
983
::
984

Simon Peyton Jones's avatar
Simon Peyton Jones committed
985 986 987
    {-# LANGUAGE RecursiveDo #-}
    justOnes = mdo { xs <- Just (1:xs)
                   ; return (map negate xs) }
988

Simon Peyton Jones's avatar
Simon Peyton Jones committed
989
or equivalently
990

Simon Peyton Jones's avatar
Simon Peyton Jones committed
991
::
992

Simon Peyton Jones's avatar
Simon Peyton Jones committed
993 994 995
    {-# LANGUAGE RecursiveDo #-}
    justOnes = do { rec { xs <- Just (1:xs) }
                  ; return (map negate xs) }
996

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
999 1000
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
1001
Haskell <http://leventerkok.github.io/papers/recdo.pdf>`__, which
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1002
in turn is based on the work `Value Recursion in Monadic
niteria's avatar
niteria committed
1003
Computations <http://leventerkok.github.io/papers/erkok-thesis.pdf>`__.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1004 1005
Furthermore, GHC extends the syntax described in the former paper with a
lower level syntax flagged by the ``rec`` keyword, as we describe next.
1006

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1007 1008
Recursive binding groups
~~~~~~~~~~~~~~~~~~~~~~~~
1009

1010
The extension :extension:`RecursiveDo` also introduces a new keyword ``rec``, which
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1011 1012 1013 1014
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
1015

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1016
::
1017

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1018 1019 1020 1021
        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) }
1022

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1023 1024 1025 1026
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.)
1027

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1028 1029 1030 1031 1032
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:
1033 1034 1035

::

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1036 1037 1038
    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) })
1039

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1040 1041 1042
As usual, the meta-variables ``b``, ``c`` etc., can be arbitrary
patterns. In general, the statement ``rec ss`` is desugared to the
statement
1043 1044 1045

::

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

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1050 1051 1052 1053
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.
1054

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1055 1056
The ``mdo`` notation
~~~~~~~~~~~~~~~~~~~~
1057

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1058 1059 1060 1061 1062 1063
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
1064
Haskell <http://leventerkok.github.io/papers/recdo.pdf>`__.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1065 1066 1067 1068 1069 1070 1071 1072
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
1073
Computations <http://leventerkok.github.io/papers/erkok-thesis.pdf>`__.)
1074

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1075 1076 1077 1078 1079 1080 1081
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.
1082

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1083
The definition is syntactic:
1084

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1087
   -  ⟨g'⟩ defines a variable that is used by ⟨g⟩, or
1088

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1089 1090
   -  ⟨g'⟩ textually appears between ⟨g⟩ and ⟨g''⟩, where ⟨g⟩ depends on
      ⟨g''⟩.
1091

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1092 1093 1094 1095 1096
-  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.
1097

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1098 1099 1100
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.
1101

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1102 1103
Here is an example ``mdo``-expression, and its translation to ``rec``
blocks:
1104

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1105
::
1106

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1107 1108 1109 1110 1111 1112 1113
    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 }
1114

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1115 1116 1117 1118
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.
1119

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1120 1121 1122 1123 1124 1125
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.
1126

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

1129 1130
-  It is enabled with the extension :extension:`RecursiveDo`, or the
   ``LANGUAGE RecursiveDo`` pragma. (The same extension enables both
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1131 1132
   ``mdo``-notation, and the use of ``rec`` blocks inside ``do``
   expressions.)
1133

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1134 1135 1136
-  ``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.
1137

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1141 1142 1143 1144 1145
-  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).
1146

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1147 1148 1149 1150
-  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.)
1151

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1152
.. _applicative-do:
1153

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1154 1155
Applicative do-notation
-----------------------
1156

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1157 1158 1159
.. index::
   single: Applicative do-notation
   single: do-notation; Applicative
1160

1161 1162
.. extension:: ApplicativeDo
    :shortdesc: Enable Applicative do-notation desugaring
1163

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1164
    :since: 8.0.1
1165

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1166
    Allow use of ``Applicative`` ``do`` notation.
1167

1168
The language option :extension:`ApplicativeDo` enables an alternative translation for
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1169 1170
the do-notation, which uses the operators ``<$>``, ``<*>``, along with ``join``
as far as possible. There are two main reasons for wanting to do this:
1171

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1172 1173 1174 1175
-  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.
1176

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1177 1178 1179
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
1180
:extension:`ApplicativeDo` without fear of breaking your program. There is one pitfall
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1181
to watch out for; see :ref:`applicative-do-pitfall`.
1182

1183
There are no syntactic changes with :extension:`ApplicativeDo`. The only way it shows
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1184 1185
up at the source level is that you can have a ``do`` expression that doesn't
require a ``Monad`` constraint. For example, in GHCi: ::
1186

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1187 1188 1189 1190
    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
1191

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1195 1196 1197
    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
1198

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1199
Here GHC has translated the expression into ::
1200

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

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1206 1207 1208 1209
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: ::
1210

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1211 1212 1213
    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
1214

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

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

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1223
where none of the variables defined by ``p1...pn`` are mentioned in ``E1...En``,
1224
and ``p1...pn`` are all variables or lazy patterns,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1225
then the expression will only require ``Applicative``. Otherwise, the expression
1226 1227
will require ``Monad``. The block may return a pure expression ``E`` depending
upon the results ``p1...pn`` with either ``return`` or ``pure``.
1228

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
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.
1244

Simon Marlow's avatar
Simon Marlow committed
1245 1246 1247 1248 1249 1250 1251 1252
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
1253 1254 1255 1256
    :shortdesc: Use a slower but better algorithm for ApplicativeDo
    :type: dynamic
    :reverse: -fno-optimal-applicative-do
    :category: optimization
Simon Marlow's avatar
Simon Marlow committed
1257 1258 1259 1260 1261 1262 1263 1264 1265

    :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)``.
1266

1267

1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
.. _applicative-do-strict:

Strict patterns
~~~~~~~~~~~~~~~


A strict pattern match in a bind statement prevents
``ApplicativeDo`` from transforming that statement to use
``Applicative``.  This is because the transformation would change the
semantics by making the expression lazier.

For example, this code will require a ``Monad`` constraint::

    > :t \m -> do { (x:xs) <- m; return x }
    \m -> do { (x:xs) <- m; return x } :: Monad m => m [b] -> m b

but making the pattern match lazy allows it to have a ``Functor`` constraint::

    > :t \m -> do { ~(x:xs) <- m; return x }
    \m -> do { ~(x:xs) <- m; return x } :: Functor f => f [b] -> f b

A "strict pattern match" is any pattern match that can fail.  For
example, ``()``, ``(x:xs)``, ``!z``, and ``C x`` are strict patterns,
but ``x`` and ``~(1,2)`` are not.  For the purposes of
``ApplicativeDo``, a pattern match against a ``newtype`` constructor
is considered strict.

When there's a strict pattern match in a sequence of statements,
``ApplicativeDo`` places a ``>>=`` between that statement and the one
that follows it.  The sequence may be transformed to use ``<*>``
elsewhere, but the strict pattern match and the following statement
will always be connected with ``>>=``, to retain the same strictness
semantics as the standard do-notation.  If you don't want this, simply
put a ``~`` on the pattern match to make it lazy.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1303
.. _applicative-do-pitfall:
1304

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1305 1306
Things to watch out for
~~~~~~~~~~~~~~~~~~~~~~~
1307

1308
Your code should just work as before when :extension:`ApplicativeDo` is enabled,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1309 1310 1311
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: ::
1312

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1313 1314
    instance Functor MyType where
        fmap f m = do x <- m; return (f x)
1315

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1316
Then applicative desugaring will turn it into ::
1317

Simon Peyton Jones's avatar
Simon Peyton Jones committed