2 single: language, GHC extensions
4 As with all known Haskell systems, GHC implements some extensions to the
5 standard Haskell language. They can all be enabled or disabled by command line
6 flags or language pragmas. By default GHC understands the most recent Haskell
7 version it supports, plus a handful of extensions.
9 Some of the Glasgow extensions serve to give you access to the
10 underlying facilities with which we implement Haskell. Thus, you can get
11 at the Raw Iron, if you are willing to write some non-portable code at a
12 more primitive level. You need not be “stuck” on performance because of
13 the implementation costs of Haskell's "high-level" features—you can
14 always code "under" them. In an extreme case, you can write all your
15 time-critical code in C, and then just glue it together with Haskell!
17 Before you get too carried away working at the lowest level (e.g.,
18 sloshing ``MutableByteArray#``\ s around your program), you may wish to
19 check if there are libraries that provide a "Haskellised veneer" over
20 the features you want. The separate
21 `libraries documentation <../libraries/index.html>`__ describes all the
22 libraries that come with GHC.
30 single: language; option
31 single: options; language
32 single: extensions; options controlling
34 The language extensions control what variation of the language are
37 Language options can be controlled in two ways:
39 - Every language option can switched on by a command-line flag
40 "``-X...``" (e.g. ``-XTemplateHaskell``), and switched off by the
41 flag "``-XNo...``"; (e.g. ``-XNoTemplateHaskell``).
43 - Language options recognised by Cabal can also be enabled using the
44 ``LANGUAGE`` pragma, thus ``{-# LANGUAGE TemplateHaskell #-}`` (see
45 :ref:`language-pragma`).
47 GHC supports these language options:
52 Although not recommended, the deprecated :ghc-flag:`-fglasgow-exts` flag enables
53 a large swath of the extensions supported by GHC at once.
55 .. ghc-flag:: -fglasgow-exts
56 :shortdesc: Deprecated. Enable most language extensions;
57 see :ref:`options-language` for exactly which ones.
59 :reverse: -fno-glasgow-exts
62 The flag ``-fglasgow-exts`` is equivalent to enabling the following extensions:
64 .. include:: what_glasgow_exts_does.rst
66 Enabling these options is the *only* effect of ``-fglasgow-exts``. We are trying
67 to move away from this portmanteau flag, and towards enabling features
72 Unboxed types and primitive operations
73 ======================================
75 GHC is built on a raft of primitive data types and operations;
76 "primitive" in the sense that they cannot be defined in Haskell itself.
77 While you really can use this stuff to write fast code, we generally
78 find it a lot less painful, and more satisfying in the long run, to use
79 higher-level language features and libraries. With any luck, the code
80 you write will be optimised to the efficient unboxed version in any
81 case. And if it isn't, we'd like to know about it.
83 All these primitive data types and operations are exported by the
84 library ``GHC.Prim``, for which there is
85 :ghc-prim-ref:`detailed online documentation <GHC.Prim.>`. (This
86 documentation is generated from the file ``compiler/prelude/primops.txt.pp``.)
88 If you want to mention any of the primitive data types or operations in
89 your program, you must first import ``GHC.Prim`` to bring them into
90 scope. Many of them have names ending in ``#``, and to mention such names
91 you need the :extension:`MagicHash` extension.
93 The primops make extensive use of `unboxed types <#glasgow-unboxed>`__
94 and `unboxed tuples <#unboxed-tuples>`__, which we briefly summarise
102 Most types in GHC are boxed, which means that values of that type are
103 represented by a pointer to a heap object. The representation of a
104 Haskell ``Int``, for example, is a two-word heap object. An unboxed
105 type, however, is represented by the value itself, no pointers or heap
106 allocation are involved.
108 Unboxed types correspond to the “raw machine” types you would use in C:
109 ``Int#`` (long int), ``Double#`` (double), ``Addr#`` (void \*), etc. The
110 *primitive operations* (PrimOps) on these types are what you might
111 expect; e.g., ``(+#)`` is addition on ``Int#``\ s, and is the
112 machine-addition that we all know and love—usually one instruction.
114 Primitive (unboxed) types cannot be defined in Haskell, and are
115 therefore built into the language and compiler. Primitive types are
116 always unlifted; that is, a value of a primitive type cannot be bottom.
117 (Note: a "boxed" type means that a value is represented by a pointer to a heap
118 object; a "lifted" type means that terms of that type may be bottom. See
119 the next paragraph for an example.)
120 We use the convention (but it is only a convention) that primitive
121 types, values, and operations have a ``#`` suffix (see
122 :ref:`magic-hash`). For some primitive types we have special syntax for
123 literals, also described in the `same section <#magic-hash>`__.
125 Primitive values are often represented by a simple bit-pattern, such as
126 ``Int#``, ``Float#``, ``Double#``. But this is not necessarily the case:
127 a primitive value might be represented by a pointer to a heap-allocated
128 object. Examples include ``Array#``, the type of primitive arrays. Thus,
129 ``Array#`` is an unlifted, boxed type. A
130 primitive array is heap-allocated because it is too big a value to fit
131 in a register, and would be too expensive to copy around; in a sense, it
132 is accidental that it is represented by a pointer. If a pointer
133 represents a primitive value, then it really does point to that value:
134 no unevaluated thunks, no indirections. Nothing can be at the other end
135 of the pointer than the primitive value. A numerically-intensive program
136 using unboxed types can go a *lot* faster than its “standard”
137 counterpart—we saw a threefold speedup on one example.
142 Because unboxed types are represented without the use of pointers, we
143 cannot store them in use a polymorphic datatype at an unboxed type.
144 For example, the ``Just`` node
145 of ``Just 42#`` would have to be different from the ``Just`` node of
146 ``Just 42``; the former stores an integer directly, while the latter
147 stores a pointer. GHC currently does not support this variety of ``Just``
148 nodes (nor for any other datatype). Accordingly, the *kind* of an unboxed
149 type is different from the kind of a boxed type.
151 The Haskell Report describes that ``*`` (spelled ``Type`` and imported from
152 ``Data.Kind`` in the GHC dialect of Haskell) is the kind of ordinary datatypes,
153 such as ``Int``. Furthermore, type constructors can have kinds with arrows; for
154 example, ``Maybe`` has kind ``Type -> Type``. Unboxed types have a kind that
155 specifies their runtime representation. For example, the type ``Int#`` has kind
156 ``TYPE 'IntRep`` and ``Double#`` has kind ``TYPE 'DoubleRep``. These kinds say
157 that the runtime representation of an ``Int#`` is a machine integer, and the
158 runtime representation of a ``Double#`` is a machine double-precision floating
159 point. In contrast, the kind ``Type`` is actually just a synonym for ``TYPE
160 'LiftedRep``. More details of the ``TYPE`` mechanisms appear in the `section
161 on runtime representation polymorphism <#runtime-rep>`__.
163 Given that ``Int#``'s kind is not ``Type``, it then it follows that ``Maybe
164 Int#`` is disallowed. Similarly, because type variables tend to be of kind
165 ``Type`` (for example, in ``(.) :: (b -> c) -> (a -> b) -> a -> c``, all the
166 type variables have kind ``Type``), polymorphism tends not to work over
167 primitive types. Stepping back, this makes some sense, because a polymorphic
168 function needs to manipulate the pointers to its data, and most primitive types
171 There are some restrictions on the use of primitive types:
173 - You cannot define a newtype whose representation type (the argument
174 type of the data constructor) is an unboxed type. Thus, this is
181 - You cannot bind a variable with an unboxed type in a *top-level*
184 - You cannot bind a variable with an unboxed type in a *recursive*
187 - You may bind unboxed variables in a (non-recursive, non-top-level)
188 pattern binding, but you must make any such pattern-match strict.
189 (Failing to do so emits a warning :ghc-flag:`-Wunbanged-strict-patterns`.)
190 For example, rather than:
194 data Foo = Foo Int Int#
196 f x = let (Foo a b, w) = ..rhs.. in ..body..
202 data Foo = Foo Int Int#
204 f x = let !(Foo a b, w) = ..rhs.. in ..body..
206 since ``b`` has type ``Int#``.
213 .. extension:: UnboxedTuples
214 :shortdesc: Enable the use of unboxed tuple syntax.
219 Unboxed tuples aren't really exported by ``GHC.Exts``; they are a
220 syntactic extension (:extension:`UnboxedTuples`). An
221 unboxed tuple looks like this: ::
225 where ``e_1..e_n`` are expressions of any type (primitive or
226 non-primitive). The type of an unboxed tuple looks the same.
228 Note that when unboxed tuples are enabled, ``(#`` is a single lexeme, so
229 for example when using operators like ``#`` and ``#-`` you need to write
230 ``( # )`` and ``( #- )`` rather than ``(#)`` and ``(#-)``.
232 Unboxed tuples are used for functions that need to return multiple
233 values, but they avoid the heap allocation normally associated with
234 using fully-fledged tuples. When an unboxed tuple is returned, the
235 components are put directly into registers or on the stack; the unboxed
236 tuple itself does not have a composite representation. Many of the
237 primitive operations listed in ``primops.txt.pp`` return unboxed tuples.
238 In particular, the ``IO`` and ``ST`` monads use unboxed tuples to avoid
239 unnecessary allocation during sequences of operations.
241 There are some restrictions on the use of unboxed tuples:
243 - The typical use of unboxed tuples is simply to return multiple
244 values, binding those multiple results with a ``case`` expression,
249 f x y = (# x+1, y-1 #)
250 g x = case f x x of { (# a, b #) -> a + b }
252 You can have an unboxed tuple in a pattern binding, thus
256 f x = let (# p,q #) = h x in ..body..
258 If the types of ``p`` and ``q`` are not unboxed, the resulting
259 binding is lazy like any other Haskell pattern binding. The above
260 example desugars like this:
264 f x = let t = case h x of { (# p,q #) -> (p,q) }
269 Indeed, the bindings can even be recursive.
276 .. extension:: UnboxedSums
277 :shortdesc: Enable unboxed sums.
281 Enable the use of unboxed sum syntax.
283 `-XUnboxedSums` enables new syntax for anonymous, unboxed sum types. The syntax
284 for an unboxed sum type with N alternatives is ::
286 (# t_1 | t_2 | ... | t_N #)
288 where ``t_1`` ... ``t_N`` are types (which can be unlifted, including unboxed
291 Unboxed tuples can be used for multi-arity alternatives. For example: ::
293 (# (# Int, String #) | Bool #)
295 The term level syntax is similar. Leading and preceding bars (`|`) indicate which
296 alternative it is. Here are two terms of the type shown above: ::
298 (# (# 1, "foo" #) | #) -- first alternative
300 (# | True #) -- second alternative
302 The pattern syntax reflects the term syntax: ::
305 (# (# i, str #) | #) -> ...
308 Unboxed sums are "unboxed" in the sense that, instead of allocating sums in the
309 heap and representing values as pointers, unboxed sums are represented as their
310 components, just like unboxed tuples. These "components" depend on alternatives
311 of a sum type. Like unboxed tuples, unboxed sums are lazy in their lifted
314 The code generator tries to generate as compact layout as possible for each
315 unboxed sum. In the best case, size of an unboxed sum is size of its biggest
316 alternative plus one word (for a tag). The algorithm for generating the memory
317 layout for a sum type works like this:
319 - All types are classified as one of these classes: 32bit word, 64bit word,
320 32bit float, 64bit float, pointer.
322 - For each alternative of the sum type, a layout that consists of these fields
323 is generated. For example, if an alternative has ``Int``, ``Float#`` and
324 ``String`` fields, the layout will have an 32bit word, 32bit float and
327 - Layout fields are then overlapped so that the final layout will be as compact
328 as possible. For example, suppose we have the unboxed sum: ::
330 (# (# Word32#, String, Float# #)
331 | (# Float#, Float#, Maybe Int #) #)
333 The final layout will be something like ::
335 Int32, Float32, Float32, Word32, Pointer
337 The first ``Int32`` is for the tag. There are two ``Float32`` fields because
338 floating point types can't overlap with other types, because of limitations of
339 the code generator that we're hoping to overcome in the future. The second
340 alternative needs two ``Float32`` fields: The ``Word32`` field is for the
341 ``Word32#`` in the first alternative. The ``Pointer`` field is shared between
342 ``String`` and ``Maybe Int`` values of the alternatives.
344 As another example, this is the layout for the unboxed version of ``Maybe a``
345 type, ``(# (# #) | a #)``: ::
349 The ``Pointer`` field is not used when tag says that it's ``Nothing``.
350 Otherwise ``Pointer`` points to the value in ``Just``. As mentioned
351 above, this type is lazy in its lifted field. Therefore, the type ::
353 data Maybe' a = Maybe' (# (# #) | a #)
355 is *precisely* isomorphic to the type ``Maybe a``, although its memory
356 representation is different.
358 In the degenerate case where all the alternatives have zero width, such
359 as the ``Bool``-like ``(# (# #) | (# #) #)``, the unboxed sum layout only
360 has an ``Int32`` tag field (i.e., the whole thing is represented by an integer).
372 .. extension:: UnicodeSyntax
373 :shortdesc: Enable unicode syntax.
377 Enable the use of Unicode characters in place of their equivalent ASCII
380 The language extension :extension:`UnicodeSyntax` enables
381 Unicode characters to be used to stand for certain ASCII character
382 sequences. The following alternatives are provided:
384 +--------------+---------------+-------------+-----------------------------------------+
385 | ASCII | Unicode | Code point | Name |
386 | | alternative | | |
387 +==============+===============+=============+=========================================+
388 | ``::`` | ∷ | 0x2237 | PROPORTION |
389 +--------------+---------------+-------------+-----------------------------------------+
390 | ``=>`` | ⇒ | 0x21D2 | RIGHTWARDS DOUBLE ARROW |
391 +--------------+---------------+-------------+-----------------------------------------+
392 | ``->`` | → | 0x2192 | RIGHTWARDS ARROW |
393 +--------------+---------------+-------------+-----------------------------------------+
394 | ``<-`` | ← | 0x2190 | LEFTWARDS ARROW |
395 +--------------+---------------+-------------+-----------------------------------------+
396 | ``>-`` | ⤚ | 0x291a | RIGHTWARDS ARROW-TAIL |
397 +--------------+---------------+-------------+-----------------------------------------+
398 | ``-<`` | ⤙ | 0x2919 | LEFTWARDS ARROW-TAIL |
399 +--------------+---------------+-------------+-----------------------------------------+
400 | ``>>-`` | ⤜ | 0x291C | RIGHTWARDS DOUBLE ARROW-TAIL |
401 +--------------+---------------+-------------+-----------------------------------------+
402 | ``-<<`` | ⤛ | 0x291B | LEFTWARDS DOUBLE ARROW-TAIL |
403 +--------------+---------------+-------------+-----------------------------------------+
404 | ``*`` | ★ | 0x2605 | BLACK STAR |
405 +--------------+---------------+-------------+-----------------------------------------+
406 | ``forall`` | ∀ | 0x2200 | FOR ALL |
407 +--------------+---------------+-------------+-----------------------------------------+
408 | ``(|`` | ⦇ | 0x2987 | Z NOTATION LEFT IMAGE BRACKET |
409 +--------------+---------------+-------------+-----------------------------------------+
410 | ``|)`` | ⦈ | 0x2988 | Z NOTATION RIGHT IMAGE BRACKET |
411 +--------------+---------------+-------------+-----------------------------------------+
412 | ``[|`` | ⟦ | 0x27E6 | MATHEMATICAL LEFT WHITE SQUARE BRACKET |
413 +--------------+---------------+-------------+-----------------------------------------+
414 | ``|]`` | ⟧ | 0x27E7 | MATHEMATICAL RIGHT WHITE SQUARE BRACKET |
415 +--------------+---------------+-------------+-----------------------------------------+
422 .. extension:: MagicHash
423 :shortdesc: Allow ``#`` as a postfix modifier on identifiers.
427 Enables the use of the hash character (``#``) as an identifier suffix.
429 The language extension :extension:`MagicHash` allows ``#`` as a postfix modifier
430 to identifiers. Thus, ``x#`` is a valid variable, and ``T#`` is a valid type
431 constructor or data constructor.
433 The hash sign does not change semantics at all. We tend to use variable
434 names ending in "#" for unboxed values or types (e.g. ``Int#``), but
435 there is no requirement to do so; they are just plain ordinary
436 variables. Nor does the :extension:`MagicHash` extension bring anything into
437 scope. For example, to bring ``Int#`` into scope you must import
438 ``GHC.Prim`` (see :ref:`primitives`); the :extension:`MagicHash` extension then
439 allows you to *refer* to the ``Int#`` that is now in scope. Note that
440 with this option, the meaning of ``x#y = 0`` is changed: it defines a
441 function ``x#`` taking a single argument ``y``; to define the operator
442 ``#``, put a space: ``x # y = 0``.
444 The :extension:`MagicHash` also enables some new forms of literals (see
445 :ref:`glasgow-unboxed`):
447 - ``'x'#`` has type ``Char#``
449 - ``"foo"#`` has type ``Addr#``
451 - ``3#`` has type ``Int#``. In general, any Haskell integer lexeme
452 followed by a ``#`` is an ``Int#`` literal, e.g. ``-0x3A#`` as well as
455 - ``3##`` has type ``Word#``. In general, any non-negative Haskell
456 integer lexeme followed by ``##`` is a ``Word#``.
458 - ``3.2#`` has type ``Float#``.
460 - ``3.2##`` has type ``Double#``
462 .. _negative-literals:
467 .. extension:: NegativeLiterals
468 :shortdesc: Enable support for negative literals.
472 Enable the use of un-parenthesized negative numeric literals.
474 The literal ``-123`` is, according to Haskell98 and Haskell 2010,
475 desugared as ``negate (fromInteger 123)``. The language extension
476 :extension:`NegativeLiterals` means that it is instead desugared as
477 ``fromInteger (-123)``.
479 This can make a difference when the positive and negative range of a
480 numeric data type don't match up. For example, in 8-bit arithmetic -128
481 is representable, but +128 is not. So ``negate (fromInteger 128)`` will
482 elicit an unexpected integer-literal-overflow message.
486 Fractional looking integer literals
487 -----------------------------------
489 .. extension:: NumDecimals
490 :shortdesc: Enable support for 'fractional' integer literals.
494 Allow the use of floating-point literal syntax for integral types.
496 Haskell 2010 and Haskell 98 define floating literals with the syntax
497 ``1.2e6``. These literals have the type ``Fractional a => a``.
499 The language extension :extension:`NumDecimals` allows you to also use the
500 floating literal syntax for instances of ``Integral``, and have values
501 like ``(1.2e6 :: Num a => a)``
505 Binary integer literals
506 -----------------------
508 .. extension:: BinaryLiterals
509 :shortdesc: Enable support for binary literals.
513 Allow the use of binary notation in integer literals.
515 Haskell 2010 and Haskell 98 allows for integer literals to be given in
516 decimal, octal (prefixed by ``0o`` or ``0O``), or hexadecimal notation
517 (prefixed by ``0x`` or ``0X``).
519 The language extension :extension:`BinaryLiterals` adds support for expressing
520 integer literals in binary notation with the prefix ``0b`` or ``0B``. For
521 instance, the binary integer literal ``0b11001001`` will be desugared into
522 ``fromInteger 201`` when :extension:`BinaryLiterals` is enabled.
524 .. _hex-float-literals:
526 Hexadecimal floating point literals
527 -----------------------------------
529 .. extension:: HexFloatLiterals
530 :shortdesc: Enable support for :ref:`hexadecimal floating point literals <hex-float-literals>`.
534 Allow writing floating point literals using hexadecimal notation.
536 The hexadecimal notation for floating point literals is useful when you
537 need to specify floating point constants precisely, as the literal notation
538 corresponds closely to the underlying bit-encoding of the number.
540 In this notation floating point numbers are written using hexadecimal digits,
541 and so the digits are interpreted using base 16, rather then the usual 10.
542 This means that digits left of the decimal point correspond to positive
543 powers of 16, while the ones to the right correspond to negaitve ones.
545 You may also write an explicit exponent, which is similar to the exponent
546 in decimal notation with the following differences:
547 - the exponent begins with ``p`` instead of ``e``
548 - the exponent is written in base ``10`` (**not** 16)
549 - the base of the exponent is ``2`` (**not** 16).
551 In terms of the underlying bit encoding, each hexadecimal digit corresponds
552 to 4 bits, and you may think of the exponent as "moving" the floating point
553 by one bit left (negative) or right (positive). Here are some examples:
555 - ``0x0.1`` is the same as ``1/16``
556 - ``0x0.01`` is the same as ``1/256``
557 - ``0xF.FF`` is the same as ``15 + 15/16 + 15/256``
558 - ``0x0.1p4`` is the same as ``1``
559 - ``0x0.1p-4`` is the same as ``1/256``
560 - ``0x0.1p12`` is the same as ``256``
565 .. _numeric-underscores:
570 .. extension:: NumericUnderscores
571 :shortdesc: Enable support for :ref:`numeric underscores <numeric-underscores>`.
575 Allow the use of underscores in numeric literals.
577 GHC allows for numeric literals to be given in decimal, octal, hexadecimal,
578 binary, or float notation.
580 The language extension :extension:`NumericUnderscores` adds support for expressing
581 underscores in numeric literals.
582 For instance, the numeric literal ``1_000_000`` will be parsed into
583 ``1000000`` when :extension:`NumericUnderscores` is enabled.
584 That is, underscores in numeric literals are ignored when
585 :extension:`NumericUnderscores` is enabled.
586 See also :ghc-ticket:`14473`.
592 billion = 1_000_000_000
593 lightspeed = 299_792_458
598 red_mask = 0xff_00_00
602 bit8th = 0b01_0000_0000
603 packbits = 0b1_11_01_0000_0_111
604 bigbits = 0b1100_1011__1110_1111__0101_0011
607 pi = 3.141_592_653_589_793
608 faraday = 96_485.332_89
609 avogadro = 6.022_140_857e+23
612 isUnderMillion = (< 1_000_000)
615 | x > 0x3ff_ffff = 0x3ff_ffff
618 test8bit x = (0b01_0000_0000 .&. x) /= 0
622 x0 = 1_000_000 -- valid
623 x1 = 1__000000 -- valid
624 x2 = 1000000_ -- invalid
625 x3 = _1000000 -- invalid
628 e1 = 0.000_1 -- valid
629 e2 = 0_.0001 -- invalid
630 e3 = _0.0001 -- invalid
631 e4 = 0._0001 -- invalid
632 e5 = 0.0001_ -- invalid
636 f2 = 1__e+23 -- valid
637 f3 = 1e_+23 -- invalid
640 g1 = 1e+_23 -- invalid
641 g2 = 1e+23_ -- invalid
644 h1 = 0xff_ff -- valid
645 h2 = 0x_ffff -- valid
646 h3 = 0x__ffff -- valid
647 h4 = _0xffff -- invalid
654 .. extension:: NoPatternGuards
655 :shortdesc: Disable pattern guards.
656 Implied by :extension:`Haskell98`.
658 :implied by: :extension:`Haskell98`
661 Disable `pattern guards
662 <http://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-460003.13>`__.
669 .. extension:: ViewPatterns
670 :shortdesc: Enable view patterns.
674 Allow use of view pattern syntax.
676 View patterns are enabled by the language extension :extension:`ViewPatterns`. More
677 information and examples of view patterns can be found on the
678 :ghc-wiki:`Wiki page <ViewPatterns>`.
680 View patterns are somewhat like pattern guards that can be nested inside
681 of other patterns. They are a convenient way of pattern-matching against
682 values of abstract types. For example, in a programming language
683 implementation, we might represent the syntax of the types of the
684 language as follows: ::
691 view :: Typ -> TypView
693 -- additional operations for constructing Typ's ...
695 The representation of Typ is held abstract, permitting implementations
696 to use a fancy representation (e.g., hash-consing to manage sharing).
697 Without view patterns, using this signature is a little inconvenient: ::
699 size :: Typ -> Integer
700 size t = case view t of
702 Arrow t1 t2 -> size t1 + size t2
704 It is necessary to iterate the case, rather than using an equational
705 function definition. And the situation is even worse when the matching
706 against ``t`` is buried deep inside another pattern.
708 View patterns permit calling the view function inside the pattern and
709 matching against the result: ::
711 size (view -> Unit) = 1
712 size (view -> Arrow t1 t2) = size t1 + size t2
714 That is, we add a new form of pattern, written ⟨expression⟩ ``->``
715 ⟨pattern⟩ that means "apply the expression to whatever we're trying to
716 match against, and then match the result of that application against the
717 pattern". The expression can be any Haskell expression of function type,
718 and view patterns can be used wherever patterns are used.
720 The semantics of a pattern ``(`` ⟨exp⟩ ``->`` ⟨pat⟩ ``)`` are as
724 The variables bound by the view pattern are the variables bound by
727 Any variables in ⟨exp⟩ are bound occurrences, but variables bound "to
728 the left" in a pattern are in scope. This feature permits, for
729 example, one argument to a function to be used in the view of another
730 argument. For example, the function ``clunky`` from
731 :ref:`pattern-guards` can be written using view patterns as follows: ::
733 clunky env (lookup env -> Just val1) (lookup env -> Just val2) = val1 + val2
734 ...other equations for clunky...
736 More precisely, the scoping rules are:
738 - In a single pattern, variables bound by patterns to the left of a
739 view pattern expression are in scope. For example: ::
741 example :: Maybe ((String -> Integer,Integer), String) -> Bool
742 example Just ((f,_), f -> 4) = True
744 Additionally, in function definitions, variables bound by matching
745 earlier curried arguments may be used in view pattern expressions
746 in later arguments: ::
748 example :: (String -> Integer) -> String -> Bool
749 example f (f -> 4) = True
751 That is, the scoping is the same as it would be if the curried
752 arguments were collected into a tuple.
754 - In mutually recursive bindings, such as ``let``, ``where``, or the
755 top level, view patterns in one declaration may not mention
756 variables bound by other declarations. That is, each declaration
757 must be self-contained. For example, the following program is not
763 (For some amplification on this design choice see :ghc-ticket:`4061`.
765 - Typing: If ⟨exp⟩ has type ⟨T1⟩ ``->`` ⟨T2⟩ and ⟨pat⟩ matches a ⟨T2⟩,
766 then the whole view pattern matches a ⟨T1⟩.
768 - Matching: To the equations in Section 3.17.3 of the `Haskell 98
769 Report <http://www.haskell.org/onlinereport/>`__, add the following: ::
771 case v of { (e -> p) -> e1 ; _ -> e2 }
773 case (e v) of { p -> e1 ; _ -> e2 }
775 That is, to match a variable ⟨v⟩ against a pattern ``(`` ⟨exp⟩ ``->``
776 ⟨pat⟩ ``)``, evaluate ``(`` ⟨exp⟩ ⟨v⟩ ``)`` and match the result
779 - Efficiency: When the same view function is applied in multiple
780 branches of a function definition or a case expression (e.g., in
781 ``size`` above), GHC makes an attempt to collect these applications
782 into a single nested case expression, so that the view function is
783 only applied once. Pattern compilation in GHC follows the matrix
784 algorithm described in Chapter 4 of `The Implementation of Functional
786 Languages <http://research.microsoft.com/~simonpj/Papers/slpj-book-1987/>`__.
787 When the top rows of the first column of a matrix are all view
788 patterns with the "same" expression, these patterns are transformed
789 into a single nested case. This includes, for example, adjacent view
790 patterns that line up in a tuple, as in
794 f ((view -> A, p1), p2) = e1
795 f ((view -> B, p3), p4) = e2
797 The current notion of when two view pattern expressions are "the
798 same" is very restricted: it is not even full syntactic equality.
799 However, it does include variables, literals, applications, and
800 tuples; e.g., two instances of ``view ("hi", "there")`` will be
801 collected. However, the current implementation does not compare up to
802 alpha-equivalence, so two instances of ``(x, view x -> y)`` will not
810 .. extension:: NPlusKPatterns
811 :shortdesc: Enable support for ``n+k`` patterns.
812 Implied by :extension:`Haskell98`.
814 :implied by: :extension:`Haskell98`
817 Enable use of ``n+k`` patterns.
819 .. _recursive-do-notation:
821 The recursive do-notation
822 -------------------------
824 .. extension:: RecursiveDo
825 :shortdesc: Enable recursive do (mdo) notation.
829 Allow the use of recursive ``do`` notation.
831 The do-notation of Haskell 98 does not allow *recursive bindings*, that
832 is, the variables bound in a do-expression are visible only in the
833 textually following code block. Compare this to a let-expression, where
834 bound variables are visible in the entire binding group.
836 It turns out that such recursive bindings do indeed make sense for a
837 variety of monads, but not all. In particular, recursion in this sense
838 requires a fixed-point operator for the underlying monad, captured by
839 the ``mfix`` method of the ``MonadFix`` class, defined in
840 ``Control.Monad.Fix`` as follows: ::
842 class Monad m => MonadFix m where
843 mfix :: (a -> m a) -> m a
845 Haskell's ``Maybe``, ``[]`` (list), ``ST`` (both strict and lazy
846 versions), ``IO``, and many other monads have ``MonadFix`` instances. On
847 the negative side, the continuation monad, with the signature
848 ``(a -> r) -> r``, does not.
850 For monads that do belong to the ``MonadFix`` class, GHC provides an
851 extended version of the do-notation that allows recursive bindings. The
852 :extension:`RecursiveDo` (language pragma: ``RecursiveDo``) provides the
853 necessary syntactic support, introducing the keywords ``mdo`` and
854 ``rec`` for higher and lower levels of the notation respectively. Unlike
855 bindings in a ``do`` expression, those introduced by ``mdo`` and ``rec``
856 are recursively defined, much like in an ordinary let-expression. Due to
857 the new keyword ``mdo``, we also call this notation the *mdo-notation*.
859 Here is a simple (albeit contrived) example:
863 {-# LANGUAGE RecursiveDo #-}
864 justOnes = mdo { xs <- Just (1:xs)
865 ; return (map negate xs) }
871 {-# LANGUAGE RecursiveDo #-}
872 justOnes = do { rec { xs <- Just (1:xs) }
873 ; return (map negate xs) }
875 As you can guess ``justOnes`` will evaluate to ``Just [-1,-1,-1,...``.
877 GHC's implementation the mdo-notation closely follows the original
878 translation as described in the paper `A recursive do for
879 Haskell <http://leventerkok.github.io/papers/recdo.pdf>`__, which
880 in turn is based on the work `Value Recursion in Monadic
881 Computations <http://leventerkok.github.io/papers/erkok-thesis.pdf>`__.
882 Furthermore, GHC extends the syntax described in the former paper with a
883 lower level syntax flagged by the ``rec`` keyword, as we describe next.
885 Recursive binding groups
886 ~~~~~~~~~~~~~~~~~~~~~~~~
888 The extension :extension:`RecursiveDo` also introduces a new keyword ``rec``, which
889 wraps a mutually-recursive group of monadic statements inside a ``do``
890 expression, producing a single statement. Similar to a ``let`` statement
891 inside a ``do``, variables bound in the ``rec`` are visible throughout
892 the ``rec`` group, and below it. For example, compare
896 do { a <- getChar do { a <- getChar
897 ; let { r1 = f a r2 ; rec { r1 <- f a r2
898 ; ; r2 = g r1 } ; ; r2 <- g r1 }
899 ; return (r1 ++ r2) } ; return (r1 ++ r2) }
901 In both cases, ``r1`` and ``r2`` are available both throughout the
902 ``let`` or ``rec`` block, and in the statements that follow it. The
903 difference is that ``let`` is non-monadic, while ``rec`` is monadic. (In
904 Haskell ``let`` is really ``letrec``, of course.)
906 The semantics of ``rec`` is fairly straightforward. Whenever GHC finds a
907 ``rec`` group, it will compute its set of bound variables, and will
908 introduce an appropriate call to the underlying monadic value-recursion
909 operator ``mfix``, belonging to the ``MonadFix`` class. Here is an
914 rec { b <- f a c ===> (b,c) <- mfix (\ ~(b,c) -> do { b <- f a c
915 ; c <- f b a } ; c <- f b a
918 As usual, the meta-variables ``b``, ``c`` etc., can be arbitrary
919 patterns. In general, the statement ``rec ss`` is desugared to the
924 vs <- mfix (\ ~vs -> do { ss; return vs })
926 where ``vs`` is a tuple of the variables bound by ``ss``.
928 Note in particular that the translation for a ``rec`` block only
929 involves wrapping a call to ``mfix``: it performs no other analysis on
930 the bindings. The latter is the task for the ``mdo`` notation, which is
936 A ``rec``-block tells the compiler where precisely the recursive knot
937 should be tied. It turns out that the placement of the recursive knots
938 can be rather delicate: in particular, we would like the knots to be
939 wrapped around as minimal groups as possible. This process is known as
940 *segmentation*, and is described in detail in Section 3.2 of `A
942 Haskell <http://leventerkok.github.io/papers/recdo.pdf>`__.
943 Segmentation improves polymorphism and reduces the size of the recursive
944 knot. Most importantly, it avoids unnecessary interference caused by a
945 fundamental issue with the so-called *right-shrinking* axiom for monadic
946 recursion. In brief, most monads of interest (IO, strict state, etc.) do
947 *not* have recursion operators that satisfy this axiom, and thus not
948 performing segmentation can cause unnecessary interference, changing the
949 termination behavior of the resulting translation. (Details can be found
950 in Sections 3.1 and 7.2.2 of `Value Recursion in Monadic
951 Computations <http://leventerkok.github.io/papers/erkok-thesis.pdf>`__.)
953 The ``mdo`` notation removes the burden of placing explicit ``rec``
954 blocks in the code. Unlike an ordinary ``do`` expression, in which
955 variables bound by statements are only in scope for later statements,
956 variables bound in an ``mdo`` expression are in scope for all statements
957 of the expression. The compiler then automatically identifies minimal
958 mutually recursively dependent segments of statements, treating them as
959 if the user had wrapped a ``rec`` qualifier around them.
961 The definition is syntactic:
963 - A generator ⟨g⟩ *depends* on a textually following generator ⟨g'⟩, if
965 - ⟨g'⟩ defines a variable that is used by ⟨g⟩, or
967 - ⟨g'⟩ textually appears between ⟨g⟩ and ⟨g''⟩, where ⟨g⟩ depends on
970 - A *segment* of a given ``mdo``-expression is a minimal sequence of
971 generators such that no generator of the sequence depends on an
972 outside generator. As a special case, although it is not a generator,
973 the final expression in an ``mdo``-expression is considered to form a
976 Segments in this sense are related to *strongly-connected components*
977 analysis, with the exception that bindings in a segment cannot be
978 reordered and must be contiguous.
980 Here is an example ``mdo``-expression, and its translation to ``rec``
985 mdo { a <- getChar ===> do { a <- getChar
986 ; b <- f a c ; rec { b <- f a c
987 ; c <- f b a ; ; c <- f b a }
988 ; z <- h a b ; z <- h a b
989 ; d <- g d e ; rec { d <- g d e
990 ; e <- g a z ; ; e <- g a z }
991 ; putChar c } ; putChar c }
993 Note that a given ``mdo`` expression can cause the creation of multiple
994 ``rec`` blocks. If there are no recursive dependencies, ``mdo`` will
995 introduce no ``rec`` blocks. In this latter case an ``mdo`` expression
996 is precisely the same as a ``do`` expression, as one would expect.
998 In summary, given an ``mdo`` expression, GHC first performs
999 segmentation, introducing ``rec`` blocks to wrap over minimal recursive
1000 groups. Then, each resulting ``rec`` is desugared, using a call to
1001 ``Control.Monad.Fix.mfix`` as described in the previous section. The
1002 original ``mdo``-expression typechecks exactly when the desugared
1003 version would do so.
1005 Here are some other important points in using the recursive-do notation:
1007 - It is enabled with the extension :extension:`RecursiveDo`, or the
1008 ``LANGUAGE RecursiveDo`` pragma. (The same extension enables both
1009 ``mdo``-notation, and the use of ``rec`` blocks inside ``do``
1012 - ``rec`` blocks can also be used inside ``mdo``-expressions, which
1013 will be treated as a single statement. However, it is good style to
1014 either use ``mdo`` or ``rec`` blocks in a single expression.
1016 - If recursive bindings are required for a monad, then that monad must
1017 be declared an instance of the ``MonadFix`` class.
1019 - The following instances of ``MonadFix`` are automatically provided:
1020 List, Maybe, IO. Furthermore, the ``Control.Monad.ST`` and
1021 ``Control.Monad.ST.Lazy`` modules provide the instances of the
1022 ``MonadFix`` class for Haskell's internal state monad (strict and
1023 lazy, respectively).
1025 - Like ``let`` and ``where`` bindings, name shadowing is not allowed
1026 within an ``mdo``-expression or a ``rec``-block; that is, all the
1027 names bound in a single ``rec`` must be distinct. (GHC will complain
1028 if this is not the case.)
1032 Applicative do-notation
1033 -----------------------
1036 single: Applicative do-notation
1037 single: do-notation; Applicative
1039 .. extension:: ApplicativeDo
1040 :shortdesc: Enable Applicative do-notation desugaring
1044 Allow use of ``Applicative`` ``do`` notation.
1046 The language option :extension:`ApplicativeDo` enables an alternative translation for
1047 the do-notation, which uses the operators ``<$>``, ``<*>``, along with ``join``
1048 as far as possible. There are two main reasons for wanting to do this:
1050 - We can use do-notation with types that are an instance of ``Applicative`` and
1051 ``Functor``, but not ``Monad``
1052 - In some monads, using the applicative operators is more efficient than monadic
1053 bind. For example, it may enable more parallelism.
1055 Applicative do-notation desugaring preserves the original semantics, provided
1056 that the ``Applicative`` instance satisfies ``<*> = ap`` and ``pure = return``
1057 (these are true of all the common monadic types). Thus, you can normally turn on
1058 :extension:`ApplicativeDo` without fear of breaking your program. There is one pitfall
1059 to watch out for; see :ref:`applicative-do-pitfall`.
1061 There are no syntactic changes with :extension:`ApplicativeDo`. The only way it shows
1062 up at the source level is that you can have a ``do`` expression that doesn't
1063 require a ``Monad`` constraint. For example, in GHCi: ::
1065 Prelude> :set -XApplicativeDo
1066 Prelude> :t \m -> do { x <- m; return (not x) }
1067 \m -> do { x <- m; return (not x) }
1068 :: Functor f => f Bool -> f Bool
1070 This example only requires ``Functor``, because it is translated into ``(\x ->
1071 not x) <$> m``. A more complex example requires ``Applicative``, ::
1073 Prelude> :t \m -> do { x <- m 'a'; y <- m 'b'; return (x || y) }
1074 \m -> do { x <- m 'a'; y <- m 'b'; return (x || y) }
1075 :: Applicative f => (Char -> f Bool) -> f Bool
1077 Here GHC has translated the expression into ::
1079 (\x y -> x || y) <$> m 'a' <*> m 'b'
1081 It is possible to see the actual translation by using :ghc-flag:`-ddump-ds`, but be
1082 warned, the output is quite verbose.
1084 Note that if the expression can't be translated into uses of ``<$>``, ``<*>``
1085 only, then it will incur a ``Monad`` constraint as usual. This happens when
1086 there is a dependency on a value produced by an earlier statement in the
1089 Prelude> :t \m -> do { x <- m True; y <- m x; return (x || y) }
1090 \m -> do { x <- m True; y <- m x; return (x || y) }
1091 :: Monad m => (Bool -> m Bool) -> m Bool
1093 Here, ``m x`` depends on the value of ``x`` produced by the first statement, so
1094 the expression cannot be translated using ``<*>``.
1096 In general, the rule for when a ``do`` statement incurs a ``Monad`` constraint
1097 is as follows. If the do-expression has the following form: ::
1099 do p1 <- E1; ...; pn <- En; return E
1101 where none of the variables defined by ``p1...pn`` are mentioned in ``E1...En``,
1102 and ``p1...pn`` are all variables or lazy patterns,
1103 then the expression will only require ``Applicative``. Otherwise, the expression
1104 will require ``Monad``. The block may return a pure expression ``E`` depending
1105 upon the results ``p1...pn`` with either ``return`` or ``pure``.
1107 Note: the final statement must match one of these patterns exactly:
1114 otherwise GHC cannot recognise it as a ``return`` statement, and the
1115 transformation to use ``<$>`` that we saw above does not apply. In
1116 particular, slight variations such as ``return . Just $ x`` or ``let x
1117 = e in return x`` would not be recognised.
1119 If the final statement is not of one of these forms, GHC falls back to
1120 standard ``do`` desugaring, and the expression will require a
1121 ``Monad`` constraint.
1123 When the statements of a ``do`` expression have dependencies between
1124 them, and ``ApplicativeDo`` cannot infer an ``Applicative`` type, it
1125 uses a heuristic algorithm to try to use ``<*>`` as much as possible.
1126 This algorithm usually finds the best solution, but in rare complex
1127 cases it might miss an opportunity. There is an algorithm that finds
1128 the optimal solution, provided as an option:
1130 .. ghc-flag:: -foptimal-applicative-do
1131 :shortdesc: Use a slower but better algorithm for ApplicativeDo
1133 :reverse: -fno-optimal-applicative-do
1134 :category: optimization
1138 Enables an alternative algorithm for choosing where to use ``<*>``
1139 in conjunction with the ``ApplicativeDo`` language extension.
1140 This algorithm always finds the optimal solution, but it is
1141 expensive: ``O(n^3)``, so this option can lead to long compile
1142 times when there are very large ``do`` expressions (over 100
1143 statements). The default ``ApplicativeDo`` algorithm is ``O(n^2)``.
1146 .. _applicative-do-strict:
1152 A strict pattern match in a bind statement prevents
1153 ``ApplicativeDo`` from transforming that statement to use
1154 ``Applicative``. This is because the transformation would change the
1155 semantics by making the expression lazier.
1157 For example, this code will require a ``Monad`` constraint::
1159 > :t \m -> do { (x:xs) <- m; return x }
1160 \m -> do { (x:xs) <- m; return x } :: Monad m => m [b] -> m b
1162 but making the pattern match lazy allows it to have a ``Functor`` constraint::
1164 > :t \m -> do { ~(x:xs) <- m; return x }
1165 \m -> do { ~(x:xs) <- m; return x } :: Functor f => f [b] -> f b
1167 A "strict pattern match" is any pattern match that can fail. For
1168 example, ``()``, ``(x:xs)``, ``!z``, and ``C x`` are strict patterns,
1169 but ``x`` and ``~(1,2)`` are not. For the purposes of
1170 ``ApplicativeDo``, a pattern match against a ``newtype`` constructor
1171 is considered strict.
1173 When there's a strict pattern match in a sequence of statements,
1174 ``ApplicativeDo`` places a ``>>=`` between that statement and the one
1175 that follows it. The sequence may be transformed to use ``<*>``
1176 elsewhere, but the strict pattern match and the following statement
1177 will always be connected with ``>>=``, to retain the same strictness
1178 semantics as the standard do-notation. If you don't want this, simply
1179 put a ``~`` on the pattern match to make it lazy.
1181 .. _applicative-do-pitfall:
1183 Things to watch out for
1184 ~~~~~~~~~~~~~~~~~~~~~~~
1186 Your code should just work as before when :extension:`ApplicativeDo` is enabled,
1187 provided you use conventional ``Applicative`` instances. However, if you define
1188 a ``Functor`` or ``Applicative`` instance using do-notation, then it will likely
1189 get turned into an infinite loop by GHC. For example, if you do this: ::
1191 instance Functor MyType where
1192 fmap f m = do x <- m; return (f x)
1194 Then applicative desugaring will turn it into ::
1196 instance Functor MyType where
1197 fmap f m = fmap (\x -> f x) m
1199 And the program will loop at runtime. Similarly, an ``Applicative`` instance
1202 instance Applicative MyType where
1204 x <*> y = do f <- x; a <- y; return (f a)
1206 will result in an infinte loop when ``<*>`` is called.
1208 Just as you wouldn't define a ``Monad`` instance using the do-notation, you
1209 shouldn't define ``Functor`` or ``Applicative`` instance using do-notation (when
1210 using ``ApplicativeDo``) either. The correct way to define these instances in
1211 terms of ``Monad`` is to use the ``Monad`` operations directly, e.g. ::
1213 instance Functor MyType where
1214 fmap f m = m >>= return . f
1216 instance Applicative MyType where
1221 .. _parallel-list-comprehensions:
1223 Parallel List Comprehensions
1224 ----------------------------
1227 single: list comprehensions; parallel
1228 single: parallel list comprehensions
1230 .. extension:: ParallelListComp
1231 :shortdesc: Enable parallel list comprehensions.
1235 Allow parallel list comprehension syntax.
1237 Parallel list comprehensions are a natural extension to list
1238 comprehensions. List comprehensions can be thought of as a nice syntax
1239 for writing maps and filters. Parallel comprehensions extend this to
1240 include the ``zipWith`` family.
1242 A parallel list comprehension has multiple independent branches of
1243 qualifier lists, each separated by a ``|`` symbol. For example, the
1244 following zips together two lists: ::
1246 [ (x, y) | x <- xs | y <- ys ]
1248 The behaviour of parallel list comprehensions follows that of zip, in
1249 that the resulting list will have the same length as the shortest
1252 We can define parallel list comprehensions by translation to regular
1253 comprehensions. Here's the basic idea:
1255 Given a parallel comprehension of the form: ::
1257 [ e | p1 <- e11, p2 <- e12, ...
1258 | q1 <- e21, q2 <- e22, ...
1262 This will be translated to: ::
1264 [ e | ((p1,p2), (q1,q2), ...) <- zipN [(p1,p2) | p1 <- e11, p2 <- e12, ...]
1265 [(q1,q2) | q1 <- e21, q2 <- e22, ...]
1269 where ``zipN`` is the appropriate zip for the given number of branches.
1271 .. _generalised-list-comprehensions:
1273 Generalised (SQL-like) List Comprehensions
1274 ------------------------------------------
1277 single: list comprehensions; generalised
1278 single: extended list comprehensions
1282 .. extension:: TransformListComp
1283 :shortdesc: Enable generalised list comprehensions.
1287 Allow use of generalised list (SQL-like) comprehension syntax. This
1288 introduces the ``group``, ``by``, and ``using`` keywords.
1290 Generalised list comprehensions are a further enhancement to the list
1291 comprehension syntactic sugar to allow operations such as sorting and
1292 grouping which are familiar from SQL. They are fully described in the
1293 paper `Comprehensive comprehensions: comprehensions with "order by" and
1294 "group by" <https://www.microsoft.com/en-us/research/wp-content/uploads/2007/09/list-comp.pdf>`__,
1295 except that the syntax we use differs slightly from the paper.
1297 The extension is enabled with the extension :extension:`TransformListComp`.
1303 employees = [ ("Simon", "MS", 80)
1304 , ("Erik", "MS", 100)
1305 , ("Phil", "Ed", 40)
1306 , ("Gordon", "Ed", 45)
1307 , ("Paul", "Yale", 60) ]
1309 output = [ (the dept, sum salary)
1310 | (name, dept, salary) <- employees
1311 , then group by dept using groupWith
1312 , then sortWith by (sum salary)
1315 In this example, the list ``output`` would take on the value:
1319 [("Yale", 60), ("Ed", 85), ("MS", 180)]
1321 There are three new keywords: ``group``, ``by``, and ``using``. (The
1322 functions ``sortWith`` and ``groupWith`` are not keywords; they are
1323 ordinary functions that are exported by ``GHC.Exts``.)
1325 There are five new forms of comprehension qualifier, all introduced by
1326 the (existing) keyword ``then``:
1332 This statement requires that
1335 forall a. [a] -> [a]
1336 . You can see an example of its use in the motivating example, as
1337 this form is used to apply
1344 This form is similar to the previous one, but allows you to create a
1345 function which will be passed as the first argument to f. As a
1346 consequence f must have the type
1347 ``forall a. (a -> t) -> [a] -> [a]``. As you can see from the type,
1348 this function lets f "project out" some information from the elements
1349 of the list it is transforming.
1351 An example is shown in the opening example, where ``sortWith`` is
1352 supplied with a function that lets it find out the ``sum salary`` for
1353 any item in the list comprehension it transforms.
1357 then group by e using f
1359 This is the most general of the grouping-type statements. In this
1360 form, f is required to have type
1361 ``forall a. (a -> t) -> [a] -> [[a]]``. As with the ``then f by e``
1362 case above, the first argument is a function supplied to f by the
1363 compiler which lets it compute e on every element of the list being
1364 transformed. However, unlike the non-grouping case, f additionally
1365 partitions the list into a number of sublists: this means that at
1366 every point after this statement, binders occurring before it in the
1367 comprehension refer to *lists* of possible values, not single values.
1368 To help understand this, let's look at an example:
1372 -- This works similarly to groupWith in GHC.Exts, but doesn't sort its input first
1373 groupRuns :: Eq b => (a -> b) -> [a] -> [[a]]
1374 groupRuns f = groupBy (\x y -> f x == f y)
1376 output = [ (the x, y)
1377 | x <- ([1..3] ++ [1..2])
1379 , then group by x using groupRuns ]
1381 This results in the variable ``output`` taking on the value below:
1385 [(1, [4, 5, 6]), (2, [4, 5, 6]), (3, [4, 5, 6]), (1, [4, 5, 6]), (2, [4, 5, 6])]
1387 Note that we have used the ``the`` function to change the type of x
1388 from a list to its original numeric type. The variable y, in
1389 contrast, is left unchanged from the list form introduced by the
1396 With this form of the group statement, f is required to simply have
1397 the type ``forall a. [a] -> [[a]]``, which will be used to group up
1398 the comprehension so far directly. An example of this form is as
1406 , then group using inits]
1408 This will yield a list containing every prefix of the word "hello"
1409 written out 5 times:
1413 ["","h","he","hel","hell","hello","helloh","hellohe","hellohel","hellohell","hellohello","hellohelloh",...]
1415 .. _monad-comprehensions:
1417 Monad comprehensions
1418 --------------------
1421 single: monad comprehensions
1423 .. extension:: MonadComprehensions
1424 :shortdesc: Enable monad comprehensions.
1428 Enable list comprehension syntax for arbitrary monads.
1430 Monad comprehensions generalise the list comprehension notation,
1431 including parallel comprehensions (:ref:`parallel-list-comprehensions`)
1432 and transform comprehensions (:ref:`generalised-list-comprehensions`) to
1435 Monad comprehensions support:
1439 [ x + y | x <- Just 1, y <- Just 2 ]
1441 Bindings are translated with the ``(>>=)`` and ``return`` functions
1442 to the usual do-notation: ::
1450 [ x | x <- [1..10], x <= 5 ]
1452 Guards are translated with the ``guard`` function, which requires a
1453 ``MonadPlus`` instance: ::
1459 - Transform statements (as with :extension:`TransformListComp`): ::
1461 [ x+y | x <- [1..10], y <- [1..x], then take 2 ]
1463 This translates to: ::
1465 do (x,y) <- take 2 (do x <- [1..10]
1470 - Group statements (as with :extension:`TransformListComp`):
1474 [ x | x <- [1,1,2,2,3], then group by x using GHC.Exts.groupWith ]
1475 [ x | x <- [1,1,2,2,3], then group using myGroup ]
1477 - Parallel statements (as with :extension:`ParallelListComp`):
1481 [ (x+y) | x <- [1..10]
1485 Parallel statements are translated using the ``mzip`` function, which
1486 requires a ``MonadZip`` instance defined in
1487 :base-ref:`Control.Monad.Zip.`:
1491 do (x,y) <- mzip (do x <- [1..10]
1497 All these features are enabled by default if the :extension:`MonadComprehensions`
1498 extension is enabled. The types and more detailed examples on how to use
1499 comprehensions are explained in the previous chapters
1500 :ref:`generalised-list-comprehensions` and
1501 :ref:`parallel-list-comprehensions`. In general you just have to replace
1502 the type ``[a]`` with the type ``Monad m => m a`` for monad
1506 Even though most of these examples are using the list monad, monad
1507 comprehensions work for any monad. The ``base`` package offers all
1508 necessary instances for lists, which make :extension:`MonadComprehensions`
1509 backward compatible to built-in, transform and parallel list
1512 More formally, the desugaring is as follows. We write ``D[ e | Q]`` to
1513 mean the desugaring of the monad comprehension ``[ e | Q]``:
1515 .. code-block:: none
1519 Lists of qualifiers: Q,R,S
1523 D[ e | p <- e, Q ] = e >>= \p -> D[ e | Q ]
1524 D[ e | e, Q ] = guard e >> \p -> D[ e | Q ]
1525 D[ e | let d, Q ] = let d in D[ e | Q ]
1527 -- Parallel comprehensions (iterate for multiple parallel branches)
1528 D[ e | (Q | R), S ] = mzip D[ Qv | Q ] D[ Rv | R ] >>= \(Qv,Rv) -> D[ e | S ]
1530 -- Transform comprehensions
1531 D[ e | Q then f, R ] = f D[ Qv | Q ] >>= \Qv -> D[ e | R ]
1533 D[ e | Q then f by b, R ] = f (\Qv -> b) D[ Qv | Q ] >>= \Qv -> D[ e | R ]
1535 D[ e | Q then group using f, R ] = f D[ Qv | Q ] >>= \ys ->
1536 case (fmap selQv1 ys, ..., fmap selQvn ys) of
1539 D[ e | Q then group by b using f, R ] = f (\Qv -> b) D[ Qv | Q ] >>= \ys ->
1540 case (fmap selQv1 ys, ..., fmap selQvn ys) of
1543 where Qv is the tuple of variables bound by Q (and used subsequently)
1544 selQvi is a selector mapping Qv to the ith component of Qv
1546 Operator Standard binding Expected type
1547 --------------------------------------------------------------------
1548 return GHC.Base t1 -> m t2
1549 (>>=) GHC.Base m1 t1 -> (t2 -> m2 t3) -> m3 t3
1550 (>>) GHC.Base m1 t1 -> m2 t2 -> m3 t3
1551 guard Control.Monad t1 -> m t2
1552 fmap GHC.Base forall a b. (a->b) -> n a -> n b
1553 mzip Control.Monad.Zip forall a b. m a -> m b -> m (a,b)
1555 The comprehension should typecheck when its desugaring would typecheck,
1556 except that (as discussed in :ref:`generalised-list-comprehensions`) in the
1557 "then ``f``" and "then group using ``f``" clauses, when the "by ``b``" qualifier
1558 is omitted, argument ``f`` should have a polymorphic type. In particular, "then
1559 ``Data.List.sort``" and "then group using ``Data.List.group``" are
1560 insufficiently polymorphic.
1562 Monad comprehensions support rebindable syntax
1563 (:ref:`rebindable-syntax`). Without rebindable syntax, the operators
1564 from the "standard binding" module are used; with rebindable syntax, the
1565 operators are looked up in the current lexical scope. For example,
1566 parallel comprehensions will be typechecked and desugared using whatever
1567 "``mzip``" is in scope.
1569 The rebindable operators must have the "Expected type" given in the
1570 table above. These types are surprisingly general. For example, you can
1571 use a bind operator with the type
1575 (>>=) :: T x y a -> (a -> T y z b) -> T x z b
1577 In the case of transform comprehensions, notice that the groups are
1578 parameterised over some arbitrary type ``n`` (provided it has an
1579 ``fmap``, as well as the comprehension being over an arbitrary monad.
1581 .. _monadfail-desugaring:
1583 New monadic failure desugaring mechanism
1584 ----------------------------------------
1586 .. extension:: MonadFailDesugaring
1587 :shortdesc: Enable monadfail desugaring.
1591 Use the ``MonadFail.fail`` instead of the legacy ``Monad.fail`` function
1592 when desugaring refutable patterns in ``do`` blocks.
1594 The ``-XMonadFailDesugaring`` extension switches the desugaring of
1595 ``do``-blocks to use ``MonadFail.fail`` instead of ``Monad.fail``. This will
1596 eventually be the default behaviour in a future GHC release, under the
1597 `MonadFail Proposal (MFP)
1598 <https://prime.haskell.org/wiki/Libraries/Proposals/MonadFail>`__.
1600 This extension is temporary, and will be deprecated in a future release. It is
1601 included so that library authors have a hard check for whether their code
1602 will work with future GHC versions.
1604 .. _rebindable-syntax:
1606 Rebindable syntax and the implicit Prelude import
1607 -------------------------------------------------
1609 .. extension:: NoImplicitPrelude
1610 :shortdesc: Don't implicitly ``import Prelude``.
1611 Implied by :extension:`RebindableSyntax`.
1615 Don't import ``Prelude`` by default.
1617 GHC normally imports ``Prelude.hi`` files for
1618 you. If you'd rather it didn't, then give it a ``-XNoImplicitPrelude``
1619 option. The idea is that you can then import a Prelude of your own. (But
1620 don't call it ``Prelude``; the Haskell module namespace is flat, and you
1621 must not conflict with any Prelude module.)
1623 .. extension:: RebindableSyntax
1624 :shortdesc: Employ rebindable syntax.
1625 Implies :extension:`NoImplicitPrelude`.
1627 :implies: :extension:`NoImplicitPrelude`
1630 Enable rebinding of a variety of usually-built-in operations.
1632 Suppose you are importing a Prelude of your own in order to define your
1633 own numeric class hierarchy. It completely defeats that purpose if the
1634 literal "1" means "``Prelude.fromInteger 1``", which is what the Haskell
1635 Report specifies. So the :extension:`RebindableSyntax` extension causes the
1636 following pieces of built-in syntax to refer to *whatever is in scope*,
1637 not the Prelude versions:
1639 - An integer literal ``368`` means "``fromInteger (368::Integer)``",
1640 rather than "``Prelude.fromInteger (368::Integer)``".
1642 - Fractional literals are handed in just the same way, except that the
1643 translation is ``fromRational (3.68::Rational)``.
1645 - The equality test in an overloaded numeric pattern uses whatever
1646 ``(==)`` is in scope.
1648 - The subtraction operation, and the greater-than-or-equal test, in
1649 ``n+k`` patterns use whatever ``(-)`` and ``(>=)`` are in scope.
1651 - Negation (e.g. "``- (f x)``") means "``negate (f x)``", both in
1652 numeric patterns, and expressions.
1654 - Conditionals (e.g. "``if`` e1 ``then`` e2 ``else`` e3") means
1655 "``ifThenElse`` e1 e2 e3". However ``case`` expressions are
1658 - "Do" notation is translated using whatever functions ``(>>=)``,
1659 ``(>>)``, and ``fail``, are in scope (not the Prelude versions). List
1660 comprehensions, ``mdo`` (:ref:`recursive-do-notation`), and parallel
1661 array comprehensions, are unaffected.
1663 - Arrow notation (see :ref:`arrow-notation`) uses whatever ``arr``,
1664 ``(>>>)``, ``first``, ``app``, ``(|||)`` and ``loop`` functions are
1665 in scope. But unlike the other constructs, the types of these
1666 functions must match the Prelude types very closely. Details are in
1667 flux; if you want to use this, ask!
1669 - List notation, such as ``[x,y]`` or ``[m..n]`` can also be treated
1670 via rebindable syntax if you use `-XOverloadedLists`;
1671 see :ref:`overloaded-lists`.
1673 - An overloaded label "``#foo``" means "``fromLabel @"foo"``", rather than
1674 "``GHC.OverloadedLabels.fromLabel @"foo"``" (see :ref:`overloaded-labels`).
1676 :extension:`RebindableSyntax` implies :extension:`NoImplicitPrelude`.
1678 In all cases (apart from arrow notation), the static semantics should be
1679 that of the desugared form, even if that is a little unexpected. For
1680 example, the static semantics of the literal ``368`` is exactly that of
1681 ``fromInteger (368::Integer)``; it's fine for ``fromInteger`` to have
1682 any of the types: ::
1684 fromInteger :: Integer -> Integer
1685 fromInteger :: forall a. Foo a => Integer -> a
1686 fromInteger :: Num a => a -> Integer
1687 fromInteger :: Integer -> Bool -> Bool
1689 Be warned: this is an experimental facility, with fewer checks than
1690 usual. Use ``-dcore-lint`` to typecheck the desugared program. If Core
1691 Lint is happy you should be all right.
1693 Things unaffected by :extension:`RebindableSyntax`
1694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1696 :extension:`RebindableSyntax` does not apply to any code generated from a
1697 ``deriving`` clause or declaration. To see why, consider the following code: ::
1699 {-# LANGUAGE RebindableSyntax, OverloadedStrings #-}
1700 newtype Text = Text String
1702 fromString :: String -> Text
1705 data Foo = Foo deriving Show
1707 This will generate code to the effect of: ::
1709 instance Show Foo where
1710 showsPrec _ Foo = showString "Foo"
1712 But because :extension:`RebindableSyntax` and :extension:`OverloadedStrings`
1713 are enabled, the ``"Foo"`` string literal would now be of type ``Text``, not
1714 ``String``, which ``showString`` doesn't accept! This causes the generated
1715 ``Show`` instance to fail to typecheck. It's hard to imagine any scenario where
1716 it would be desirable have :extension:`RebindableSyntax` behavior within
1717 derived code, so GHC simply ignores :extension:`RebindableSyntax` entirely
1718 when checking derived code.
1720 .. _postfix-operators:
1725 .. extension:: PostfixOperators
1726 :shortdesc: Enable postfix operators.
1730 Allow the use of post-fix operators
1732 The :extension:`PostfixOperators` extension enables a small extension to the syntax
1733 of left operator sections, which allows you to define postfix operators.
1734 The extension is this: the left section ::
1738 is equivalent (from the point of view of both type checking and
1739 execution) to the expression ::
1743 (for any expression ``e`` and operator ``(!)``. The strict Haskell 98
1744 interpretation is that the section is equivalent to ::
1748 That is, the operator must be a function of two arguments. GHC allows it
1749 to take only one argument, and that in turn allows you to write the
1752 The extension does not extend to the left-hand side of function
1753 definitions; you must define such a function in prefix form.
1760 .. extension:: TupleSections
1761 :shortdesc: Enable tuple sections.
1765 Allow the use of tuple section syntax
1767 The :extension:`TupleSections` extension enables partially applied
1768 tuple constructors. For example, the following program ::
1772 is considered to be an alternative notation for the more unwieldy
1777 You can omit any combination of arguments to the tuple, as in the
1780 (, "I", , , "Love", , 1337)
1782 which translates to ::
1784 \a b c d -> (a, "I", b, c, "Love", d, 1337)
1786 If you have `unboxed tuples <#unboxed-tuples>`__ enabled, tuple sections
1787 will also be available for them, like so ::
1791 Because there is no unboxed unit tuple, the following expression ::
1795 continues to stand for the unboxed singleton tuple data constructor.
1802 .. extension:: LambdaCase
1803 :shortdesc: Enable lambda-case expressions.
1807 Allow the use of lambda-case syntax.
1809 The :extension:`LambdaCase` extension enables expressions of the form ::
1811 \case { p1 -> e1; ...; pN -> eN }
1813 which is equivalent to ::
1815 \freshName -> case freshName of { p1 -> e1; ...; pN -> eN }
1817 Note that ``\case`` starts a layout, so you can write ::
1826 Empty case alternatives
1827 -----------------------
1829 .. extension:: EmptyCase
1830 :shortdesc: Allow empty case alternatives.
1834 Allow empty case expressions.
1836 The :extension:`EmptyCase` extension enables case expressions, or lambda-case
1837 expressions, that have no alternatives, thus: ::
1839 case e of { } -- No alternatives
1843 \case { } -- -XLambdaCase is also required
1845 This can be useful when you know that the expression being scrutinised
1846 has no non-bottom values. For example:
1854 With dependently-typed features it is more useful (see :ghc-ticket:`2431`). For
1855 example, consider these two candidate definitions of ``absurd``:
1862 absurd :: True :~: False -> a
1863 absurd x = error "absurd" -- (A)
1864 absurd x = case x of {} -- (B)
1866 We much prefer (B). Why? Because GHC can figure out that
1867 ``(True :~: False)`` is an empty type. So (B) has no partiality and GHC
1868 is able to compile with :ghc-flag:`-Wincomplete-patterns` and
1869 :ghc-flag:`-Werror`. On the other hand (A) looks dangerous, and GHC doesn't
1870 check to make sure that, in fact, the function can never get called.
1874 Multi-way if-expressions
1875 ------------------------
1877 .. extension:: MultiWayIf
1878 :shortdesc: Enable multi-way if-expressions.
1882 Allow the use of multi-way-``if`` syntax.
1884 With :extension:`MultiWayIf` extension GHC accepts conditional expressions with
1885 multiple branches: ::
1887 if | guard1 -> expr1
1891 which is roughly equivalent to ::
1898 Multi-way if expressions introduce a new layout context. So the example
1899 above is equivalent to: ::
1901 if { | guard1 -> expr1
1906 The following behaves as expected: ::
1908 if | guard1 -> if | guard2 -> expr2
1912 because layout translates it as ::
1914 if { | guard1 -> if { | guard2 -> expr2
1920 Layout with multi-way if works in the same way as other layout contexts,
1921 except that the semi-colons between guards in a multi-way if are
1922 optional. So it is not necessary to line up all the guards at the same
1923 column; this is consistent with the way guards work in function
1924 definitions and case expressions.
1926 .. _local-fixity-declarations:
1928 Local Fixity Declarations
1929 -------------------------
1931 A careful reading of the Haskell 98 Report reveals that fixity
1932 declarations (``infix``, ``infixl``, and ``infixr``) are permitted to
1933 appear inside local bindings such those introduced by ``let`` and
1934 ``where``. However, the Haskell Report does not specify the semantics of
1935 such bindings very precisely.
1937 In GHC, a fixity declaration may accompany a local binding: ::
1944 and the fixity declaration applies wherever the binding is in scope. For
1945 example, in a ``let``, it applies in the right-hand sides of other
1946 ``let``-bindings and the body of the ``let``\ C. Or, in recursive ``do``
1947 expressions (:ref:`recursive-do-notation`), the local fixity
1948 declarations of a ``let`` statement scope over other statements in the
1949 group, just as the bound name does.
1951 Moreover, a local fixity declaration *must* accompany a local binding
1952 of that name: it is not possible to revise the fixity of name bound
1955 let infixr 9 $ in ...
1957 Because local fixity declarations are technically Haskell 98, no extension is
1958 necessary to enable them.
1960 .. _package-imports:
1962 Import and export extensions
1963 ----------------------------
1965 Hiding things the imported module doesn't export
1966 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1968 Technically in Haskell 2010 this is illegal: ::
1974 import A hiding( g ) -- A does not export g
1977 The ``import A hiding( g )`` in module ``B`` is technically an error
1979 5.3.1 <http://www.haskell.org/onlinereport/haskell2010/haskellch5.html#x11-1020005.3.1>`__)
1980 because ``A`` does not export ``g``. However GHC allows it, in the
1981 interests of supporting backward compatibility; for example, a newer
1982 version of ``A`` might export ``g``, and you want ``B`` to work in
1985 The warning :ghc-flag:`-Wdodgy-imports`, which is off by default but included
1986 with :ghc-flag:`-W`, warns if you hide something that the imported module does
1989 .. _package-qualified-imports:
1991 Package-qualified imports
1992 ~~~~~~~~~~~~~~~~~~~~~~~~~
1994 .. extension:: PackageImports
1995 :shortdesc: Enable package-qualified imports.
1999 Allow the use of package-qualified ``import`` syntax.
2001 With the :extension:`PackageImports` extension, GHC allows import declarations to be
2002 qualified by the package name that the module is intended to be imported
2003 from. For example: ::
2005 import "network" Network.Socket
2007 would import the module ``Network.Socket`` from the package ``network``
2008 (any version). This may be used to disambiguate an import when the same
2009 module is available from multiple packages, or is present in both the
2010 current package being built and an external package.
2012 The special package name ``this`` can be used to refer to the current
2013 package being built.
2016 You probably don't need to use this feature, it was added mainly so that we
2017 can build backwards-compatible versions of packages when APIs change. It can
2018 lead to fragile dependencies in the common case: modules occasionally move
2019 from one package to another, rendering any package-qualified imports broken.
2020 See also :ref:`package-thinning-and-renaming` for an alternative way of
2021 disambiguating between module names.
2023 .. _safe-imports-ext:
2029 :shortdesc: Enable the :ref:`Safe Haskell <safe-haskell>` Safe mode.
2034 Declare the Safe Haskell state of the current module.
2036 .. extension:: Trustworthy
2037 :shortdesc: Enable the :ref:`Safe Haskell <safe-haskell>` Trustworthy mode.
2042 Declare the Safe Haskell state of the current module.
2044 .. extension:: Unsafe
2045 :shortdesc: Enable Safe Haskell Unsafe mode.
2050 Declare the Safe Haskell state of the current module.
2052 With the :extension:`Safe`, :extension:`Trustworthy` and :extension:`Unsafe`
2053 language flags, GHC extends the import declaration syntax to take an optional
2054 ``safe`` keyword after the ``import`` keyword. This feature is part of the Safe
2055 Haskell GHC extension. For example: ::
2057 import safe qualified Network.Socket as NS
2059 would import the module ``Network.Socket`` with compilation only
2060 succeeding if ``Network.Socket`` can be safely imported. For a description of
2061 when a import is considered safe see :ref:`safe-haskell`.
2063 .. _explicit-namespaces:
2065 Explicit namespaces in import/export
2066 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2068 .. extension:: ExplicitNamespaces
2069 :shortdesc: Enable using the keyword ``type`` to specify the namespace of
2070 entries in imports and exports (:ref:`explicit-namespaces`).
2071 Implied by :extension:`TypeOperators` and :extension:`TypeFamilies`.
2075 Enable use of explicit namespaces in module export lists.
2077 In an import or export list, such as ::
2079 module M( f, (++) ) where ...
2083 the entities ``f`` and ``(++)`` are *values*. However, with type
2084 operators (:ref:`type-operators`) it becomes possible to declare
2085 ``(++)`` as a *type constructor*. In that case, how would you export or
2088 The :extension:`ExplicitNamespaces` extension allows you to prefix the name of
2089 a type constructor in an import or export list with "``type``" to
2090 disambiguate this case, thus: ::
2092 module M( f, type (++) ) where ...
2093 import N( f, type (++) )
2095 module N( f, type (++) ) where
2096 data family a ++ b = L a | R b
2098 The extension :extension:`ExplicitNamespaces` is implied by
2099 :extension:`TypeOperators` and (for some reason) by :extension:`TypeFamilies`.
2101 In addition, with :extension:`PatternSynonyms` you can prefix the name of a
2102 data constructor in an import or export list with the keyword
2103 ``pattern``, to allow the import or export of a data constructor without
2104 its parent type constructor (see :ref:`patsyn-impexp`).
2106 .. _block-arguments:
2108 More liberal syntax for function arguments
2109 ------------------------------------------
2111 .. extension:: BlockArguments
2112 :shortdesc: Allow ``do`` blocks and other constructs as function arguments.
2116 Allow ``do`` expressions, lambda expressions, etc. to be directly used as
2117 a function argument.
2119 In Haskell 2010, certain kinds of expressions can be used without parentheses
2120 as an argument to an operator, but not as an argument to a function.
2121 They include ``do``, lambda, ``if``, ``case``, and ``let``
2122 expressions. Some GHC extensions also define language constructs of this type:
2123 ``mdo`` (:ref:`recursive-do-notation`), ``\case`` (:ref:`lambda-case`), and
2124 ``proc`` (:ref:`arrow-notation`).
2126 The :extension:`BlockArguments` extension allows these constructs to be directly
2127 used as a function argument. For example::
2143 withForeignPtr fptr \ptr -> c_memcpy buf ptr size
2147 withForeignPtr fptr (\ptr -> c_memcpy buf ptr size)
2149 Changes to the grammar
2150 ~~~~~~~~~~~~~~~~~~~~~~
2152 The Haskell report `defines
2153 <https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-220003>`_
2154 the ``lexp`` nonterminal thus (``*`` indicates a rule of interest)::
2156 lexp → \ apat1 … apatn -> exp (lambda abstraction, n ≥ 1) *
2157 | let decls in exp (let expression) *
2158 | if exp [;] then exp [;] else exp (conditional) *
2159 | case exp of { alts } (case expression) *
2160 | do { stmts } (do expression) *
2163 fexp → [fexp] aexp (function application)
2165 aexp → qvar (variable)
2166 | gcon (general constructor)
2168 | ( exp ) (parenthesized expression)
2169 | qcon { fbind1 … fbindn } (labeled construction)
2170 | aexp { fbind1 … fbindn } (labelled update)
2173 The :extension:`BlockArguments` extension moves these production rules under
2178 fexp → [fexp] aexp (function application)
2180 aexp → qvar (variable)
2181 | gcon (general constructor)
2183 | ( exp ) (parenthesized expression)
2184 | qcon { fbind1 … fbindn } (labeled construction)
2185 | aexp { fbind1 … fbindn } (labelled update)
2186 | \ apat1 … apatn -> exp (lambda abstraction, n ≥ 1) *
2187 | let decls in exp (let expression) *
2188 | if exp [;] then exp [;] else exp (conditional) *
2189 | case exp of { alts } (case expression) *
2190 | do { stmts } (do expression) *
2193 Now the ``lexp`` nonterminal is redundant and can be dropped from the grammar.
2195 Note that this change relies on an existing meta-rule to resolve ambiguities:
2197 The grammar is ambiguous regarding the extent of lambda abstractions, let
2198 expressions, and conditionals. The ambiguity is resolved by the meta-rule
2199 that each of these constructs extends as far to the right as possible.
2201 For example, ``f \a -> a b`` will be parsed as ``f (\a -> a b)``, not as ``f
2206 Summary of stolen syntax
2207 ------------------------
2209 Turning on an option that enables special syntax *might* cause working
2210 Haskell 98 code to fail to compile, perhaps because it uses a variable
2211 name which has become a reserved word. This section lists the syntax
2212 that is "stolen" by language extensions. We use notation and nonterminal
2213 names from the Haskell 98 lexical syntax (see the Haskell 98 Report). We
2214 only list syntax changes here that might affect existing working
2215 programs (i.e. "stolen" syntax). Many of these extensions will also
2216 enable new context-free syntax, but in all cases programs written to use
2217 the new syntax would not be compilable without the option enabled.
2219 There are two classes of special syntax:
2221 - New reserved words and symbols: character sequences which are no
2222 longer available for use as identifiers in the program.
2224 - Other special syntax: sequences of characters that have a different
2225 meaning when this particular option is turned on.
2227 The following syntax is stolen:
2233 Stolen (in types) by: :extension:`ExplicitForAll`, and hence by
2234 :extension:`ScopedTypeVariables`, :extension:`LiberalTypeSynonyms`,
2235 :extension:`RankNTypes`, :extension:`ExistentialQuantification`
2241 Stolen by: :extension:`RecursiveDo`
2247 Stolen by: :extension:`ForeignFunctionInterface`
2249 ``rec``, ``proc``, ``-<``, ``>-``, ``-<<``, ``>>-``, ``(|``, ``|)``
2253 Stolen by: :extension:`Arrows`
2257 single: implicit parameters
2259 Stolen by: :extension:`ImplicitParams`
2261 ``[|``, ``[e|``, ``[p|``, ``[d|``, ``[t|``, ``[||``, ``[e||``
2263 single: Quasi-quotes
2265 Stolen by: :extension:`QuasiQuotes`. Moreover, this introduces an ambiguity
2266 with list comprehension syntax. See the
2267 :ref:`discussion on quasi-quoting <quasi-quotes-list-comprehension-ambiguity>`
2270 ``$(``, ``$$(``, ``$varid``, ``$$varid``
2272 single: Template Haskell
2274 Stolen by: :extension:`TemplateHaskell`
2278 single: quasi-quotation
2280 Stolen by: :extension:`QuasiQuotes`
2282 ⟨varid⟩, ``#``\ ⟨char⟩, ``#``, ⟨string⟩, ``#``, ⟨integer⟩, ``#``, ⟨float⟩, ``#``, ⟨float⟩, ``##``
2283 Stolen by: :extension:`MagicHash`
2286 Stolen by: :extension:`UnboxedTuples`
2288 ⟨varid⟩, ``!``, ⟨varid⟩
2289 Stolen by: :extension:`BangPatterns`
2292 Stolen by: :extension:`PatternSynonyms`
2294 .. _data-type-extensions:
2296 Extensions to data types and type synonyms
2297 ==========================================
2301 Data types with no constructors
2302 -------------------------------
2304 .. extension:: EmptyDataDecls
2305 :shortdesc: Allow definition of empty ``data`` types.
2309 Allow definition of empty ``data`` types.
2311 With the :extension:`EmptyDataDecls` extension, GHC
2312 lets you declare a data type with no constructors. For example: ::
2315 data T a -- T :: Type -> Type
2317 Syntactically, the declaration lacks the "= constrs" part. The type can be
2318 parameterised over types of any kind, but if the kind is not ``Type`` then an
2319 explicit kind annotation must be used (see :ref:`kinding`).
2321 Such data types have only one value, namely bottom. Nevertheless, they
2322 can be useful when defining "phantom types".
2324 In conjunction with the :ghc-flag:`-XEmptyDataDeriving` extension, empty data
2325 declarations can also derive instances of standard type classes
2326 (see :ref:`empty-data-deriving`).
2328 .. _datatype-contexts:
2333 .. extension:: DatatypeContexts
2334 :shortdesc: Allow contexts on ``data`` types.
2338 Allow contexts on ``data`` types.
2340 Haskell allows datatypes to be given contexts, e.g. ::
2342 data Eq a => Set a = NilSet | ConsSet a (Set a)
2344 give constructors with types: ::
2347 ConsSet :: Eq a => a -> Set a -> Set a
2349 This is widely considered a misfeature, and is going to be removed from
2350 the language. In GHC, it is controlled by the deprecated extension
2351 ``DatatypeContexts``.
2355 Infix type constructors, classes, and type variables
2356 ----------------------------------------------------
2358 GHC allows type constructors, classes, and type variables to be
2359 operators, and to be written infix, very much like expressions. More
2362 - A type constructor or class can be any non-reserved operator.
2363 Symbols used in types are always like capitalized identifiers; they
2364 are never variables. Note that this is different from the lexical
2365 syntax of data constructors, which are required to begin with a
2368 - Data type and type-synonym declarations can be written infix,
2369 parenthesised if you want further arguments. E.g. ::
2371 data a :*: b = Foo a b
2372 type a :+: b = Either a b
2373 class a :=: b where ...
2375 data (a :**: b) x = Baz a b x
2376 type (a :++: b) y = Either (a,b) y
2378 - Types, and class constraints, can be written infix. For example ::
2381 f :: (a :=: b) => a -> b
2383 - Back-quotes work as for expressions, both for type constructors and
2384 type variables; e.g. ``Int `Either` Bool``, or ``Int `a` Bool``.
2385 Similarly, parentheses work the same; e.g. ``(:*:) Int Bool``.
2387 - Fixities may be declared for type constructors, or classes, just as
2388 for data constructors. However, one cannot distinguish between the
2389 two in a fixity declaration; a fixity declaration sets the fixity for
2390 a data constructor and the corresponding type constructor. For
2395 sets the fixity for both type constructor ``T`` and data constructor
2396 ``T``, and similarly for ``:*:``. ``Int `a` Bool``.
2398 - Function arrow is ``infixr`` with fixity 0 (this might change; it's
2399 not clear what it should be).
2406 .. extension:: TypeOperators
2407 :shortdesc: Enable type operators.
2408 Implies :extension:`ExplicitNamespaces`.
2410 :implies: :extension:`ExplicitNamespaces`
2413 Allow the use and definition of types with operator names.
2415 In types, an operator symbol like ``(+)`` is normally treated as a type
2416 *variable*, just like ``a``. Thus in Haskell 98 you can say
2420 type T (+) = ((+), (+))
2421 -- Just like: type T a = (a,a)
2426 As you can see, using operators in this way is not very useful, and
2427 Haskell 98 does not even allow you to write them infix.
2429 The language :extension:`TypeOperators` changes this behaviour:
2431 - Operator symbols become type *constructors* rather than type
2434 - Operator symbols in types can be written infix, both in definitions
2435 and uses. For example: ::
2437 data a + b = Plus a b
2438 type Foo = Int + Bool
2440 - There is now some potential ambiguity in import and export lists; for
2441 example if you write ``import M( (+) )`` do you mean the *function*
2442 ``(+)`` or the *type constructor* ``(+)``? The default is the former,
2443 but with :extension:`ExplicitNamespaces` (which is implied by
2444 :extension:`TypeOperators`) GHC allows you to specify the latter by
2445 preceding it with the keyword ``type``, thus: ::
2447 import M( type (+) )
2449 See :ref:`explicit-namespaces`.
2451 - The fixity of a type operator may be set using the usual fixity
2452 declarations but, as in :ref:`infix-tycons`, the function and type
2453 constructor share a single fixity.
2457 Liberalised type synonyms
2458 -------------------------
2460 .. extension:: LiberalTypeSynonyms
2461 :shortdesc: Enable liberalised type synonyms.
2463 :implies: :extension:`ExplicitForAll`
2466 Relax many of the Haskell 98 rules on type synonym definitions.
2468 Type synonyms are like macros at the type level, but Haskell 98 imposes
2469 many rules on individual synonym declarations. With the
2470 :extension:`LiberalTypeSynonyms` extension, GHC does validity checking on types
2471 *only after expanding type synonyms*. That means that GHC can be very
2472 much more liberal about type synonyms than Haskell 98.
2474 - You can write a ``forall`` (including overloading) in a type synonym,
2477 type Discard a = forall b. Show b => a -> b -> (a, String)
2482 g :: Discard Int -> (Int,String) -- A rank-2 type
2485 - If you also use :extension:`UnboxedTuples`, you can write an unboxed tuple
2486 in a type synonym: ::
2488 type Pr = (# Int, Int #)
2493 - You can apply a type synonym to a forall type: ::
2495 type Foo a = a -> a -> Bool
2497 f :: Foo (forall b. b->b)
2499 After expanding the synonym, ``f`` has the legal (in GHC) type: ::
2501 f :: (forall b. b->b) -> (forall b. b->b) -> Bool
2503 - You can apply a type synonym to a partially applied type synonym: ::
2505 type Generic i o = forall x. i x -> o x
2508 foo :: Generic Id []
2510 After expanding the synonym, ``foo`` has the legal (in GHC) type: ::
2512 foo :: forall x. x -> [x]
2514 GHC currently does kind checking before expanding synonyms (though even
2515 that could be changed).
2517 After expanding type synonyms, GHC does validity checking on types,
2518 looking for the following malformedness which isn't detected simply by
2521 - Type constructor applied to a type involving for-alls (if
2522 :extension:`ImpredicativeTypes` is off)
2524 - Partially-applied type synonym.
2526 So, for example, this will be rejected: ::
2528 type Pr = forall a. a
2533 because GHC does not allow type constructors applied to for-all types.
2535 .. _existential-quantification:
2537 Existentially quantified data constructors
2538 ------------------------------------------
2540 .. extension:: ExistentialQuantification
2541 :shortdesc: Enable liberalised type synonyms.
2543 :implies: :extension:`ExplicitForAll`
2546 Allow existentially quantified type variables in types.
2548 The idea of using existential quantification in data type declarations
2549 was suggested by Perry, and implemented in Hope+ (Nigel Perry, *The
2550 Implementation of Practical Functional Programming Languages*, PhD
2551 Thesis, University of London, 1991). It was later formalised by Laufer
2552 and Odersky (*Polymorphic type inference and abstract data types*,
2553 TOPLAS, 16(5), pp. 1411-1430, 1994). It's been in Lennart Augustsson's
2554 ``hbc`` Haskell compiler for several years, and proved very useful.
2555 Here's the idea. Consider the declaration: ::
2557 data Foo = forall a. MkFoo a (a -> Bool)
2560 The data type ``Foo`` has two constructors with types: ::
2562 MkFoo :: forall a. a -> (a -> Bool) -> Foo
2565 Notice that the type variable ``a`` in the type of ``MkFoo`` does not
2566 appear in the data type itself, which is plain ``Foo``. For example, the
2567 following expression is fine: ::
2569 [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
2571 Here, ``(MkFoo 3 even)`` packages an integer with a function ``even``
2572 that maps an integer to ``Bool``; and ``MkFoo 'c'
2573 isUpper`` packages a character with a compatible function. These two
2574 things are each of type ``Foo`` and can be put in a list.
2576 What can we do with a value of type ``Foo``? In particular, what
2577 happens when we pattern-match on ``MkFoo``? ::
2579 f (MkFoo val fn) = ???
2581 Since all we know about ``val`` and ``fn`` is that they are compatible,
2582 the only (useful) thing we can do with them is to apply ``fn`` to
2583 ``val`` to get a boolean. For example: ::
2586 f (MkFoo val fn) = fn val
2588 What this allows us to do is to package heterogeneous values together
2589 with a bunch of functions that manipulate them, and then treat that
2590 collection of packages in a uniform manner. You can express quite a bit
2591 of object-oriented-like programming this way.
2598 What has this to do with *existential* quantification? Simply that
2599 ``MkFoo`` has the (nearly) isomorphic type ::
2601 MkFoo :: (exists a . (a, a -> Bool)) -> Foo
2603 But Haskell programmers can safely think of the ordinary *universally*
2604 quantified type given above, thereby avoiding adding a new existential
2605 quantification construct.
2607 .. _existential-with-context:
2609 Existentials and type classes
2610 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2612 An easy extension is to allow arbitrary contexts before the constructor.
2615 data Baz = forall a. Eq a => Baz1 a a
2616 | forall b. Show b => Baz2 b (b -> b)
2618 The two constructors have the types you'd expect: ::
2620 Baz1 :: forall a. Eq a => a -> a -> Baz
2621 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
2623 But when pattern matching on ``Baz1`` the matched values can be compared
2624 for equality, and when pattern matching on ``Baz2`` the first matched
2625 value can be converted to a string (as well as applying the function to
2626 it). So this program is legal: ::
2629 f (Baz1 p q) | p == q = "Yes"
2631 f (Baz2 v fn) = show (fn v)
2633 Operationally, in a dictionary-passing implementation, the constructors
2634 ``Baz1`` and ``Baz2`` must store the dictionaries for ``Eq`` and
2635 ``Show`` respectively, and extract it on pattern matching.
2637 .. _existential-records:
2642 GHC allows existentials to be used with records syntax as well. For
2645 data Counter a = forall self. NewCounter
2647 , _inc :: self -> self
2648 , _display :: self -> IO ()
2652 Here ``tag`` is a public field, with a well-typed selector function
2653 ``tag :: Counter a -> a``. The ``self`` type is hidden from the outside;
2654 any attempt to apply ``_this``, ``_inc`` or ``_display`` as functions
2655 will raise a compile-time error. In other words, *GHC defines a record
2656 selector function only for fields whose type does not mention the
2657 existentially-quantified variables*. (This example used an underscore in
2658 the fields for which record selectors will not be defined, but that is
2659 only programming style; GHC ignores them.)
2661 To make use of these hidden fields, we need to create some helper
2664 inc :: Counter a -> Counter a
2665 inc (NewCounter x i d t) = NewCounter
2666 { _this = i x, _inc = i, _display = d, tag = t }
2668 display :: Counter a -> IO ()
2669 display NewCounter{ _this = x, _display = d } = d x
2671 Now we can define counters with different underlying implementations: ::
2673 counterA :: Counter String
2674 counterA = NewCounter
2675 { _this = 0, _inc = (1+), _display = print, tag = "A" }
2677 counterB :: Counter String
2678 counterB = NewCounter
2679 { _this = "", _inc = ('#':), _display = putStrLn, tag = "B" }
2682 display (inc counterA) -- prints "1"
2683 display (inc (inc counterB)) -- prints "##"
2685 Record update syntax is supported for existentials (and GADTs): ::
2687 setTag :: Counter a -> a -> Counter a
2688 setTag obj t = obj{ tag = t }
2690 The rule for record update is this:
2692 the types of the updated fields may mention only the universally-quantified
2693 type variables of the data constructor. For GADTs, the field may mention
2694 only types that appear as a simple type-variable argument in the
2695 constructor's result type.
2699 data T a b where { T1 { f1::a, f2::b, f3::(b,c) } :: T a b } -- c is existential
2700 upd1 t x = t { f1=x } -- OK: upd1 :: T a b -> a' -> T a' b
2701 upd2 t x = t { f3=x } -- BAD (f3's type mentions c, which is
2702 -- existentially quantified)
2704 data G a b where { G1 { g1::a, g2::c } :: G a [c] }
2705 upd3 g x = g { g1=x } -- OK: upd3 :: G a b -> c -> G c b
2706 upd4 g x = g { g2=x } -- BAD (f2's type mentions c, which is not a simple
2707 -- type-variable argument in G1's result type)
2712 There are several restrictions on the ways in which existentially-quantified
2713 constructors can be used.
2715 - When pattern matching, each pattern match introduces a new, distinct,
2716 type for each existential type variable. These types cannot be
2717 unified with any other type, nor can they escape from the scope of
2718 the pattern match. For example, these fragments are incorrect: ::
2722 Here, the type bound by ``MkFoo`` "escapes", because ``a`` is the
2723 result of ``f1``. One way to see why this is wrong is to ask what
2726 f1 :: Foo -> a -- Weird!
2728 What is this "``a``" in the result type? Clearly we don't mean this: ::
2730 f1 :: forall a. Foo -> a -- Wrong!
2732 The original program is just plain wrong. Here's another sort of
2735 f2 (Baz1 a b) (Baz1 p q) = a==q
2737 It's ok to say ``a==b`` or ``p==q``, but ``a==q`` is wrong because it
2738 equates the two distinct types arising from the two ``Baz1``
2741 - You can't pattern-match on an existentially quantified constructor in
2742 a ``let`` or ``where`` group of bindings. So this is illegal: ::
2744 f3 x = a==b where { Baz1 a b = x }
2746 Instead, use a ``case`` expression: ::
2748 f3 x = case x of Baz1 a b -> a==b
2750 In general, you can only pattern-match on an existentially-quantified
2751 constructor in a ``case`` expression or in the patterns of a function
2752 definition. The reason for this restriction is really an
2753 implementation one. Type-checking binding groups is already a
2754 nightmare without existentials complicating the picture. Also an
2755 existential pattern binding at the top level of a module doesn't make
2756 sense, because it's not clear how to prevent the
2757 existentially-quantified type "escaping". So for now, there's a
2758 simple-to-state restriction. We'll see how annoying it is.
2760 - You can't use existential quantification for ``newtype``
2761 declarations. So this is illegal: ::
2763 newtype T = forall a. Ord a => MkT a
2765 Reason: a value of type ``T`` must be represented as a pair of a
2766 dictionary for ``Ord t`` and a value of type ``t``. That contradicts
2767 the idea that ``newtype`` should have no concrete representation. You
2768 can get just the same efficiency and effect by using ``data`` instead
2769 of ``newtype``. If there is no overloading involved, then there is
2770 more of a case for allowing an existentially-quantified ``newtype``,
2771 because the ``data`` version does carry an implementation cost, but
2772 single-field existentially quantified constructors aren't much use.
2773 So the simple restriction (no existential stuff on ``newtype``)
2774 stands, unless there are convincing reasons to change it.
2776 - You can't use ``deriving`` to define instances of a data type with
2777 existentially quantified data constructors. Reason: in most cases it
2778 would not make sense. For example:; ::
2780 data T = forall a. MkT [a] deriving( Eq )
2782 To derive ``Eq`` in the standard way we would need to have equality
2783 between the single component of two ``MkT`` constructors: ::
2786 (MkT a) == (MkT b) = ???
2788 But ``a`` and ``b`` have distinct types, and so can't be compared.
2789 It's just about possible to imagine examples in which the derived
2790 instance would make sense, but it seems altogether simpler simply to
2791 prohibit such declarations. Define your own instances!
2795 Declaring data types with explicit constructor signatures
2796 ---------------------------------------------------------
2798 .. extension:: GADTSyntax
2799 :shortdesc: Enable generalised algebraic data type syntax.
2803 Allow the use of GADT syntax in data type definitions (but not GADTs
2804 themselves; for this see :extension:`GADTs`)
2806 When the ``GADTSyntax`` extension is enabled, GHC allows you to declare
2807 an algebraic data type by giving the type signatures of constructors
2808 explicitly. For example: ::
2812 Just :: a -> Maybe a
2814 The form is called a "GADT-style declaration" because Generalised
2815 Algebraic Data Types, described in :ref:`gadt`, can only be declared
2818 Notice that GADT-style syntax generalises existential types
2819 (:ref:`existential-quantification`). For example, these two declarations
2822 data Foo = forall a. MkFoo a (a -> Bool)
2823 data Foo' where { MKFoo :: a -> (a->Bool) -> Foo' }
2825 Any data type that can be declared in standard Haskell 98 syntax can
2826 also be declared using GADT-style syntax. The choice is largely
2827 stylistic, but GADT-style declarations differ in one important respect:
2828 they treat class constraints on the data constructors differently.
2829 Specifically, if the constructor is given a type-class context, that
2830 context is made available by pattern matching. For example: ::
2833 MkSet :: Eq a => [a] -> Set a
2835 makeSet :: Eq a => [a] -> Set a
2836 makeSet xs = MkSet (nub xs)
2838 insert :: a -> Set a -> Set a
2839 insert a (MkSet as) | a `elem` as = MkSet as
2840 | otherwise = MkSet (a:as)
2842 A use of ``MkSet`` as a constructor (e.g. in the definition of
2843 ``makeSet``) gives rise to a ``(Eq a)`` constraint, as you would expect.
2844 The new feature is that pattern-matching on ``MkSet`` (as in the
2845 definition of ``insert``) makes *available* an ``(Eq a)`` context. In
2846 implementation terms, the ``MkSet`` constructor has a hidden field that
2847 stores the ``(Eq a)`` dictionary that is passed to ``MkSet``; so when
2848 pattern-matching that dictionary becomes available for the right-hand
2849 side of the match. In the example, the equality dictionary is used to
2850 satisfy the equality constraint generated by the call to ``elem``, so
2851 that the type of ``insert`` itself has no ``Eq`` constraint.
2853 For example, one possible application is to reify dictionaries: ::
2855 data NumInst a where
2856 MkNumInst :: Num a => NumInst a
2858 intInst :: NumInst Int
2861 plus :: NumInst a -> a -> a -> a
2862 plus MkNumInst p q = p + q
2864 Here, a value of type ``NumInst a`` is equivalent to an explicit
2865 ``(Num a)`` dictionary.
2867 All this applies to constructors declared using the syntax of
2868 :ref:`existential-with-context`. For example, the ``NumInst`` data type
2869 above could equivalently be declared like this: ::
2872 = Num a => MkNumInst (NumInst a)
2874 Notice that, unlike the situation when declaring an existential, there
2875 is no ``forall``, because the ``Num`` constrains the data type's
2876 universally quantified type variable ``a``. A constructor may have both
2877 universal and existential type variables: for example, the following two
2878 declarations are equivalent: ::
2881 = forall b. (Num a, Eq b) => MkT1 a b
2883 MkT2 :: (Num a, Eq b) => a -> b -> T2 a
2885 All this behaviour contrasts with Haskell 98's peculiar treatment of
2886 contexts on a data type declaration (Section 4.2.1 of the Haskell 98
2887 Report). In Haskell 98 the definition ::
2889 data Eq a => Set' a = MkSet' [a]
2891 gives ``MkSet'`` the same type as ``MkSet`` above. But instead of
2892 *making available* an ``(Eq a)`` constraint, pattern-matching on
2893 ``MkSet'`` *requires* an ``(Eq a)`` constraint! GHC faithfully
2894 implements this behaviour, odd though it is. But for GADT-style
2895 declarations, GHC's behaviour is much more useful, as well as much more
2898 The rest of this section gives further details about GADT-style data
2901 - The result type of each data constructor must begin with the type
2902 constructor being defined. If the result type of all constructors has
2903 the form ``T a1 ... an``, where ``a1 ... an`` are distinct type
2904 variables, then the data type is *ordinary*; otherwise is a
2905 *generalised* data type (:ref:`gadt`).
2907 - As with other type signatures, you can give a single signature for
2908 several data constructors. In this example we give a single signature
2909 for ``T1`` and ``T2``: ::
2915 - The type signature of each constructor is independent, and is
2916 implicitly universally quantified as usual. In particular, the type
2917 variable(s) in the "``data T a where``" header have no scope, and
2918 different constructors may have different universally-quantified type
2921 data T a where -- The 'a' has no scope
2922 T1,T2 :: b -> T b -- Means forall b. b -> T b
2923 T3 :: T a -- Means forall a. T a
2925 - A constructor signature may mention type class constraints, which can
2926 differ for different constructors. For example, this is fine: ::
2929 T1 :: Eq b => b -> b -> T b
2930 T2 :: (Show c, Ix c) => c -> [c] -> T c
2932 When pattern matching, these constraints are made available to
2933 discharge constraints in the body of the match. For example: ::
2936 f (T1 x y) | x==y = "yes"
2940 Note that ``f`` is not overloaded; the ``Eq`` constraint arising from
2941 the use of ``==`` is discharged by the pattern match on ``T1`` and
2942 similarly the ``Show`` constraint arising from the use of ``show``.
2944 - Unlike a Haskell-98-style data type declaration, the type variable(s)
2945 in the "``data Set a where``" header have no scope. Indeed, one can
2946 write a kind signature instead: ::
2948 data Set :: Type -> Type where ...
2950 or even a mixture of the two: ::
2952 data Bar a :: (Type -> Type) -> Type where ...
2954 The type variables (if given) may be explicitly kinded, so we could
2955 also write the header for ``Foo`` like this: ::
2957 data Bar a (b :: Type -> Type) where ...
2959 - You can use strictness annotations, in the obvious places in the
2960 constructor type: ::
2963 Lit :: !Int -> Term Int
2964 If :: Term Bool -> !(Term a) -> !(Term a) -> Term a
2965 Pair :: Term a -> Term b -> Term (a,b)
2967 - You can use a ``deriving`` clause on a GADT-style data type
2968 declaration. For example, these two declarations are equivalent ::
2970 data Maybe1 a where {
2971 Nothing1 :: Maybe1 a ;
2972 Just1 :: a -> Maybe1 a
2973 } deriving( Eq, Ord )
2975 data Maybe2 a = Nothing2 | Just2 a
2978 - The type signature may have quantified type variables that do not
2979 appear in the result type: ::
2982 MkFoo :: a -> (a->Bool) -> Foo
2985 Here the type variable ``a`` does not appear in the result type of
2986 either constructor. Although it is universally quantified in the type
2987 of the constructor, such a type variable is often called
2988 "existential". Indeed, the above declaration declares precisely the
2989 same type as the ``data Foo`` in :ref:`existential-quantification`.
2991 The type may contain a class context too, of course: ::
2994 MkShowable :: Show a => a -> Showable
2996 - You can use record syntax on a GADT-style data type declaration: ::
2999 Adult :: { name :: String, children :: [Person] } -> Person
3000 Child :: Show a => { name :: !String, funny :: a } -> Person
3002 As usual, for every constructor that has a field ``f``, the type of
3003 field ``f`` must be the same (modulo alpha conversion). The ``Child``
3004 constructor above shows that the signature may have a context,
3005 existentially-quantified variables, and strictness annotations, just
3006 as in the non-record case. (NB: the "type" that follows the
3007 double-colon is not really a type, because of the record syntax and
3008 strictness annotations. A "type" of this form can appear only in a
3009 constructor signature.)
3011 - Record updates are allowed with GADT-style declarations, only fields
3012 that have the following property: the type of the field mentions no
3013 existential type variables.
3015 - As in the case of existentials declared using the Haskell-98-like
3016 record syntax (:ref:`existential-records`), record-selector functions
3017 are generated only for those fields that have well-typed selectors.
3018 Here is the example of that section, in GADT-style syntax: ::
3020 data Counter a where
3021 NewCounter :: { _this :: self
3022 , _inc :: self -> self
3023 , _display :: self -> IO ()
3027 As before, only one selector function is generated here, that for
3028 ``tag``. Nevertheless, you can still use all the field names in
3029 pattern matching and record construction.
3031 - In a GADT-style data type declaration there is no obvious way to
3032 specify that a data constructor should be infix, which makes a
3033 difference if you derive ``Show`` for the type. (Data constructors
3034 declared infix are displayed infix by the derived ``show``.) So GHC
3035 implements the following design: a data constructor declared in a
3036 GADT-style data type declaration is displayed infix by ``Show`` iff
3037 (a) it is an operator symbol, (b) it has two arguments, (c) it has a
3038 programmer-supplied fixity declaration. For example
3044 (:--:) :: Int -> Bool -> T Int
3048 Generalised Algebraic Data Types (GADTs)
3049 ----------------------------------------
3051 .. extension:: GADTs
3052 :shortdesc: Enable generalised algebraic data types.
3053 Implies :extension:`GADTSyntax` and :extension:`MonoLocalBinds`.
3055 :implies: :extension:`MonoLocalBinds`, :extension:`GADTSyntax`
3058 Allow use of Generalised Algebraic Data Types (GADTs).
3060 Generalised Algebraic Data Types generalise ordinary algebraic data
3061 types by allowing constructors to have richer return types. Here is an
3065 Lit :: Int -> Term Int
3066 Succ :: Term Int -> Term Int
3067 IsZero :: Term Int -> Term Bool
3068 If :: Term Bool -> Term a -> Term a -> Term a
3069 Pair :: Term a -> Term b -> Term (a,b)
3071 Notice that the return type of the constructors is not always
3072 ``Term a``, as is the case with ordinary data types. This generality
3073 allows us to write a well-typed ``eval`` function for these ``Terms``: ::
3077 eval (Succ t) = 1 + eval t
3078 eval (IsZero t) = eval t == 0
3079 eval (If b e1 e2) = if eval b then eval e1 else eval e2
3080 eval (Pair e1 e2) = (eval e1, eval e2)
3082 The key point about GADTs is that *pattern matching causes type
3083 refinement*. For example, in the right hand side of the equation ::
3088 the type ``a`` is refined to ``Int``. That's the whole point! A precise
3089 specification of the type rules is beyond what this user manual aspires
3090 to, but the design closely follows that described in the paper `Simple
3091 unification-based type inference for
3092 GADTs <http://research.microsoft.com/%7Esimonpj/papers/gadt/>`__, (ICFP
3093 2006). The general principle is this: *type refinement is only carried
3094 out based on user-supplied type annotations*. So if no type signature is
3095 supplied for ``eval``, no type refinement happens, and lots of obscure
3096 error messages will occur. However, the refinement is quite general. For
3097 example, if we had: ::
3099 eval :: Term a -> a -> a
3100 eval (Lit i) j = i+j
3102 the pattern match causes the type ``a`` to be refined to ``Int``
3103 (because of the type of the constructor ``Lit``), and that refinement
3104 also applies to the type of ``j``, and the result type of the ``case``
3105 expression. Hence the addition ``i+j`` is legal.
3107 These and many other examples are given in papers by Hongwei Xi, and Tim
3108 Sheard. There is a longer introduction `on the
3109 wiki <http://www.haskell.org/haskellwiki/GADT>`__, and Ralf Hinze's `Fun
3111 types <http://www.cs.ox.ac.uk/ralf.hinze/publications/With.pdf>`__ also
3112 has a number of examples. Note that papers may use different notation to
3113 that implemented in GHC.
3115 The rest of this section outlines the extensions to GHC that support
3116 GADTs. The extension is enabled with :extension:`GADTs`. The :extension:`GADTs` extension
3117 also sets :extension:`GADTSyntax` and :extension:`MonoLocalBinds`.
3119 - A GADT can only be declared using GADT-style syntax
3120 (:ref:`gadt-style`); the old Haskell 98 syntax for data declarations
3121 always declares an ordinary data type. The result type of each
3122 constructor must begin with the type constructor being defined, but
3123 for a GADT the arguments to the type constructor can be arbitrary
3124 monotypes. For example, in the ``Term`` data type above, the type of
3125 each constructor must end with ``Term ty``, but the ``ty`` need not
3126 be a type variable (e.g. the ``Lit`` constructor).
3128 - It is permitted to declare an ordinary algebraic data type using
3129 GADT-style syntax. What makes a GADT into a GADT is not the syntax,
3130 but rather the presence of data constructors whose result type is not
3133 - You cannot use a ``deriving`` clause for a GADT; only for an ordinary
3136 - As mentioned in :ref:`gadt-style`, record syntax is supported. For
3142 Lit :: { val :: Int } -> Term Int
3143 Succ :: { num :: Term Int } -> Term Int
3144 Pred :: { num :: Term Int } -> Term Int
3145 IsZero :: { arg :: Term Int } -> Term Bool
3146 Pair :: { arg1 :: Term a
3149 If :: { cnd :: Term Bool
3154 However, for GADTs there is the following additional constraint:
3155 every constructor that has a field ``f`` must have the same result
3156 type (modulo alpha conversion) Hence, in the above example, we cannot
3157 merge the ``num`` and ``arg`` fields above into a single name.
3158 Although their field types are both ``Term Int``, their selector
3159 functions actually have different types:
3163 num :: Term Int -> Term Int
3164 arg :: Term Bool -> Term Int
3166 - When pattern-matching against data constructors drawn from a GADT,
3167 for example in a ``case`` expression, the following rules apply:
3169 - The type of the scrutinee must be rigid.
3171 - The type of the entire ``case`` expression must be rigid.
3173 - The type of any free variable mentioned in any of the ``case``
3174 alternatives must be rigid.
3176 A type is "rigid" if it is completely known to the compiler at its
3177 binding site. The easiest way to ensure that a variable a rigid type
3178 is to give it a type signature. For more precise details see `Simple
3179 unification-based type inference for
3180 GADTs <http://research.microsoft.com/%7Esimonpj/papers/gadt/>`__. The
3181 criteria implemented by GHC are given in the Appendix.
3183 .. _record-system-extensions:
3185 Extensions to the record system
3186 ===============================
3188 .. _traditional-record-syntax:
3190 Traditional record syntax
3191 -------------------------
3193 .. extension:: NoTraditionalRecordSyntax
3194 :shortdesc: Disable support for traditional record syntax
3195 (as supported by Haskell 98) ``C {f = x}``
3199 Disallow use of record syntax.
3201 Traditional record syntax, such as ``C {f = x}``, is enabled by default.
3202 To disable it, you can use the :extension:`NoTraditionalRecordSyntax` extension.
3204 .. _disambiguate-fields:
3206 Record field disambiguation
3207 ---------------------------
3209 .. extension:: DisambiguateRecordFields
3210 :shortdesc: Enable record field disambiguation.
3211 Implied by :extension:`RecordWildCards`.
3217 Allow the compiler to automatically choose between identically-named
3218 record selectors based on type (if the choice is unambiguous).
3220 In record construction and record pattern matching it is entirely
3221 unambiguous which field is referred to, even if there are two different
3222 data types in scope with a common field name. For example:
3227 data S = MkS { x :: Int, y :: Bool }
3232 data T = MkT { x :: Int }
3234 ok1 (MkS { x = n }) = n+1 -- Unambiguous
3235 ok2 n = MkT { x = n+1 } -- Unambiguous
3237 bad1 k = k { x = 3 } -- Ambiguous
3238 bad2 k = x k -- Ambiguous
3240 Even though there are two ``x``'s in scope, it is clear that the ``x``
3241 in the pattern in the definition of ``ok1`` can only mean the field
3242 ``x`` from type ``S``. Similarly for the function ``ok2``. However, in
3243 the record update in ``bad1`` and the record selection in ``bad2`` it is
3244 not clear which of the two types is intended.
3246 Haskell 98 regards all four as ambiguous, but with the
3247 :extension:`DisambiguateRecordFields` extension, GHC will accept the former two. The
3248 rules are precisely the same as those for instance declarations in
3249 Haskell 98, where the method names on the left-hand side of the method
3250 bindings in an instance declaration refer unambiguously to the method of
3251 that class (provided they are in scope at all), even if there are other
3252 variables in scope with the same name. This reduces the clutter of
3253 qualified names when you import two records from different modules that
3254 use the same field name.
3258 - Field disambiguation can be combined with punning (see
3259 :ref:`record-puns`). For example: ::
3264 ok3 (MkS { x }) = x+1 -- Uses both disambiguation and punning
3266 - With :extension:`DisambiguateRecordFields` you can use *unqualified* field
3267 names even if the corresponding selector is only in scope *qualified*
3268 For example, assuming the same module ``M`` as in our earlier
3269 example, this is legal: ::
3272 import qualified M -- Note qualified
3274 ok4 (M.MkS { x = n }) = n+1 -- Unambiguous
3276 Since the constructor ``MkS`` is only in scope qualified, you must
3277 name it ``M.MkS``, but the field ``x`` does not need to be qualified
3278 even though ``M.x`` is in scope but ``x`` is not (In effect, it is
3279 qualified by the constructor).
3281 .. _duplicate-record-fields:
3283 Duplicate record fields
3284 -----------------------
3286 .. extension:: DuplicateRecordFields
3287 :shortdesc: Allow definition of record types with identically-named fields.
3289 :implies: :extension:`DisambiguateRecordFields`
3292 Allow definition of record types with identically-named fields.
3294 Going beyond :extension:`DisambiguateRecordFields` (see :ref:`disambiguate-fields`),
3295 the :extension:`DuplicateRecordFields` extension allows multiple datatypes to be
3296 declared using the same field names in a single module. For example, it allows
3300 data S = MkS { x :: Int }
3301 data T = MkT { x :: Bool }
3303 Uses of fields that are always unambiguous because they mention the constructor,
3304 including construction and pattern-matching, may freely use duplicated field
3305 names. For example, the following are permitted (just as with
3306 :extension:`DisambiguateRecordFields`): ::
3310 f (MkT { x = b }) = b
3312 Field names used as selector functions or in record updates must be unambiguous,
3313 either because there is only one such field in scope, or because a type
3314 signature is supplied, as described in the following sections.
3319 Fields may be used as selector functions only if they are unambiguous, so this
3320 is still not allowed if both ``S(x)`` and ``T(x)`` are in scope: ::
3324 An ambiguous selector may be disambiguated by the type being "pushed down" to
3325 the occurrence of the selector (see :ref:`higher-rank-type-inference` for more
3326 details on what "pushed down" means). For example, the following are permitted: ::
3333 ok3 = k x -- assuming we already have k :: (S -> Int) -> _
3335 In addition, the datatype that is meant may be given as a type signature on the
3336 argument to the selector: ::
3340 However, we do not infer the type of the argument to determine the datatype, or
3341 have any way of deferring the choice to the constraint solver. Thus the
3342 following is ambiguous: ::
3347 Even though a field label is duplicated in its defining module, it may be
3348 possible to use the selector unambiguously elsewhere. For example, another
3349 module could import ``S(x)`` but not ``T(x)``, and then use ``x`` unambiguously.
3354 In a record update such as ``e { x = 1 }``, if there are multiple ``x`` fields
3355 in scope, then the type of the context must fix which record datatype is
3356 intended, or a type annotation must be supplied. Consider the following
3359 data S = MkS { foo :: Int }
3360 data T = MkT { foo :: Int, bar :: Int }
3361 data U = MkU { bar :: Int, baz :: Int }
3363 Without :extension:`DuplicateRecordFields`, an update mentioning ``foo`` will always be
3364 ambiguous if all these definitions were in scope. When the extension is enabled,
3365 there are several options for disambiguating updates:
3367 - Check for types that have all the fields being updated. For example: ::
3369 f x = x { foo = 3, bar = 2 }
3371 Here ``f`` must be updating ``T`` because neither ``S`` nor ``U`` have both
3374 - Use the type being pushed in to the record update, as in the following: ::
3377 g1 x = x { foo = 3 }
3379 g2 x = x { foo = 3 } :: T
3381 g3 = k (x { foo = 3 }) -- assuming we already have k :: T -> _
3383 - Use an explicit type signature on the record expression, as in: ::
3385 h x = (x :: T) { foo = 3 }
3387 The type of the expression being updated will not be inferred, and no
3388 constraint-solving will be performed, so the following will be rejected as
3395 \x -> [x { foo = 3 }, blah :: T ]
3397 \ (x :: T) -> x { foo = 3 }
3399 Import and export of record fields
3400 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3402 When :extension:`DuplicateRecordFields` is enabled, an ambiguous field must be exported
3403 as part of its datatype, rather than at the top level. For example, the
3404 following is legal: ::
3406 module M (S(x), T(..)) where
3407 data S = MkS { x :: Int }
3408 data T = MkT { x :: Bool }
3410 However, this would not be permitted, because ``x`` is ambiguous: ::
3412 module M (x) where ...
3414 Similar restrictions apply on import.
3421 .. extension:: NamedFieldPuns
3422 :shortdesc: Enable record puns.
3426 Allow use of record puns.
3428 Record puns are enabled by the language extension :extension:`NamedFieldPuns`.
3430 When using records, it is common to write a pattern that binds a
3431 variable with the same name as a record field, such as: ::
3433 data C = C {a :: Int}
3436 Record punning permits the variable name to be elided, so one can simply
3441 to mean the same pattern as above. That is, in a record pattern, the
3442 pattern ``a`` expands into the pattern ``a = a`` for the same name
3447 - Record punning can also be used in an expression, writing, for
3454 let a = 1 in C {a = a}
3456 The expansion is purely syntactic, so the expanded right-hand side
3457 expression refers to the nearest enclosing variable that is spelled
3458 the same as the field name.
3460 - Puns and other patterns can be mixed in the same record: ::
3462 data C = C {a :: Int, b :: Int}
3463 f (C {a, b = 4}) = a
3465 - Puns can be used wherever record patterns occur (e.g. in ``let``
3466 bindings or at the top-level).
3468 - A pun on a qualified field name is expanded by stripping off the
3469 module qualifier. For example: ::
3475 f (M.C {M.a = a}) = a
3477 (This is useful if the field selector ``a`` for constructor ``M.C``
3478 is only in scope in qualified form.)
3480 .. _record-wildcards:
3485 .. extension:: RecordWildCards
3486 :shortdesc: Enable record wildcards.
3487 Implies :extension:`DisambiguateRecordFields`.
3489 :implies: :extension:`DisambiguateRecordFields`.
3492 Allow the use of wildcards in record construction and pattern matching.
3494 Record wildcards are enabled by the language extension :extension:`RecordWildCards`. This
3495 exension implies :extension:`DisambiguateRecordFields`.
3497 For records with many fields, it can be tiresome to write out each field
3498 individually in a record pattern, as in ::
3500 data C = C {a :: Int, b :: Int, c :: Int, d :: Int}
3501 f (C {a = 1, b = b, c = c, d = d}) = b + c + d
3503 Record wildcard syntax permits a "``..``" in a record pattern, where
3504 each elided field ``f`` is replaced by the pattern ``f = f``. For
3505 example, the above pattern can be written as ::
3507 f (C {a = 1, ..}) = b + c + d
3511 - Record wildcards in patterns can be mixed with other patterns,
3512 including puns (:ref:`record-puns`); for example, in a pattern
3513 ``(C {a = 1, b, ..})``. Additionally, record wildcards can be used
3514 wherever record patterns occur, including in ``let`` bindings and at
3515 the top-level. For example, the top-level binding ::
3519 defines ``b``, ``c``, and ``d``.
3521 - Record wildcards can also be used in an expression, when constructing
3522 a record. For example, ::
3524 let {a = 1; b = 2; c = 3; d = 4} in C {..}
3528 let {a = 1; b = 2; c = 3; d = 4} in C {a=a, b=b, c=c, d=d}
3530 The expansion is purely syntactic, so the record wildcard expression
3531 refers to the nearest enclosing variables that are spelled the same
3532 as the omitted field names.
3534 - For both pattern and expression wildcards, the "``..``" expands to
3535 the missing *in-scope* record fields. Specifically the expansion of
3536 "``C {..}``" includes ``f`` if and only if:
3538 - ``f`` is a record field of constructor ``C``.
3540 - The record field ``f`` is in scope somehow (either qualified or
3543 These rules restrict record wildcards to the situations in which the
3544 user could have written the expanded version. For example ::
3547 data R = R { a,b,c :: Int }
3552 The ``R{..}`` expands to ``R{M.a=a}``, omitting ``b`` since the
3553 record field is not in scope, and omitting ``c`` since the variable
3554 ``c`` is not in scope (apart from the binding of the record selector
3557 - When record wildcards are use in record construction, a field ``f``
3558 is initialised only if ``f`` is in scope,
3559 and is not imported or bound at top level.
3560 For example, ``f`` can be bound by an enclosing pattern match or
3561 let/where-binding. For example ::
3566 data R = R { a,b,c,d :: Int }
3570 f b = R { .. } -- Expands to R { b = b, d = d }
3574 Here, ``a`` is imported, and ``c`` is bound at top level, so neither
3575 contribute to the expansion of the "``..``".
3576 The motivation here is that it should be
3577 easy for the reader to figure out what the "``..``" expands to.
3579 - Record wildcards cannot be used (a) in a record update construct, and
3580 (b) for data constructors that are not declared with record fields.
3583 f x = x { v=True, .. } -- Illegal (a)
3585 data T = MkT Int Bool
3586 g = MkT { .. } -- Illegal (b)
3587 h (MkT { .. }) = True -- Illegal (b)
3590 .. _record-field-selector-polymorphism:
3592 Record field selector polymorphism
3593 ----------------------------------
3595 The module :base-ref:`GHC.Records.` defines the following: ::
3597 class HasField (x :: k) r a | x r -> a where
3600 A ``HasField x r a`` constraint represents the fact that ``x`` is a
3601 field of type ``a`` belonging to a record type ``r``. The
3602 ``getField`` method gives the record selector function.
3604 This allows definitions that are polymorphic over record types with a specified
3605 field. For example, the following works with any record type that has a field
3606 ``name :: String``: ::
3608 foo :: HasField "name" r String => r -> String
3609 foo r = reverse (getField @"name" r)
3611 ``HasField`` is a magic built-in typeclass (similar to ``Coercible``, for
3612 example). It is given special treatment by the constraint solver (see
3613 :ref:`solving-hasfield-constraints`). Users may define their own instances of
3614 ``HasField`` also (see :ref:`virtual-record-fields`).
3616 .. _solving-hasfield-constraints:
3618 Solving HasField constraints
3619 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3621 If the constraint solver encounters a constraint ``HasField x r a``
3622 where ``r`` is a concrete datatype with a field ``x`` in scope, it
3623 will automatically solve the constraint using the field selector as
3624 the dictionary, unifying ``a`` with the type of the field if
3625 necessary. This happens irrespective of which extensions are enabled.
3627 For example, if the following datatype is in scope ::
3629 data Person = Person { name :: String }
3631 the end result is rather like having an instance ::
3633 instance HasField "name" Person String where
3636 except that this instance is not actually generated anywhere, rather
3637 the constraint is solved directly by the constraint solver.
3639 A field must be in scope for the corresponding ``HasField`` constraint
3640 to be solved. This retains the existing representation hiding
3641 mechanism, whereby a module may choose not to export a field,
3642 preventing client modules from accessing or updating it directly.
3644 Solving ``HasField`` constraints depends on the field selector functions that
3645 are generated for each datatype definition:
3647 - If a record field does not have a selector function because its type would allow
3648 an existential variable to escape, the corresponding ``HasField`` constraint
3649 will not be solved. For example, ::
3651 {-# LANGUAGE ExistentialQuantification #-}
3652 data Exists t = forall x . MkExists { unExists :: t x }
3654 does not give rise to a selector ``unExists :: Exists t -> t x`` and we will not
3655 solve ``HasField "unExists" (Exists t) a`` automatically.
3657 - If a record field has a polymorphic type (and hence the selector function is
3658 higher-rank), the corresponding ``HasField`` constraint will not be solved,
3659 because doing so would violate the functional dependency on ``HasField`` and/or
3660 require impredicativity. For example, ::
3662 {-# LANGUAGE RankNTypes #-}
3663 data Higher = MkHigher { unHigher :: forall t . t -> t }
3665 gives rise to a selector ``unHigher :: Higher -> (forall t . t -> t)`` but does
3666 not lead to solution of the constraint ``HasField "unHigher" Higher a``.
3668 - A record GADT may have a restricted type for a selector function, which may lead
3669 to additional unification when solving ``HasField`` constraints. For example, ::
3671 {-# LANGUAGE GADTs #-}
3673 MkGadt :: { unGadt :: Maybe v } -> Gadt [v]
3675 gives rise to a selector ``unGadt :: Gadt [v] -> Maybe v``, so the solver will reduce
3676 the constraint ``HasField "unGadt" (Gadt t) b`` by unifying ``t ~ [v]`` and
3677 ``b ~ Maybe v`` for some fresh metavariable ``v``, rather as if we had an instance ::
3679 instance (t ~ [v], b ~ Maybe v) => HasField "unGadt" (Gadt t) b
3681 - If a record type has an old-fashioned datatype context, the ``HasField``
3682 constraint will be reduced to solving the constraints from the context.
3685 {-# LANGUAGE DatatypeContexts #-}
3686 data Eq a => Silly a = MkSilly { unSilly :: a }
3688 gives rise to a selector ``unSilly :: Eq a => Silly a -> a``, so
3689 the solver will reduce the constraint ``HasField "unSilly" (Silly a) b`` to
3690 ``Eq a`` (and unify ``a`` with ``b``), rather as if we had an instance ::
3692 instance (Eq a, a ~ b) => HasField "unSilly" (Silly a) b
3694 .. _virtual-record-fields:
3696 Virtual record fields
3697 ~~~~~~~~~~~~~~~~~~~~~
3699 Users may define their own instances of ``HasField``, provided they do
3700 not conflict with the built-in constraint solving behaviour. This
3701 allows "virtual" record fields to be defined for datatypes that do not
3702 otherwise have them.
3704 For example, this instance would make the ``name`` field of ``Person``
3705 accessible using ``#fullname`` as well: ::
3707 instance HasField "fullname" Person String where
3710 More substantially, an anonymous records library could provide
3711 ``HasField`` instances for its anonymous records, and thus be
3712 compatible with the polymorphic record selectors introduced by this
3713 proposal. For example, something like this makes it possible to use
3714 ``getField`` to access ``Record`` values with the appropriate
3715 string in the type-level list of fields: ::
3717 data Record (xs :: [(k, Type)]) where
3719 Cons :: Proxy x -> a -> Record xs -> Record ('(x, a) ': xs)
3721 instance HasField x (Record ('(x, a) ': xs)) a where
3722 getField (Cons _ v _) = v
3723 instance HasField x (Record xs) a => HasField x (Record ('(y, b) ': xs)) a where
3724 getField (Cons _ _ r) = getField @x r
3726 r :: Record '[ '("name", String) ]
3727 r = Cons Proxy "R" Nil)
3729 x = getField @"name" r
3731 Since representations such as this can support field labels with kinds other
3732 than ``Symbol``, the ``HasField`` class is poly-kinded (even though the built-in
3733 constraint solving works only at kind ``Symbol``). In particular, this allows
3734 users to declare scoped field labels such as in the following example: ::
3736 data PersonFields = Name
3738 s :: Record '[ '(Name, String) ]
3739 s = Cons Proxy "S" Nil
3741 y = getField @Name s
3743 In order to avoid conflicting with the built-in constraint solving,
3744 the following user-defined ``HasField`` instances are prohibited (in
3745 addition to the usual rules, such as the prohibition on type
3746 families appearing in instance heads):
3748 - ``HasField _ r _`` where ``r`` is a variable;
3750 - ``HasField _ (T ...) _`` if ``T`` is a data family (because it
3751 might have fields introduced later, using data instance declarations);
3753 - ``HasField x (T ...) _`` if ``x`` is a variable and ``T`` has any
3754 fields at all (but this instance is permitted if ``T`` has no fields);
3756 - ``HasField "foo" (T ...) _`` if ``T`` has a field ``foo`` (but this
3757 instance is permitted if it does not).
3759 If a field has a higher-rank or existential type, the corresponding ``HasField``
3760 constraint will not be solved automatically (as described above), but in the
3761 interests of simplicity we do not permit users to define their own instances
3762 either. If a field is not in scope, the corresponding instance is still
3763 prohibited, to avoid conflicts in downstream modules.
3768 Extensions to the "deriving" mechanism
3769 ======================================
3771 Haskell 98 allows the programmer to add a deriving clause to a data type
3772 declaration, to generate a standard instance declaration for specified class.
3773 GHC extends this mechanism along several axes:
3775 * The derivation mechanism can be used separtely from the data type
3776 declaration, using the `standalone deriving mechanism
3777 <#stand-alone-deriving>`__.
3779 * In Haskell 98, the only derivable classes are ``Eq``,
3780 ``Ord``, ``Enum``, ``Ix``, ``Bounded``, ``Read``, and ``Show``. `Various
3781 langauge extensions <#deriving-extra>`__ extend this list.
3783 * Besides the stock approach to deriving instances by generating all method
3784 definitions, GHC supports two additional deriving strategies, which can
3785 derive arbitrary classes:
3787 * `Generalised newtype deriving <#newtype-deriving>`__ for newtypes and
3788 * `deriving any class <#derive-any-class>`__ using an empty instance
3791 The user can optionally declare the desired `deriving strategy
3792 <#deriving-stragies>`__, especially if the compiler chooses the wrong
3793 one `by default <#default-deriving-strategy>`__.
3795 .. _empty-data-deriving:
3797 Deriving instances for empty data types
3798 ---------------------------------------
3800 .. ghc-flag:: -XEmptyDataDeriving
3801 :shortdesc: Allow deriving instances of standard type classes for
3804 :reverse: -XNoEmptyDataDeriving
3809 Allow deriving instances of standard type classes for empty data types.
3811 One can write data types with no constructors using the
3812 :ghc-flag:`-XEmptyDataDecls` flag (see :ref:`nullary-types`), which is on by
3813 default in Haskell 2010. What is not on by default is the ability to derive
3814 type class instances for these types. This ability is enabled through use of
3815 the :ghc-flag:`-XEmptyDataDeriving` flag. For instance, this lets one write: ::
3817 data Empty deriving (Eq, Ord, Read, Show)
3819 This would generate the following instances: ::
3821 instance Eq Empty where
3824 instance Ord Empty where
3827 instance Read Empty where
3830 instance Show Empty where
3831 showsPrec _ x = case x of {}
3833 The :ghc-flag:`-XEmptyDataDeriving` flag is only required to enable deriving
3834 of these four "standard" type classes (which are mentioned in the Haskell
3835 Report). Other extensions to the ``deriving`` mechanism, which are explained
3836 below in greater detail, do not require :ghc-flag:`-XEmptyDataDeriving` to be
3837 used in conjunction with empty data types. These include:
3839 * :ghc-flag:`-XStandaloneDeriving` (see :ref:`stand-alone-deriving`)
3840 * Type classes which require their own extensions to be enabled to be derived,
3841 such as :ghc-flag:`-XDeriveFunctor` (see :ref:`deriving-extra`)
3842 * :ghc-flag:`-XDeriveAnyClass` (see :ref:`derive-any-class`)
3844 .. _deriving-inferred:
3846 Inferred context for deriving clauses
3847 -------------------------------------
3849 The Haskell Report is vague about exactly when a ``deriving`` clause is
3850 legal. For example: ::
3852 data T0 f a = MkT0 a deriving( Eq )
3853 data T1 f a = MkT1 (f a) deriving( Eq )
3854 data T2 f a = MkT2 (f (f a)) deriving( Eq )
3856 The natural generated ``Eq`` code would result in these instance
3859 instance Eq a => Eq (T0 f a) where ...
3860 instance Eq (f a) => Eq (T1 f a) where ...
3861 instance Eq (f (f a)) => Eq (T2 f a) where ...
3863 The first of these is obviously fine. The second is still fine, although
3864 less obviously. The third is not Haskell 98, and risks losing
3865 termination of instances.
3867 GHC takes a conservative position: it accepts the first two, but not the
3868 third. The rule is this: each constraint in the inferred instance
3869 context must consist only of type variables, with no repetitions.
3871 This rule is applied regardless of flags. If you want a more exotic
3872 context, you can write it yourself, using the `standalone deriving
3873 mechanism <#stand-alone-deriving>`__.
3875 .. _stand-alone-deriving:
3877 Stand-alone deriving declarations
3878 ---------------------------------
3880 .. extension:: StandaloneDeriving
3881 :shortdesc: Enable standalone deriving.
3885 Allow the use of stand-alone ``deriving`` declarations.
3887 GHC allows stand-alone ``deriving`` declarations, enabled by
3888 :extension:`StandaloneDeriving`: ::
3890 data Foo a = Bar a | Baz String
3892 deriving instance Eq a => Eq (Foo a)
3894 The syntax is identical to that of an ordinary instance declaration
3895 apart from (a) the keyword ``deriving``, and (b) the absence of the
3898 However, standalone deriving differs from a ``deriving`` clause in a
3899 number of important ways:
3901 - The standalone deriving declaration does not need to be in the same
3902 module as the data type declaration. (But be aware of the dangers of
3903 orphan instances (:ref:`orphan-modules`).
3905 - In most cases, you must supply an explicit context (in the example the
3906 context is ``(Eq a)``), exactly as you would in an ordinary instance
3907 declaration. (In contrast, in a ``deriving`` clause attached to a
3908 data type declaration, the context is inferred.)
3910 The exception to this rule is that the context of a standalone deriving
3911 declaration can infer its context when a single, extra-wildcards constraint
3912 is used as the context, such as in: ::
3914 deriving instance _ => Eq (Foo a)
3916 This is essentially the same as if you had written ``deriving Foo`` after
3917 the declaration for ``data Foo a``. Using this feature requires the use of
3918 :extension:`PartialTypeSignatures` (:ref:`partial-type-signatures`).
3920 - Unlike a ``deriving`` declaration attached to a ``data`` declaration,
3921 the instance can be more specific than the data type (assuming you
3922 also use :extension:`FlexibleInstances`, :ref:`instance-rules`). Consider
3925 data Foo a = Bar a | Baz String
3927 deriving instance Eq a => Eq (Foo [a])
3928 deriving instance Eq a => Eq (Foo (Maybe a))
3930 This will generate a derived instance for ``(Foo [a])`` and
3931 ``(Foo (Maybe a))``, but other types such as ``(Foo (Int,Bool))``
3932 will not be an instance of ``Eq``.
3934 - Unlike a ``deriving`` declaration attached to a ``data`` declaration,
3935 GHC does not restrict the form of the data type. Instead, GHC simply
3936 generates the appropriate boilerplate code for the specified class,
3937 and typechecks it. If there is a type error, it is your problem. (GHC
3938 will show you the offending code if it has a type error.)
3940 The merit of this is that you can derive instances for GADTs and
3941 other exotic data types, providing only that the boilerplate code
3942 does indeed typecheck. For example: ::
3948 deriving instance Show (T a)
3950 In this example, you cannot say ``... deriving( Show )`` on the data
3951 type declaration for ``T``, because ``T`` is a GADT, but you *can*
3952 generate the instance declaration using stand-alone deriving.
3954 The down-side is that, if the boilerplate code fails to typecheck,
3955 you will get an error message about that code, which you did not
3956 write. Whereas, with a ``deriving`` clause the side-conditions are
3957 necessarily more conservative, but any error message may be more
3960 - Under most circumstances, you cannot use standalone deriving to create an
3961 instance for a data type whose constructors are not all in scope. This is
3962 because the derived instance would generate code that uses the constructors
3963 behind the scenes, which would break abstraction.
3965 The one exception to this rule is :extension:`DeriveAnyClass`, since
3966 deriving an instance via :extension:`DeriveAnyClass` simply generates
3967 an empty instance declaration, which does not require the use of any
3968 constructors. See the `deriving any class <#derive-any-class>`__ section
3971 In other ways, however, a standalone deriving obeys the same rules as
3974 - A ``deriving instance`` declaration must obey the same rules
3975 concerning form and termination as ordinary instance declarations,
3976 controlled by the same flags; see :ref:`instance-decls`.
3978 - The stand-alone syntax is generalised for newtypes in exactly the
3979 same way that ordinary ``deriving`` clauses are generalised
3980 (:ref:`newtype-deriving`). For example: ::
3982 newtype Foo a = MkFoo (State Int a)
3984 deriving instance MonadState Int Foo
3986 GHC always treats the *last* parameter of the instance (``Foo`` in
3987 this example) as the type whose instance is being derived.
3991 Deriving instances of extra classes (``Data``, etc.)
3992 ----------------------------------------------------
3994 Haskell 98 allows the programmer to add "``deriving( Eq, Ord )``" to a
3995 data type declaration, to generate a standard instance declaration for
3996 classes specified in the ``deriving`` clause. In Haskell 98, the only
3997 classes that may appear in the ``deriving`` clause are the standard
3998 classes ``Eq``, ``Ord``, ``Enum``, ``Ix``, ``Bounded``, ``Read``, and
4001 GHC extends this list with several more classes that may be
4002 automatically derived:
4004 - With :extension:`DeriveGeneric`, you can derive instances of the classes
4005 ``Generic`` and ``Generic1``, defined in ``GHC.Generics``. You can
4006 use these to define generic functions, as described in
4007 :ref:`generic-programming`.
4009 - With :extension:`DeriveFunctor`, you can derive instances of the class
4010 ``Functor``, defined in ``GHC.Base``.
4012 - With :extension:`DeriveDataTypeable`, you can derive instances of the class
4013 ``Data``, defined in ``Data.Data``.
4015 - With :extension:`DeriveFoldable`, you can derive instances of the class
4016 ``Foldable``, defined in ``Data.Foldable``.
4018 - With :extension:`DeriveTraversable`, you can derive instances of the class
4019 ``Traversable``, defined in ``Data.Traversable``. Since the
4020 ``Traversable`` instance dictates the instances of ``Functor`` and
4021 ``Foldable``, you'll probably want to derive them too, so
4022 :extension:`DeriveTraversable` implies :extension:`DeriveFunctor` and
4023 :extension:`DeriveFoldable`.
4025 - With :extension:`DeriveLift`, you can derive instances of the class ``Lift``,
4026 defined in the ``Language.Haskell.TH.Syntax`` module of the
4027 ``template-haskell`` package.
4029 You can also use a standalone deriving declaration instead (see
4030 :ref:`stand-alone-deriving`).
4032 In each case the appropriate class must be in scope before it can be
4033 mentioned in the ``deriving`` clause.
4035 .. _deriving-functor:
4037 Deriving ``Functor`` instances
4038 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4040 .. extension:: DeriveFunctor
4041 :shortdesc: Enable deriving for the Functor class.
4042 Implied by :extension:`DeriveTraversable`.
4046 Allow automatic deriving of instances for the ``Functor`` typeclass.
4049 With :extension:`DeriveFunctor`, one can derive ``Functor`` instances for data types
4050 of kind ``Type -> Type``. For example, this declaration::
4052 data Example a = Ex a Char (Example a) (Example Char)
4055 would generate the following instance: ::
4057 instance Functor Example where
4058 fmap f (Ex a1 a2 a3 a4) = Ex (f a1) a2 (fmap f a3) a4
4060 The basic algorithm for :extension:`DeriveFunctor` walks the arguments of each
4061 constructor of a data type, applying a mapping function depending on the type
4062 of each argument. If a plain type variable is found that is syntactically
4063 equivalent to the last type parameter of the data type (``a`` in the above
4064 example), then we apply the function ``f`` directly to it. If a type is
4065 encountered that is not syntactically equivalent to the last type parameter
4066 *but does mention* the last type parameter somewhere in it, then a recursive
4067 call to ``fmap`` is made. If a type is found which doesn't mention the last
4068 type parameter at all, then it is left alone.
4070 The second of those cases, in which a type is unequal to the type parameter but
4071 does contain the type parameter, can be surprisingly tricky. For example, the
4072 following example compiles::
4074 newtype Right a = Right (Either Int a) deriving Functor
4076 Modifying the code slightly, however, produces code which will not compile::
4078 newtype Wrong a = Wrong (Either a Int) deriving Functor
4080 The difference involves the placement of the last type parameter, ``a``. In the
4081 ``Right`` case, ``a`` occurs within the type ``Either Int a``, and moreover, it
4082 appears as the last type argument of ``Either``. In the ``Wrong`` case,
4083 however, ``a`` is not the last type argument to ``Either``; rather, ``Int`` is.
4085 This distinction is important because of the way :extension:`DeriveFunctor` works. The
4086 derived ``Functor Right`` instance would be::
4088 instance Functor Right where
4089 fmap f (Right a) = Right (fmap f a)
4091 Given a value of type ``Right a``, GHC must produce a value of type
4092 ``Right b``. Since the argument to the ``Right`` constructor has type
4093 ``Either Int a``, the code recursively calls ``fmap`` on it to produce a value
4094 of type ``Either Int b``, which is used in turn to construct a final value of
4097 The generated code for the ``Functor Wrong`` instance would look exactly the
4098 same, except with ``Wrong`` replacing every occurrence of ``Right``. The
4099 problem is now that ``fmap`` is being applied recursively to a value of type
4100 ``Either a Int``. This cannot possibly produce a value of type
4101 ``Either b Int``, as ``fmap`` can only change the last type parameter! This
4102 causes the generated code to be ill-typed.
4104 As a general rule, if a data type has a derived ``Functor`` instance and its
4105 last type parameter occurs on the right-hand side of the data declaration, then
4106 either it must (1) occur bare (e.g., ``newtype Id a = Id a``), or (2) occur as the
4107 last argument of a type constructor (as in ``Right`` above).
4109 There are two exceptions to this rule:
4111 #. Tuple types. When a non-unit tuple is used on the right-hand side of a data
4112 declaration, :extension:`DeriveFunctor` treats it as a product of distinct types.
4113 In other words, the following code::
4115 newtype Triple a = Triple (a, Int, [a]) deriving Functor
4117 Would result in a generated ``Functor`` instance like so::
4119 instance Functor Triple where
4122 (a1, a2, a3) -> (f a1, a2, fmap f a3))
4124 That is, :extension:`DeriveFunctor` pattern-matches its way into tuples and maps
4125 over each type that constitutes the tuple. The generated code is
4126 reminiscient of what would be generated&