1 <?xml version="1.0" encoding="iso-8859-1"?>
3 <indexterm><primary>language, GHC</primary></indexterm>
4 <indexterm><primary>extensions, GHC</primary></indexterm>
5 As with all known Haskell systems, GHC implements some extensions to
6 the language. They are all enabled by options; by default GHC
7 understands only plain Haskell 98.
11 Some of the Glasgow extensions serve to give you access to the
12 underlying facilities with which we implement Haskell. Thus, you can
13 get at the Raw Iron, if you are willing to write some non-portable
14 code at a more primitive level. You need not be “stuck”
15 on performance because of the implementation costs of Haskell's
16 “high-level” features—you can always code
17 “under” them. In an extreme case, you can write all your
18 time-critical code in C, and then just glue it together with Haskell!
22 Before you get too carried away working at the lowest level (e.g.,
23 sloshing <literal>MutableByteArray#</literal>s around your
24 program), you may wish to check if there are libraries that provide a
25 “Haskellised veneer” over the features you want. The
26 separate <ulink url="../libraries/index.html">libraries
27 documentation</ulink> describes all the libraries that come with GHC.
30 <!-- LANGUAGE OPTIONS -->
31 <sect1 id="options-language">
32 <title>Language options</title>
34 <indexterm><primary>language</primary><secondary>option</secondary>
36 <indexterm><primary>options</primary><secondary>language</secondary>
38 <indexterm><primary>extensions</primary><secondary>options controlling</secondary>
41 <para>The language option flags control what variation of the language are
42 permitted. Leaving out all of them gives you standard Haskell
45 <para>Language options can be controlled in two ways:
47 <listitem><para>Every language option can switched on by a command-line flag "<option>-X...</option>"
48 (e.g. <option>-XTemplateHaskell</option>), and switched off by the flag "<option>-XNo...</option>";
49 (e.g. <option>-XNoTemplateHaskell</option>).</para></listitem>
51 Language options recognised by Cabal can also be enabled using the <literal>LANGUAGE</literal> pragma,
52 thus <literal>{-# LANGUAGE TemplateHaskell #-}</literal> (see <xref linkend="language-pragma"/>). </para>
54 </itemizedlist></para>
56 <para>The flag <option>-fglasgow-exts</option>
57 <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
58 is equivalent to enabling the following extensions:
59 <option>-XPrintExplicitForalls</option>,
60 <option>-XForeignFunctionInterface</option>,
61 <option>-XUnliftedFFITypes</option>,
62 <option>-XGADTs</option>,
63 <option>-XImplicitParams</option>,
64 <option>-XScopedTypeVariables</option>,
65 <option>-XUnboxedTuples</option>,
66 <option>-XTypeSynonymInstances</option>,
67 <option>-XStandaloneDeriving</option>,
68 <option>-XDeriveDataTypeable</option>,
69 <option>-XFlexibleContexts</option>,
70 <option>-XFlexibleInstances</option>,
71 <option>-XConstrainedClassMethods</option>,
72 <option>-XMultiParamTypeClasses</option>,
73 <option>-XFunctionalDependencies</option>,
74 <option>-XMagicHash</option>,
75 <option>-XPolymorphicComponents</option>,
76 <option>-XExistentialQuantification</option>,
77 <option>-XUnicodeSyntax</option>,
78 <option>-XPostfixOperators</option>,
79 <option>-XPatternGuards</option>,
80 <option>-XLiberalTypeSynonyms</option>,
81 <option>-XRankNTypes</option>,
82 <option>-XImpredicativeTypes</option>,
83 <option>-XTypeOperators</option>,
84 <option>-XRecursiveDo</option>,
85 <option>-XParallelListComp</option>,
86 <option>-XEmptyDataDecls</option>,
87 <option>-XKindSignatures</option>,
88 <option>-XGeneralizedNewtypeDeriving</option>,
89 <option>-XTypeFamilies</option>.
90 Enabling these options is the <emphasis>only</emphasis>
91 effect of <option>-fglasgow-exts</option>.
92 We are trying to move away from this portmanteau flag,
93 and towards enabling features individually.</para>
97 <!-- UNBOXED TYPES AND PRIMITIVE OPERATIONS -->
98 <sect1 id="primitives">
99 <title>Unboxed types and primitive operations</title>
101 <para>GHC is built on a raft of primitive data types and operations;
102 "primitive" in the sense that they cannot be defined in Haskell itself.
103 While you really can use this stuff to write fast code,
104 we generally find it a lot less painful, and more satisfying in the
105 long run, to use higher-level language features and libraries. With
106 any luck, the code you write will be optimised to the efficient
107 unboxed version in any case. And if it isn't, we'd like to know
110 <para>All these primitive data types and operations are exported by the
111 library <literal>GHC.Prim</literal>, for which there is
112 <ulink url="../libraries/base/GHC.Prim.html">detailed online documentation</ulink>.
113 (This documentation is generated from the file <filename>compiler/prelude/primops.txt.pp</filename>.)
116 If you want to mention any of the primitive data types or operations in your
117 program, you must first import <literal>GHC.Prim</literal> to bring them
118 into scope. Many of them have names ending in "#", and to mention such
119 names you need the <option>-XMagicHash</option> extension (<xref linkend="magic-hash"/>).
122 <para>The primops make extensive use of <link linkend="glasgow-unboxed">unboxed types</link>
123 and <link linkend="unboxed-tuples">unboxed tuples</link>, which
124 we briefly summarise here. </para>
126 <sect2 id="glasgow-unboxed">
131 <indexterm><primary>Unboxed types (Glasgow extension)</primary></indexterm>
134 <para>Most types in GHC are <firstterm>boxed</firstterm>, which means
135 that values of that type are represented by a pointer to a heap
136 object. The representation of a Haskell <literal>Int</literal>, for
137 example, is a two-word heap object. An <firstterm>unboxed</firstterm>
138 type, however, is represented by the value itself, no pointers or heap
139 allocation are involved.
143 Unboxed types correspond to the “raw machine” types you
144 would use in C: <literal>Int#</literal> (long int),
145 <literal>Double#</literal> (double), <literal>Addr#</literal>
146 (void *), etc. The <emphasis>primitive operations</emphasis>
147 (PrimOps) on these types are what you might expect; e.g.,
148 <literal>(+#)</literal> is addition on
149 <literal>Int#</literal>s, and is the machine-addition that we all
150 know and love—usually one instruction.
154 Primitive (unboxed) types cannot be defined in Haskell, and are
155 therefore built into the language and compiler. Primitive types are
156 always unlifted; that is, a value of a primitive type cannot be
157 bottom. We use the convention (but it is only a convention)
158 that primitive types, values, and
159 operations have a <literal>#</literal> suffix (see <xref linkend="magic-hash"/>).
160 For some primitive types we have special syntax for literals, also
161 described in the <link linkend="magic-hash">same section</link>.
165 Primitive values are often represented by a simple bit-pattern, such
166 as <literal>Int#</literal>, <literal>Float#</literal>,
167 <literal>Double#</literal>. But this is not necessarily the case:
168 a primitive value might be represented by a pointer to a
169 heap-allocated object. Examples include
170 <literal>Array#</literal>, the type of primitive arrays. A
171 primitive array is heap-allocated because it is too big a value to fit
172 in a register, and would be too expensive to copy around; in a sense,
173 it is accidental that it is represented by a pointer. If a pointer
174 represents a primitive value, then it really does point to that value:
175 no unevaluated thunks, no indirections…nothing can be at the
176 other end of the pointer than the primitive value.
177 A numerically-intensive program using unboxed types can
178 go a <emphasis>lot</emphasis> faster than its “standard”
179 counterpart—we saw a threefold speedup on one example.
183 There are some restrictions on the use of primitive types:
185 <listitem><para>The main restriction
186 is that you can't pass a primitive value to a polymorphic
187 function or store one in a polymorphic data type. This rules out
188 things like <literal>[Int#]</literal> (i.e. lists of primitive
189 integers). The reason for this restriction is that polymorphic
190 arguments and constructor fields are assumed to be pointers: if an
191 unboxed integer is stored in one of these, the garbage collector would
192 attempt to follow it, leading to unpredictable space leaks. Or a
193 <function>seq</function> operation on the polymorphic component may
194 attempt to dereference the pointer, with disastrous results. Even
195 worse, the unboxed value might be larger than a pointer
196 (<literal>Double#</literal> for instance).
199 <listitem><para> You cannot define a newtype whose representation type
200 (the argument type of the data constructor) is an unboxed type. Thus,
206 <listitem><para> You cannot bind a variable with an unboxed type
207 in a <emphasis>top-level</emphasis> binding.
209 <listitem><para> You cannot bind a variable with an unboxed type
210 in a <emphasis>recursive</emphasis> binding.
212 <listitem><para> You may bind unboxed variables in a (non-recursive,
213 non-top-level) pattern binding, but you must make any such pattern-match
214 strict. For example, rather than:
216 data Foo = Foo Int Int#
218 f x = let (Foo a b, w) = ..rhs.. in ..body..
222 data Foo = Foo Int Int#
224 f x = let !(Foo a b, w) = ..rhs.. in ..body..
226 since <literal>b</literal> has type <literal>Int#</literal>.
234 <sect2 id="unboxed-tuples">
235 <title>Unboxed Tuples
239 Unboxed tuples aren't really exported by <literal>GHC.Exts</literal>,
240 they're available by default with <option>-fglasgow-exts</option>. An
241 unboxed tuple looks like this:
253 where <literal>e_1..e_n</literal> are expressions of any
254 type (primitive or non-primitive). The type of an unboxed tuple looks
259 Unboxed tuples are used for functions that need to return multiple
260 values, but they avoid the heap allocation normally associated with
261 using fully-fledged tuples. When an unboxed tuple is returned, the
262 components are put directly into registers or on the stack; the
263 unboxed tuple itself does not have a composite representation. Many
264 of the primitive operations listed in <literal>primops.txt.pp</literal> return unboxed
266 In particular, the <literal>IO</literal> and <literal>ST</literal> monads use unboxed
267 tuples to avoid unnecessary allocation during sequences of operations.
271 There are some pretty stringent restrictions on the use of unboxed tuples:
276 Values of unboxed tuple types are subject to the same restrictions as
277 other unboxed types; i.e. they may not be stored in polymorphic data
278 structures or passed to polymorphic functions.
285 No variable can have an unboxed tuple type, nor may a constructor or function
286 argument have an unboxed tuple type. The following are all illegal:
290 data Foo = Foo (# Int, Int #)
292 f :: (# Int, Int #) -> (# Int, Int #)
295 g :: (# Int, Int #) -> Int
298 h x = let y = (# x,x #) in ...
305 The typical use of unboxed tuples is simply to return multiple values,
306 binding those multiple results with a <literal>case</literal> expression, thus:
308 f x y = (# x+1, y-1 #)
309 g x = case f x x of { (# a, b #) -> a + b }
311 You can have an unboxed tuple in a pattern binding, thus
313 f x = let (# p,q #) = h x in ..body..
315 If the types of <literal>p</literal> and <literal>q</literal> are not unboxed,
316 the resulting binding is lazy like any other Haskell pattern binding. The
317 above example desugars like this:
319 f x = let t = case h x o f{ (# p,q #) -> (p,q)
324 Indeed, the bindings can even be recursive.
331 <!-- ====================== SYNTACTIC EXTENSIONS ======================= -->
333 <sect1 id="syntax-extns">
334 <title>Syntactic extensions</title>
336 <sect2 id="unicode-syntax">
337 <title>Unicode syntax</title>
339 extension <option>-XUnicodeSyntax</option><indexterm><primary><option>-XUnicodeSyntax</option></primary></indexterm>
340 enables Unicode characters to be used to stand for certain ASCII
341 character sequences. The following alternatives are provided:</para>
344 <tgroup cols="2" align="left" colsep="1" rowsep="1">
348 <entry>Unicode alternative</entry>
349 <entry>Code point</entry>
355 <entry><literal>::</literal></entry>
356 <entry>::</entry> <!-- no special char, apparently -->
357 <entry>0x2237</entry>
358 <entry>PROPORTION</entry>
363 <entry><literal>=></literal></entry>
364 <entry>⇒</entry>
365 <entry>0x21D2</entry>
366 <entry>RIGHTWARDS DOUBLE ARROW</entry>
371 <entry><literal>forall</literal></entry>
372 <entry>∀</entry>
373 <entry>0x2200</entry>
374 <entry>FOR ALL</entry>
379 <entry><literal>-></literal></entry>
380 <entry>→</entry>
381 <entry>0x2192</entry>
382 <entry>RIGHTWARDS ARROW</entry>
387 <entry><literal><-</literal></entry>
388 <entry>←</entry>
389 <entry>0x2190</entry>
390 <entry>LEFTWARDS ARROW</entry>
396 <entry>…</entry>
397 <entry>0x22EF</entry>
398 <entry>MIDLINE HORIZONTAL ELLIPSIS</entry>
405 <sect2 id="magic-hash">
406 <title>The magic hash</title>
407 <para>The language extension <option>-XMagicHash</option> allows "#" as a
408 postfix modifier to identifiers. Thus, "x#" is a valid variable, and "T#" is
409 a valid type constructor or data constructor.</para>
411 <para>The hash sign does not change sematics at all. We tend to use variable
412 names ending in "#" for unboxed values or types (e.g. <literal>Int#</literal>),
413 but there is no requirement to do so; they are just plain ordinary variables.
414 Nor does the <option>-XMagicHash</option> extension bring anything into scope.
415 For example, to bring <literal>Int#</literal> into scope you must
416 import <literal>GHC.Prim</literal> (see <xref linkend="primitives"/>);
417 the <option>-XMagicHash</option> extension
418 then allows you to <emphasis>refer</emphasis> to the <literal>Int#</literal>
419 that is now in scope.</para>
420 <para> The <option>-XMagicHash</option> also enables some new forms of literals (see <xref linkend="glasgow-unboxed"/>):
422 <listitem><para> <literal>'x'#</literal> has type <literal>Char#</literal></para> </listitem>
423 <listitem><para> <literal>"foo"#</literal> has type <literal>Addr#</literal></para> </listitem>
424 <listitem><para> <literal>3#</literal> has type <literal>Int#</literal>. In general,
425 any Haskell 98 integer lexeme followed by a <literal>#</literal> is an <literal>Int#</literal> literal, e.g.
426 <literal>-0x3A#</literal> as well as <literal>32#</literal></para>.</listitem>
427 <listitem><para> <literal>3##</literal> has type <literal>Word#</literal>. In general,
428 any non-negative Haskell 98 integer lexeme followed by <literal>##</literal>
429 is a <literal>Word#</literal>. </para> </listitem>
430 <listitem><para> <literal>3.2#</literal> has type <literal>Float#</literal>.</para> </listitem>
431 <listitem><para> <literal>3.2##</literal> has type <literal>Double#</literal></para> </listitem>
436 <sect2 id="new-qualified-operators">
437 <title>New qualified operator syntax</title>
439 <para>A new syntax for referencing qualified operators is
440 planned to be introduced by Haskell', and is enabled in GHC
442 the <option>-XNewQualifiedOperators</option><indexterm><primary><option>-XNewQualifiedOperators</option></primary></indexterm>
443 option. In the new syntax, the prefix form of a qualified
445 written <literal><replaceable>module</replaceable>.(<replaceable>symbol</replaceable>)</literal>
446 (in Haskell 98 this would
447 be <literal>(<replaceable>module</replaceable>.<replaceable>symbol</replaceable>)</literal>),
448 and the infix form is
449 written <literal>`<replaceable>module</replaceable>.(<replaceable>symbol</replaceable>)`</literal>
450 (in Haskell 98 this would
451 be <literal>`<replaceable>module</replaceable>.<replaceable>symbol</replaceable>`</literal>.
454 add x y = Prelude.(+) x y
455 subtract y = (`Prelude.(-)` y)
457 The new form of qualified operators is intended to regularise
458 the syntax by eliminating odd cases
459 like <literal>Prelude..</literal>. For example,
460 when <literal>NewQualifiedOperators</literal> is on, it is possible to
461 write the enumerated sequence <literal>[Monday..]</literal>
462 without spaces, whereas in Haskell 98 this would be a
463 reference to the operator ‘<literal>.</literal>‘
464 from module <literal>Monday</literal>.</para>
466 <para>When <option>-XNewQualifiedOperators</option> is on, the old Haskell
467 98 syntax for qualified operators is not accepted, so this
468 option may cause existing Haskell 98 code to break.</para>
473 <!-- ====================== HIERARCHICAL MODULES ======================= -->
476 <sect2 id="hierarchical-modules">
477 <title>Hierarchical Modules</title>
479 <para>GHC supports a small extension to the syntax of module
480 names: a module name is allowed to contain a dot
481 <literal>‘.’</literal>. This is also known as the
482 “hierarchical module namespace” extension, because
483 it extends the normally flat Haskell module namespace into a
484 more flexible hierarchy of modules.</para>
486 <para>This extension has very little impact on the language
487 itself; modules names are <emphasis>always</emphasis> fully
488 qualified, so you can just think of the fully qualified module
489 name as <quote>the module name</quote>. In particular, this
490 means that the full module name must be given after the
491 <literal>module</literal> keyword at the beginning of the
492 module; for example, the module <literal>A.B.C</literal> must
495 <programlisting>module A.B.C</programlisting>
498 <para>It is a common strategy to use the <literal>as</literal>
499 keyword to save some typing when using qualified names with
500 hierarchical modules. For example:</para>
503 import qualified Control.Monad.ST.Strict as ST
506 <para>For details on how GHC searches for source and interface
507 files in the presence of hierarchical modules, see <xref
508 linkend="search-path"/>.</para>
510 <para>GHC comes with a large collection of libraries arranged
511 hierarchically; see the accompanying <ulink
512 url="../libraries/index.html">library
513 documentation</ulink>. More libraries to install are available
515 url="http://hackage.haskell.org/packages/hackage.html">HackageDB</ulink>.</para>
518 <!-- ====================== PATTERN GUARDS ======================= -->
520 <sect2 id="pattern-guards">
521 <title>Pattern guards</title>
524 <indexterm><primary>Pattern guards (Glasgow extension)</primary></indexterm>
525 The discussion that follows is an abbreviated version of Simon Peyton Jones's original <ulink url="http://research.microsoft.com/~simonpj/Haskell/guards.html">proposal</ulink>. (Note that the proposal was written before pattern guards were implemented, so refers to them as unimplemented.)
529 Suppose we have an abstract data type of finite maps, with a
533 lookup :: FiniteMap -> Int -> Maybe Int
536 The lookup returns <function>Nothing</function> if the supplied key is not in the domain of the mapping, and <function>(Just v)</function> otherwise,
537 where <varname>v</varname> is the value that the key maps to. Now consider the following definition:
541 clunky env var1 var2 | ok1 && ok2 = val1 + val2
542 | otherwise = var1 + var2
553 The auxiliary functions are
557 maybeToBool :: Maybe a -> Bool
558 maybeToBool (Just x) = True
559 maybeToBool Nothing = False
561 expectJust :: Maybe a -> a
562 expectJust (Just x) = x
563 expectJust Nothing = error "Unexpected Nothing"
567 What is <function>clunky</function> doing? The guard <literal>ok1 &&
568 ok2</literal> checks that both lookups succeed, using
569 <function>maybeToBool</function> to convert the <function>Maybe</function>
570 types to booleans. The (lazily evaluated) <function>expectJust</function>
571 calls extract the values from the results of the lookups, and binds the
572 returned values to <varname>val1</varname> and <varname>val2</varname>
573 respectively. If either lookup fails, then clunky takes the
574 <literal>otherwise</literal> case and returns the sum of its arguments.
578 This is certainly legal Haskell, but it is a tremendously verbose and
579 un-obvious way to achieve the desired effect. Arguably, a more direct way
580 to write clunky would be to use case expressions:
584 clunky env var1 var2 = case lookup env var1 of
586 Just val1 -> case lookup env var2 of
588 Just val2 -> val1 + val2
594 This is a bit shorter, but hardly better. Of course, we can rewrite any set
595 of pattern-matching, guarded equations as case expressions; that is
596 precisely what the compiler does when compiling equations! The reason that
597 Haskell provides guarded equations is because they allow us to write down
598 the cases we want to consider, one at a time, independently of each other.
599 This structure is hidden in the case version. Two of the right-hand sides
600 are really the same (<function>fail</function>), and the whole expression
601 tends to become more and more indented.
605 Here is how I would write clunky:
610 | Just val1 <- lookup env var1
611 , Just val2 <- lookup env var2
613 ...other equations for clunky...
617 The semantics should be clear enough. The qualifiers are matched in order.
618 For a <literal><-</literal> qualifier, which I call a pattern guard, the
619 right hand side is evaluated and matched against the pattern on the left.
620 If the match fails then the whole guard fails and the next equation is
621 tried. If it succeeds, then the appropriate binding takes place, and the
622 next qualifier is matched, in the augmented environment. Unlike list
623 comprehensions, however, the type of the expression to the right of the
624 <literal><-</literal> is the same as the type of the pattern to its
625 left. The bindings introduced by pattern guards scope over all the
626 remaining guard qualifiers, and over the right hand side of the equation.
630 Just as with list comprehensions, boolean expressions can be freely mixed
631 with among the pattern guards. For example:
642 Haskell's current guards therefore emerge as a special case, in which the
643 qualifier list has just one element, a boolean expression.
647 <!-- ===================== View patterns =================== -->
649 <sect2 id="view-patterns">
654 View patterns are enabled by the flag <literal>-XViewPatterns</literal>.
655 More information and examples of view patterns can be found on the
656 <ulink url="http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns">Wiki
661 View patterns are somewhat like pattern guards that can be nested inside
662 of other patterns. They are a convenient way of pattern-matching
663 against values of abstract types. For example, in a programming language
664 implementation, we might represent the syntax of the types of the
673 view :: Type -> TypeView
675 -- additional operations for constructing Typ's ...
678 The representation of Typ is held abstract, permitting implementations
679 to use a fancy representation (e.g., hash-consing to manage sharing).
681 Without view patterns, using this signature a little inconvenient:
683 size :: Typ -> Integer
684 size t = case view t of
686 Arrow t1 t2 -> size t1 + size t2
689 It is necessary to iterate the case, rather than using an equational
690 function definition. And the situation is even worse when the matching
691 against <literal>t</literal> is buried deep inside another pattern.
695 View patterns permit calling the view function inside the pattern and
696 matching against the result:
698 size (view -> Unit) = 1
699 size (view -> Arrow t1 t2) = size t1 + size t2
702 That is, we add a new form of pattern, written
703 <replaceable>expression</replaceable> <literal>-></literal>
704 <replaceable>pattern</replaceable> that means "apply the expression to
705 whatever we're trying to match against, and then match the result of
706 that application against the pattern". The expression can be any Haskell
707 expression of function type, and view patterns can be used wherever
712 The semantics of a pattern <literal>(</literal>
713 <replaceable>exp</replaceable> <literal>-></literal>
714 <replaceable>pat</replaceable> <literal>)</literal> are as follows:
720 <para>The variables bound by the view pattern are the variables bound by
721 <replaceable>pat</replaceable>.
725 Any variables in <replaceable>exp</replaceable> are bound occurrences,
726 but variables bound "to the left" in a pattern are in scope. This
727 feature permits, for example, one argument to a function to be used in
728 the view of another argument. For example, the function
729 <literal>clunky</literal> from <xref linkend="pattern-guards" /> can be
730 written using view patterns as follows:
733 clunky env (lookup env -> Just val1) (lookup env -> Just val2) = val1 + val2
734 ...other equations for clunky...
739 More precisely, the scoping rules are:
743 In a single pattern, variables bound by patterns to the left of a view
744 pattern expression are in scope. For example:
746 example :: Maybe ((String -> Integer,Integer), String) -> Bool
747 example Just ((f,_), f -> 4) = True
750 Additionally, in function definitions, variables bound by matching earlier curried
751 arguments may be used in view pattern expressions in later arguments:
753 example :: (String -> Integer) -> String -> Bool
754 example f (f -> 4) = True
756 That is, the scoping is the same as it would be if the curried arguments
757 were collected into a tuple.
763 In mutually recursive bindings, such as <literal>let</literal>,
764 <literal>where</literal>, or the top level, view patterns in one
765 declaration may not mention variables bound by other declarations. That
766 is, each declaration must be self-contained. For example, the following
767 program is not allowed:
774 restriction in the future; the only cost is that type checking patterns
775 would get a little more complicated.)
785 <listitem><para> Typing: If <replaceable>exp</replaceable> has type
786 <replaceable>T1</replaceable> <literal>-></literal>
787 <replaceable>T2</replaceable> and <replaceable>pat</replaceable> matches
788 a <replaceable>T2</replaceable>, then the whole view pattern matches a
789 <replaceable>T1</replaceable>.
792 <listitem><para> Matching: To the equations in Section 3.17.3 of the
793 <ulink url="http://www.haskell.org/onlinereport/">Haskell 98
794 Report</ulink>, add the following:
796 case v of { (e -> p) -> e1 ; _ -> e2 }
798 case (e v) of { p -> e1 ; _ -> e2 }
800 That is, to match a variable <replaceable>v</replaceable> against a pattern
801 <literal>(</literal> <replaceable>exp</replaceable>
802 <literal>-></literal> <replaceable>pat</replaceable>
803 <literal>)</literal>, evaluate <literal>(</literal>
804 <replaceable>exp</replaceable> <replaceable> v</replaceable>
805 <literal>)</literal> and match the result against
806 <replaceable>pat</replaceable>.
809 <listitem><para> Efficiency: When the same view function is applied in
810 multiple branches of a function definition or a case expression (e.g.,
811 in <literal>size</literal> above), GHC makes an attempt to collect these
812 applications into a single nested case expression, so that the view
813 function is only applied once. Pattern compilation in GHC follows the
814 matrix algorithm described in Chapter 4 of <ulink
815 url="http://research.microsoft.com/~simonpj/Papers/slpj-book-1987/">The
816 Implementation of Functional Programming Languages</ulink>. When the
817 top rows of the first column of a matrix are all view patterns with the
818 "same" expression, these patterns are transformed into a single nested
819 case. This includes, for example, adjacent view patterns that line up
822 f ((view -> A, p1), p2) = e1
823 f ((view -> B, p3), p4) = e2
827 <para> The current notion of when two view pattern expressions are "the
828 same" is very restricted: it is not even full syntactic equality.
829 However, it does include variables, literals, applications, and tuples;
830 e.g., two instances of <literal>view ("hi", "there")</literal> will be
831 collected. However, the current implementation does not compare up to
832 alpha-equivalence, so two instances of <literal>(x, view x ->
833 y)</literal> will not be coalesced.
843 <!-- ===================== Recursive do-notation =================== -->
845 <sect2 id="mdo-notation">
846 <title>The recursive do-notation
849 <para> The recursive do-notation (also known as mdo-notation) is implemented as described in
850 <ulink url="http://citeseer.ist.psu.edu/erk02recursive.html">A recursive do for Haskell</ulink>,
851 by Levent Erkok, John Launchbury,
852 Haskell Workshop 2002, pages: 29-37. Pittsburgh, Pennsylvania.
853 This paper is essential reading for anyone making non-trivial use of mdo-notation,
854 and we do not repeat it here.
857 The do-notation of Haskell does not allow <emphasis>recursive bindings</emphasis>,
858 that is, the variables bound in a do-expression are visible only in the textually following
859 code block. Compare this to a let-expression, where bound variables are visible in the entire binding
860 group. It turns out that several applications can benefit from recursive bindings in
861 the do-notation, and this extension provides the necessary syntactic support.
864 Here is a simple (yet contrived) example:
867 import Control.Monad.Fix
869 justOnes = mdo xs <- Just (1:xs)
873 As you can guess <literal>justOnes</literal> will evaluate to <literal>Just [1,1,1,...</literal>.
877 The Control.Monad.Fix library introduces the <literal>MonadFix</literal> class. It's definition is:
880 class Monad m => MonadFix m where
881 mfix :: (a -> m a) -> m a
884 The function <literal>mfix</literal>
885 dictates how the required recursion operation should be performed. For example,
886 <literal>justOnes</literal> desugars as follows:
888 justOnes = mfix (\xs' -> do { xs <- Just (1:xs'); return xs }
890 For full details of the way in which mdo is typechecked and desugared, see
891 the paper <ulink url="http://citeseer.ist.psu.edu/erk02recursive.html">A recursive do for Haskell</ulink>.
892 In particular, GHC implements the segmentation technique described in Section 3.2 of the paper.
895 If recursive bindings are required for a monad,
896 then that monad must be declared an instance of the <literal>MonadFix</literal> class.
897 The following instances of <literal>MonadFix</literal> are automatically provided: List, Maybe, IO.
898 Furthermore, the Control.Monad.ST and Control.Monad.ST.Lazy modules provide the instances of the MonadFix class
899 for Haskell's internal state monad (strict and lazy, respectively).
902 Here are some important points in using the recursive-do notation:
905 The recursive version of the do-notation uses the keyword <literal>mdo</literal> (rather
906 than <literal>do</literal>).
910 It is enabled with the flag <literal>-XRecursiveDo</literal>, which is in turn implied by
911 <literal>-fglasgow-exts</literal>.
915 Unlike ordinary do-notation, but like <literal>let</literal> and <literal>where</literal> bindings,
916 name shadowing is not allowed; that is, all the names bound in a single <literal>mdo</literal> must
917 be distinct (Section 3.3 of the paper).
921 Variables bound by a <literal>let</literal> statement in an <literal>mdo</literal>
922 are monomorphic in the <literal>mdo</literal> (Section 3.1 of the paper). However
923 GHC breaks the <literal>mdo</literal> into segments to enhance polymorphism,
924 and improve termination (Section 3.2 of the paper).
930 Historical note: The old implementation of the mdo-notation (and most
931 of the existing documents) used the name
932 <literal>MonadRec</literal> for the class and the corresponding library.
933 This name is not supported by GHC.
939 <!-- ===================== PARALLEL LIST COMPREHENSIONS =================== -->
941 <sect2 id="parallel-list-comprehensions">
942 <title>Parallel List Comprehensions</title>
943 <indexterm><primary>list comprehensions</primary><secondary>parallel</secondary>
945 <indexterm><primary>parallel list comprehensions</primary>
948 <para>Parallel list comprehensions are a natural extension to list
949 comprehensions. List comprehensions can be thought of as a nice
950 syntax for writing maps and filters. Parallel comprehensions
951 extend this to include the zipWith family.</para>
953 <para>A parallel list comprehension has multiple independent
954 branches of qualifier lists, each separated by a `|' symbol. For
955 example, the following zips together two lists:</para>
958 [ (x, y) | x <- xs | y <- ys ]
961 <para>The behavior of parallel list comprehensions follows that of
962 zip, in that the resulting list will have the same length as the
963 shortest branch.</para>
965 <para>We can define parallel list comprehensions by translation to
966 regular comprehensions. Here's the basic idea:</para>
968 <para>Given a parallel comprehension of the form: </para>
971 [ e | p1 <- e11, p2 <- e12, ...
972 | q1 <- e21, q2 <- e22, ...
977 <para>This will be translated to: </para>
980 [ e | ((p1,p2), (q1,q2), ...) <- zipN [(p1,p2) | p1 <- e11, p2 <- e12, ...]
981 [(q1,q2) | q1 <- e21, q2 <- e22, ...]
986 <para>where `zipN' is the appropriate zip for the given number of
991 <!-- ===================== TRANSFORM LIST COMPREHENSIONS =================== -->
993 <sect2 id="generalised-list-comprehensions">
994 <title>Generalised (SQL-Like) List Comprehensions</title>
995 <indexterm><primary>list comprehensions</primary><secondary>generalised</secondary>
997 <indexterm><primary>extended list comprehensions</primary>
999 <indexterm><primary>group</primary></indexterm>
1000 <indexterm><primary>sql</primary></indexterm>
1003 <para>Generalised list comprehensions are a further enhancement to the
1004 list comprehension syntatic sugar to allow operations such as sorting
1005 and grouping which are familiar from SQL. They are fully described in the
1006 paper <ulink url="http://research.microsoft.com/~simonpj/papers/list-comp">
1007 Comprehensive comprehensions: comprehensions with "order by" and "group by"</ulink>,
1008 except that the syntax we use differs slightly from the paper.</para>
1009 <para>The extension is enabled with the flag <option>-XTransformListComp</option>.</para>
1010 <para>Here is an example:
1012 employees = [ ("Simon", "MS", 80)
1013 , ("Erik", "MS", 100)
1014 , ("Phil", "Ed", 40)
1015 , ("Gordon", "Ed", 45)
1016 , ("Paul", "Yale", 60)]
1018 output = [ (the dept, sum salary)
1019 | (name, dept, salary) <- employees
1020 , then group by dept
1021 , then sortWith by (sum salary)
1024 In this example, the list <literal>output</literal> would take on
1028 [("Yale", 60), ("Ed", 85), ("MS", 180)]
1031 <para>There are three new keywords: <literal>group</literal>, <literal>by</literal>, and <literal>using</literal>.
1032 (The function <literal>sortWith</literal> is not a keyword; it is an ordinary
1033 function that is exported by <literal>GHC.Exts</literal>.)</para>
1035 <para>There are five new forms of comprehension qualifier,
1036 all introduced by the (existing) keyword <literal>then</literal>:
1044 This statement requires that <literal>f</literal> have the type <literal>
1045 forall a. [a] -> [a]</literal>. You can see an example of it's use in the
1046 motivating example, as this form is used to apply <literal>take 5</literal>.
1057 This form is similar to the previous one, but allows you to create a function
1058 which will be passed as the first argument to f. As a consequence f must have
1059 the type <literal>forall a. (a -> t) -> [a] -> [a]</literal>. As you can see
1060 from the type, this function lets f "project out" some information
1061 from the elements of the list it is transforming.</para>
1063 <para>An example is shown in the opening example, where <literal>sortWith</literal>
1064 is supplied with a function that lets it find out the <literal>sum salary</literal>
1065 for any item in the list comprehension it transforms.</para>
1073 then group by e using f
1076 <para>This is the most general of the grouping-type statements. In this form,
1077 f is required to have type <literal>forall a. (a -> t) -> [a] -> [[a]]</literal>.
1078 As with the <literal>then f by e</literal> case above, the first argument
1079 is a function supplied to f by the compiler which lets it compute e on every
1080 element of the list being transformed. However, unlike the non-grouping case,
1081 f additionally partitions the list into a number of sublists: this means that
1082 at every point after this statement, binders occurring before it in the comprehension
1083 refer to <emphasis>lists</emphasis> of possible values, not single values. To help understand
1084 this, let's look at an example:</para>
1087 -- This works similarly to groupWith in GHC.Exts, but doesn't sort its input first
1088 groupRuns :: Eq b => (a -> b) -> [a] -> [[a]]
1089 groupRuns f = groupBy (\x y -> f x == f y)
1091 output = [ (the x, y)
1092 | x <- ([1..3] ++ [1..2])
1094 , then group by x using groupRuns ]
1097 <para>This results in the variable <literal>output</literal> taking on the value below:</para>
1100 [(1, [4, 5, 6]), (2, [4, 5, 6]), (3, [4, 5, 6]), (1, [4, 5, 6]), (2, [4, 5, 6])]
1103 <para>Note that we have used the <literal>the</literal> function to change the type
1104 of x from a list to its original numeric type. The variable y, in contrast, is left
1105 unchanged from the list form introduced by the grouping.</para>
1115 <para>This form of grouping is essentially the same as the one described above. However,
1116 since no function to use for the grouping has been supplied it will fall back on the
1117 <literal>groupWith</literal> function defined in
1118 <ulink url="../libraries/base/GHC-Exts.html"><literal>GHC.Exts</literal></ulink>. This
1119 is the form of the group statement that we made use of in the opening example.</para>
1130 <para>With this form of the group statement, f is required to simply have the type
1131 <literal>forall a. [a] -> [[a]]</literal>, which will be used to group up the
1132 comprehension so far directly. An example of this form is as follows:</para>
1138 , then group using inits]
1141 <para>This will yield a list containing every prefix of the word "hello" written out 5 times:</para>
1144 ["","h","he","hel","hell","hello","helloh","hellohe","hellohel","hellohell","hellohello","hellohelloh",...]
1152 <!-- ===================== REBINDABLE SYNTAX =================== -->
1154 <sect2 id="rebindable-syntax">
1155 <title>Rebindable syntax and the implicit Prelude import</title>
1157 <para><indexterm><primary>-XNoImplicitPrelude
1158 option</primary></indexterm> GHC normally imports
1159 <filename>Prelude.hi</filename> files for you. If you'd
1160 rather it didn't, then give it a
1161 <option>-XNoImplicitPrelude</option> option. The idea is
1162 that you can then import a Prelude of your own. (But don't
1163 call it <literal>Prelude</literal>; the Haskell module
1164 namespace is flat, and you must not conflict with any
1165 Prelude module.)</para>
1167 <para>Suppose you are importing a Prelude of your own
1168 in order to define your own numeric class
1169 hierarchy. It completely defeats that purpose if the
1170 literal "1" means "<literal>Prelude.fromInteger
1171 1</literal>", which is what the Haskell Report specifies.
1172 So the <option>-XNoImplicitPrelude</option>
1173 flag <emphasis>also</emphasis> causes
1174 the following pieces of built-in syntax to refer to
1175 <emphasis>whatever is in scope</emphasis>, not the Prelude
1179 <para>An integer literal <literal>368</literal> means
1180 "<literal>fromInteger (368::Integer)</literal>", rather than
1181 "<literal>Prelude.fromInteger (368::Integer)</literal>".
1184 <listitem><para>Fractional literals are handed in just the same way,
1185 except that the translation is
1186 <literal>fromRational (3.68::Rational)</literal>.
1189 <listitem><para>The equality test in an overloaded numeric pattern
1190 uses whatever <literal>(==)</literal> is in scope.
1193 <listitem><para>The subtraction operation, and the
1194 greater-than-or-equal test, in <literal>n+k</literal> patterns
1195 use whatever <literal>(-)</literal> and <literal>(>=)</literal> are in scope.
1199 <para>Negation (e.g. "<literal>- (f x)</literal>")
1200 means "<literal>negate (f x)</literal>", both in numeric
1201 patterns, and expressions.
1205 <para>"Do" notation is translated using whatever
1206 functions <literal>(>>=)</literal>,
1207 <literal>(>>)</literal>, and <literal>fail</literal>,
1208 are in scope (not the Prelude
1209 versions). List comprehensions, mdo (<xref linkend="mdo-notation"/>), and parallel array
1210 comprehensions, are unaffected. </para></listitem>
1214 notation (see <xref linkend="arrow-notation"/>)
1215 uses whatever <literal>arr</literal>,
1216 <literal>(>>>)</literal>, <literal>first</literal>,
1217 <literal>app</literal>, <literal>(|||)</literal> and
1218 <literal>loop</literal> functions are in scope. But unlike the
1219 other constructs, the types of these functions must match the
1220 Prelude types very closely. Details are in flux; if you want
1224 In all cases (apart from arrow notation), the static semantics should be that of the desugared form,
1225 even if that is a little unexpected. For example, the
1226 static semantics of the literal <literal>368</literal>
1227 is exactly that of <literal>fromInteger (368::Integer)</literal>; it's fine for
1228 <literal>fromInteger</literal> to have any of the types:
1230 fromInteger :: Integer -> Integer
1231 fromInteger :: forall a. Foo a => Integer -> a
1232 fromInteger :: Num a => a -> Integer
1233 fromInteger :: Integer -> Bool -> Bool
1237 <para>Be warned: this is an experimental facility, with
1238 fewer checks than usual. Use <literal>-dcore-lint</literal>
1239 to typecheck the desugared program. If Core Lint is happy
1240 you should be all right.</para>
1244 <sect2 id="postfix-operators">
1245 <title>Postfix operators</title>
1248 The <option>-XPostfixOperators</option> flag enables a small
1249 extension to the syntax of left operator sections, which allows you to
1250 define postfix operators. The extension is this: the left section
1254 is equivalent (from the point of view of both type checking and execution) to the expression
1258 (for any expression <literal>e</literal> and operator <literal>(!)</literal>.
1259 The strict Haskell 98 interpretation is that the section is equivalent to
1263 That is, the operator must be a function of two arguments. GHC allows it to
1264 take only one argument, and that in turn allows you to write the function
1267 <para>The extension does not extend to the left-hand side of function
1268 definitions; you must define such a function in prefix form.</para>
1272 <sect2 id="disambiguate-fields">
1273 <title>Record field disambiguation</title>
1275 In record construction and record pattern matching
1276 it is entirely unambiguous which field is referred to, even if there are two different
1277 data types in scope with a common field name. For example:
1280 data S = MkS { x :: Int, y :: Bool }
1285 data T = MkT { x :: Int }
1287 ok1 (MkS { x = n }) = n+1 -- Unambiguous
1289 ok2 n = MkT { x = n+1 } -- Unambiguous
1291 bad1 k = k { x = 3 } -- Ambiguous
1292 bad2 k = x k -- Ambiguous
1294 Even though there are two <literal>x</literal>'s in scope,
1295 it is clear that the <literal>x</literal> in the pattern in the
1296 definition of <literal>ok1</literal> can only mean the field
1297 <literal>x</literal> from type <literal>S</literal>. Similarly for
1298 the function <literal>ok2</literal>. However, in the record update
1299 in <literal>bad1</literal> and the record selection in <literal>bad2</literal>
1300 it is not clear which of the two types is intended.
1303 Haskell 98 regards all four as ambiguous, but with the
1304 <option>-XDisambiguateRecordFields</option> flag, GHC will accept
1305 the former two. The rules are precisely the same as those for instance
1306 declarations in Haskell 98, where the method names on the left-hand side
1307 of the method bindings in an instance declaration refer unambiguously
1308 to the method of that class (provided they are in scope at all), even
1309 if there are other variables in scope with the same name.
1310 This reduces the clutter of qualified names when you import two
1311 records from different modules that use the same field name.
1315 <!-- ===================== Record puns =================== -->
1317 <sect2 id="record-puns">
1322 Record puns are enabled by the flag <literal>-XNamedFieldPuns</literal>.
1326 When using records, it is common to write a pattern that binds a
1327 variable with the same name as a record field, such as:
1330 data C = C {a :: Int}
1336 Record punning permits the variable name to be elided, so one can simply
1343 to mean the same pattern as above. That is, in a record pattern, the
1344 pattern <literal>a</literal> expands into the pattern <literal>a =
1345 a</literal> for the same name <literal>a</literal>.
1349 Note that puns and other patterns can be mixed in the same record:
1351 data C = C {a :: Int, b :: Int}
1352 f (C {a, b = 4}) = a
1354 and that puns can be used wherever record patterns occur (e.g. in
1355 <literal>let</literal> bindings or at the top-level).
1359 Record punning can also be used in an expression, writing, for example,
1365 let a = 1 in C {a = a}
1368 Note that this expansion is purely syntactic, so the record pun
1369 expression refers to the nearest enclosing variable that is spelled the
1370 same as the field name.
1375 <!-- ===================== Record wildcards =================== -->
1377 <sect2 id="record-wildcards">
1378 <title>Record wildcards
1382 Record wildcards are enabled by the flag <literal>-XRecordWildCards</literal>.
1386 For records with many fields, it can be tiresome to write out each field
1387 individually in a record pattern, as in
1389 data C = C {a :: Int, b :: Int, c :: Int, d :: Int}
1390 f (C {a = 1, b = b, c = c, d = d}) = b + c + d
1395 Record wildcard syntax permits a (<literal>..</literal>) in a record
1396 pattern, where each elided field <literal>f</literal> is replaced by the
1397 pattern <literal>f = f</literal>. For example, the above pattern can be
1400 f (C {a = 1, ..}) = b + c + d
1405 Note that wildcards can be mixed with other patterns, including puns
1406 (<xref linkend="record-puns"/>); for example, in a pattern <literal>C {a
1407 = 1, b, ..})</literal>. Additionally, record wildcards can be used
1408 wherever record patterns occur, including in <literal>let</literal>
1409 bindings and at the top-level. For example, the top-level binding
1413 defines <literal>b</literal>, <literal>c</literal>, and
1414 <literal>d</literal>.
1418 Record wildcards can also be used in expressions, writing, for example,
1421 let {a = 1; b = 2; c = 3; d = 4} in C {..}
1427 let {a = 1; b = 2; c = 3; d = 4} in C {a=a, b=b, c=c, d=d}
1430 Note that this expansion is purely syntactic, so the record wildcard
1431 expression refers to the nearest enclosing variables that are spelled
1432 the same as the omitted field names.
1437 <!-- ===================== Local fixity declarations =================== -->
1439 <sect2 id="local-fixity-declarations">
1440 <title>Local Fixity Declarations
1443 <para>A careful reading of the Haskell 98 Report reveals that fixity
1444 declarations (<literal>infix</literal>, <literal>infixl</literal>, and
1445 <literal>infixr</literal>) are permitted to appear inside local bindings
1446 such those introduced by <literal>let</literal> and
1447 <literal>where</literal>. However, the Haskell Report does not specify
1448 the semantics of such bindings very precisely.
1451 <para>In GHC, a fixity declaration may accompany a local binding:
1458 and the fixity declaration applies wherever the binding is in scope.
1459 For example, in a <literal>let</literal>, it applies in the right-hand
1460 sides of other <literal>let</literal>-bindings and the body of the
1461 <literal>let</literal>C. Or, in recursive <literal>do</literal>
1462 expressions (<xref linkend="mdo-notation"/>), the local fixity
1463 declarations of a <literal>let</literal> statement scope over other
1464 statements in the group, just as the bound name does.
1468 Moreover, a local fixity declaration *must* accompany a local binding of
1469 that name: it is not possible to revise the fixity of name bound
1472 let infixr 9 $ in ...
1475 Because local fixity declarations are technically Haskell 98, no flag is
1476 necessary to enable them.
1480 <sect2 id="package-imports">
1481 <title>Package-qualified imports</title>
1483 <para>With the <option>-XPackageImports</option> flag, GHC allows
1484 import declarations to be qualified by the package name that the
1485 module is intended to be imported from. For example:</para>
1488 import "network" Network.Socket
1491 <para>would import the module <literal>Network.Socket</literal> from
1492 the package <literal>network</literal> (any version). This may
1493 be used to disambiguate an import when the same module is
1494 available from multiple packages, or is present in both the
1495 current package being built and an external package.</para>
1497 <para>Note: you probably don't need to use this feature, it was
1498 added mainly so that we can build backwards-compatible versions of
1499 packages when APIs change. It can lead to fragile dependencies in
1500 the common case: modules occasionally move from one package to
1501 another, rendering any package-qualified imports broken.</para>
1504 <sect2 id="syntax-stolen">
1505 <title>Summary of stolen syntax</title>
1507 <para>Turning on an option that enables special syntax
1508 <emphasis>might</emphasis> cause working Haskell 98 code to fail
1509 to compile, perhaps because it uses a variable name which has
1510 become a reserved word. This section lists the syntax that is
1511 "stolen" by language extensions.
1513 notation and nonterminal names from the Haskell 98 lexical syntax
1514 (see the Haskell 98 Report).
1515 We only list syntax changes here that might affect
1516 existing working programs (i.e. "stolen" syntax). Many of these
1517 extensions will also enable new context-free syntax, but in all
1518 cases programs written to use the new syntax would not be
1519 compilable without the option enabled.</para>
1521 <para>There are two classes of special
1526 <para>New reserved words and symbols: character sequences
1527 which are no longer available for use as identifiers in the
1531 <para>Other special syntax: sequences of characters that have
1532 a different meaning when this particular option is turned
1537 The following syntax is stolen:
1542 <literal>forall</literal>
1543 <indexterm><primary><literal>forall</literal></primary></indexterm>
1546 Stolen (in types) by: <option>-XScopedTypeVariables</option>,
1547 <option>-XLiberalTypeSynonyms</option>,
1548 <option>-XRank2Types</option>,
1549 <option>-XRankNTypes</option>,
1550 <option>-XPolymorphicComponents</option>,
1551 <option>-XExistentialQuantification</option>
1557 <literal>mdo</literal>
1558 <indexterm><primary><literal>mdo</literal></primary></indexterm>
1561 Stolen by: <option>-XRecursiveDo</option>,
1567 <literal>foreign</literal>
1568 <indexterm><primary><literal>foreign</literal></primary></indexterm>
1571 Stolen by: <option>-XForeignFunctionInterface</option>,
1577 <literal>rec</literal>,
1578 <literal>proc</literal>, <literal>-<</literal>,
1579 <literal>>-</literal>, <literal>-<<</literal>,
1580 <literal>>>-</literal>, and <literal>(|</literal>,
1581 <literal>|)</literal> brackets
1582 <indexterm><primary><literal>proc</literal></primary></indexterm>
1585 Stolen by: <option>-XArrows</option>,
1591 <literal>?<replaceable>varid</replaceable></literal>,
1592 <literal>%<replaceable>varid</replaceable></literal>
1593 <indexterm><primary>implicit parameters</primary></indexterm>
1596 Stolen by: <option>-XImplicitParams</option>,
1602 <literal>[|</literal>,
1603 <literal>[e|</literal>, <literal>[p|</literal>,
1604 <literal>[d|</literal>, <literal>[t|</literal>,
1605 <literal>$(</literal>,
1606 <literal>$<replaceable>varid</replaceable></literal>
1607 <indexterm><primary>Template Haskell</primary></indexterm>
1610 Stolen by: <option>-XTemplateHaskell</option>,
1616 <literal>[:<replaceable>varid</replaceable>|</literal>
1617 <indexterm><primary>quasi-quotation</primary></indexterm>
1620 Stolen by: <option>-XQuasiQuotes</option>,
1626 <replaceable>varid</replaceable>{<literal>#</literal>},
1627 <replaceable>char</replaceable><literal>#</literal>,
1628 <replaceable>string</replaceable><literal>#</literal>,
1629 <replaceable>integer</replaceable><literal>#</literal>,
1630 <replaceable>float</replaceable><literal>#</literal>,
1631 <replaceable>float</replaceable><literal>##</literal>,
1632 <literal>(#</literal>, <literal>#)</literal>,
1635 Stolen by: <option>-XMagicHash</option>,
1644 <!-- TYPE SYSTEM EXTENSIONS -->
1645 <sect1 id="data-type-extensions">
1646 <title>Extensions to data types and type synonyms</title>
1648 <sect2 id="nullary-types">
1649 <title>Data types with no constructors</title>
1651 <para>With the <option>-fglasgow-exts</option> flag, GHC lets you declare
1652 a data type with no constructors. For example:</para>
1656 data T a -- T :: * -> *
1659 <para>Syntactically, the declaration lacks the "= constrs" part. The
1660 type can be parameterised over types of any kind, but if the kind is
1661 not <literal>*</literal> then an explicit kind annotation must be used
1662 (see <xref linkend="kinding"/>).</para>
1664 <para>Such data types have only one value, namely bottom.
1665 Nevertheless, they can be useful when defining "phantom types".</para>
1668 <sect2 id="infix-tycons">
1669 <title>Infix type constructors, classes, and type variables</title>
1672 GHC allows type constructors, classes, and type variables to be operators, and
1673 to be written infix, very much like expressions. More specifically:
1676 A type constructor or class can be an operator, beginning with a colon; e.g. <literal>:*:</literal>.
1677 The lexical syntax is the same as that for data constructors.
1680 Data type and type-synonym declarations can be written infix, parenthesised
1681 if you want further arguments. E.g.
1683 data a :*: b = Foo a b
1684 type a :+: b = Either a b
1685 class a :=: b where ...
1687 data (a :**: b) x = Baz a b x
1688 type (a :++: b) y = Either (a,b) y
1692 Types, and class constraints, can be written infix. For example
1695 f :: (a :=: b) => a -> b
1699 A type variable can be an (unqualified) operator e.g. <literal>+</literal>.
1700 The lexical syntax is the same as that for variable operators, excluding "(.)",
1701 "(!)", and "(*)". In a binding position, the operator must be
1702 parenthesised. For example:
1704 type T (+) = Int + Int
1708 liftA2 :: Arrow (~>)
1709 => (a -> b -> c) -> (e ~> a) -> (e ~> b) -> (e ~> c)
1715 as for expressions, both for type constructors and type variables; e.g. <literal>Int `Either` Bool</literal>, or
1716 <literal>Int `a` Bool</literal>. Similarly, parentheses work the same; e.g. <literal>(:*:) Int Bool</literal>.
1719 Fixities may be declared for type constructors, or classes, just as for data constructors. However,
1720 one cannot distinguish between the two in a fixity declaration; a fixity declaration
1721 sets the fixity for a data constructor and the corresponding type constructor. For example:
1725 sets the fixity for both type constructor <literal>T</literal> and data constructor <literal>T</literal>,
1726 and similarly for <literal>:*:</literal>.
1727 <literal>Int `a` Bool</literal>.
1730 Function arrow is <literal>infixr</literal> with fixity 0. (This might change; I'm not sure what it should be.)
1737 <sect2 id="type-synonyms">
1738 <title>Liberalised type synonyms</title>
1741 Type synonyms are like macros at the type level, but Haskell 98 imposes many rules
1742 on individual synonym declarations.
1743 With the <option>-XLiberalTypeSynonyms</option> extension,
1744 GHC does validity checking on types <emphasis>only after expanding type synonyms</emphasis>.
1745 That means that GHC can be very much more liberal about type synonyms than Haskell 98.
1748 <listitem> <para>You can write a <literal>forall</literal> (including overloading)
1749 in a type synonym, thus:
1751 type Discard a = forall b. Show b => a -> b -> (a, String)
1756 g :: Discard Int -> (Int,String) -- A rank-2 type
1763 If you also use <option>-XUnboxedTuples</option>,
1764 you can write an unboxed tuple in a type synonym:
1766 type Pr = (# Int, Int #)
1774 You can apply a type synonym to a forall type:
1776 type Foo a = a -> a -> Bool
1778 f :: Foo (forall b. b->b)
1780 After expanding the synonym, <literal>f</literal> has the legal (in GHC) type:
1782 f :: (forall b. b->b) -> (forall b. b->b) -> Bool
1787 You can apply a type synonym to a partially applied type synonym:
1789 type Generic i o = forall x. i x -> o x
1792 foo :: Generic Id []
1794 After expanding the synonym, <literal>foo</literal> has the legal (in GHC) type:
1796 foo :: forall x. x -> [x]
1804 GHC currently does kind checking before expanding synonyms (though even that
1808 After expanding type synonyms, GHC does validity checking on types, looking for
1809 the following mal-formedness which isn't detected simply by kind checking:
1812 Type constructor applied to a type involving for-alls.
1815 Unboxed tuple on left of an arrow.
1818 Partially-applied type synonym.
1822 this will be rejected:
1824 type Pr = (# Int, Int #)
1829 because GHC does not allow unboxed tuples on the left of a function arrow.
1834 <sect2 id="existential-quantification">
1835 <title>Existentially quantified data constructors
1839 The idea of using existential quantification in data type declarations
1840 was suggested by Perry, and implemented in Hope+ (Nigel Perry, <emphasis>The Implementation
1841 of Practical Functional Programming Languages</emphasis>, PhD Thesis, University of
1842 London, 1991). It was later formalised by Laufer and Odersky
1843 (<emphasis>Polymorphic type inference and abstract data types</emphasis>,
1844 TOPLAS, 16(5), pp1411-1430, 1994).
1845 It's been in Lennart
1846 Augustsson's <command>hbc</command> Haskell compiler for several years, and
1847 proved very useful. Here's the idea. Consider the declaration:
1853 data Foo = forall a. MkFoo a (a -> Bool)
1860 The data type <literal>Foo</literal> has two constructors with types:
1866 MkFoo :: forall a. a -> (a -> Bool) -> Foo
1873 Notice that the type variable <literal>a</literal> in the type of <function>MkFoo</function>
1874 does not appear in the data type itself, which is plain <literal>Foo</literal>.
1875 For example, the following expression is fine:
1881 [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
1887 Here, <literal>(MkFoo 3 even)</literal> packages an integer with a function
1888 <function>even</function> that maps an integer to <literal>Bool</literal>; and <function>MkFoo 'c'
1889 isUpper</function> packages a character with a compatible function. These
1890 two things are each of type <literal>Foo</literal> and can be put in a list.
1894 What can we do with a value of type <literal>Foo</literal>?. In particular,
1895 what happens when we pattern-match on <function>MkFoo</function>?
1901 f (MkFoo val fn) = ???
1907 Since all we know about <literal>val</literal> and <function>fn</function> is that they
1908 are compatible, the only (useful) thing we can do with them is to
1909 apply <function>fn</function> to <literal>val</literal> to get a boolean. For example:
1916 f (MkFoo val fn) = fn val
1922 What this allows us to do is to package heterogeneous values
1923 together with a bunch of functions that manipulate them, and then treat
1924 that collection of packages in a uniform manner. You can express
1925 quite a bit of object-oriented-like programming this way.
1928 <sect3 id="existential">
1929 <title>Why existential?
1933 What has this to do with <emphasis>existential</emphasis> quantification?
1934 Simply that <function>MkFoo</function> has the (nearly) isomorphic type
1940 MkFoo :: (exists a . (a, a -> Bool)) -> Foo
1946 But Haskell programmers can safely think of the ordinary
1947 <emphasis>universally</emphasis> quantified type given above, thereby avoiding
1948 adding a new existential quantification construct.
1953 <sect3 id="existential-with-context">
1954 <title>Existentials and type classes</title>
1957 An easy extension is to allow
1958 arbitrary contexts before the constructor. For example:
1964 data Baz = forall a. Eq a => Baz1 a a
1965 | forall b. Show b => Baz2 b (b -> b)
1971 The two constructors have the types you'd expect:
1977 Baz1 :: forall a. Eq a => a -> a -> Baz
1978 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
1984 But when pattern matching on <function>Baz1</function> the matched values can be compared
1985 for equality, and when pattern matching on <function>Baz2</function> the first matched
1986 value can be converted to a string (as well as applying the function to it).
1987 So this program is legal:
1994 f (Baz1 p q) | p == q = "Yes"
1996 f (Baz2 v fn) = show (fn v)
2002 Operationally, in a dictionary-passing implementation, the
2003 constructors <function>Baz1</function> and <function>Baz2</function> must store the
2004 dictionaries for <literal>Eq</literal> and <literal>Show</literal> respectively, and
2005 extract it on pattern matching.
2010 <sect3 id="existential-records">
2011 <title>Record Constructors</title>
2014 GHC allows existentials to be used with records syntax as well. For example:
2017 data Counter a = forall self. NewCounter
2019 , _inc :: self -> self
2020 , _display :: self -> IO ()
2024 Here <literal>tag</literal> is a public field, with a well-typed selector
2025 function <literal>tag :: Counter a -> a</literal>. The <literal>self</literal>
2026 type is hidden from the outside; any attempt to apply <literal>_this</literal>,
2027 <literal>_inc</literal> or <literal>_display</literal> as functions will raise a
2028 compile-time error. In other words, <emphasis>GHC defines a record selector function
2029 only for fields whose type does not mention the existentially-quantified variables</emphasis>.
2030 (This example used an underscore in the fields for which record selectors
2031 will not be defined, but that is only programming style; GHC ignores them.)
2035 To make use of these hidden fields, we need to create some helper functions:
2038 inc :: Counter a -> Counter a
2039 inc (NewCounter x i d t) = NewCounter
2040 { _this = i x, _inc = i, _display = d, tag = t }
2042 display :: Counter a -> IO ()
2043 display NewCounter{ _this = x, _display = d } = d x
2046 Now we can define counters with different underlying implementations:
2049 counterA :: Counter String
2050 counterA = NewCounter
2051 { _this = 0, _inc = (1+), _display = print, tag = "A" }
2053 counterB :: Counter String
2054 counterB = NewCounter
2055 { _this = "", _inc = ('#':), _display = putStrLn, tag = "B" }
2058 display (inc counterA) -- prints "1"
2059 display (inc (inc counterB)) -- prints "##"
2062 Record update syntax is supported for existentials (and GADTs):
2064 setTag :: Counter a -> a -> Counter a
2065 setTag obj t = obj{ tag = t }
2067 The rule for record update is this: <emphasis>
2068 the types of the updated fields may
2069 mention only the universally-quantified type variables
2070 of the data constructor. For GADTs, the field may mention only types
2071 that appear as a simple type-variable argument in the constructor's result
2072 type</emphasis>. For example:
2074 data T a b where { T1 { f1::a, f2::b, f3::(b,c) } :: T a b } -- c is existential
2075 upd1 t x = t { f1=x } -- OK: upd1 :: T a b -> a' -> T a' b
2076 upd2 t x = t { f3=x } -- BAD (f3's type mentions c, which is
2077 -- existentially quantified)
2079 data G a b where { G1 { g1::a, g2::c } :: G a [c] }
2080 upd3 g x = g { g1=x } -- OK: upd3 :: G a b -> c -> G c b
2081 upd4 g x = g { g2=x } -- BAD (f2's type mentions c, which is not a simple
2082 -- type-variable argument in G1's result type)
2090 <title>Restrictions</title>
2093 There are several restrictions on the ways in which existentially-quantified
2094 constructors can be use.
2103 When pattern matching, each pattern match introduces a new,
2104 distinct, type for each existential type variable. These types cannot
2105 be unified with any other type, nor can they escape from the scope of
2106 the pattern match. For example, these fragments are incorrect:
2114 Here, the type bound by <function>MkFoo</function> "escapes", because <literal>a</literal>
2115 is the result of <function>f1</function>. One way to see why this is wrong is to
2116 ask what type <function>f1</function> has:
2120 f1 :: Foo -> a -- Weird!
2124 What is this "<literal>a</literal>" in the result type? Clearly we don't mean
2129 f1 :: forall a. Foo -> a -- Wrong!
2133 The original program is just plain wrong. Here's another sort of error
2137 f2 (Baz1 a b) (Baz1 p q) = a==q
2141 It's ok to say <literal>a==b</literal> or <literal>p==q</literal>, but
2142 <literal>a==q</literal> is wrong because it equates the two distinct types arising
2143 from the two <function>Baz1</function> constructors.
2151 You can't pattern-match on an existentially quantified
2152 constructor in a <literal>let</literal> or <literal>where</literal> group of
2153 bindings. So this is illegal:
2157 f3 x = a==b where { Baz1 a b = x }
2160 Instead, use a <literal>case</literal> expression:
2163 f3 x = case x of Baz1 a b -> a==b
2166 In general, you can only pattern-match
2167 on an existentially-quantified constructor in a <literal>case</literal> expression or
2168 in the patterns of a function definition.
2170 The reason for this restriction is really an implementation one.
2171 Type-checking binding groups is already a nightmare without
2172 existentials complicating the picture. Also an existential pattern
2173 binding at the top level of a module doesn't make sense, because it's
2174 not clear how to prevent the existentially-quantified type "escaping".
2175 So for now, there's a simple-to-state restriction. We'll see how
2183 You can't use existential quantification for <literal>newtype</literal>
2184 declarations. So this is illegal:
2188 newtype T = forall a. Ord a => MkT a
2192 Reason: a value of type <literal>T</literal> must be represented as a
2193 pair of a dictionary for <literal>Ord t</literal> and a value of type
2194 <literal>t</literal>. That contradicts the idea that
2195 <literal>newtype</literal> should have no concrete representation.
2196 You can get just the same efficiency and effect by using
2197 <literal>data</literal> instead of <literal>newtype</literal>. If
2198 there is no overloading involved, then there is more of a case for
2199 allowing an existentially-quantified <literal>newtype</literal>,
2200 because the <literal>data</literal> version does carry an
2201 implementation cost, but single-field existentially quantified
2202 constructors aren't much use. So the simple restriction (no
2203 existential stuff on <literal>newtype</literal>) stands, unless there
2204 are convincing reasons to change it.
2212 You can't use <literal>deriving</literal> to define instances of a
2213 data type with existentially quantified data constructors.
2215 Reason: in most cases it would not make sense. For example:;
2218 data T = forall a. MkT [a] deriving( Eq )
2221 To derive <literal>Eq</literal> in the standard way we would need to have equality
2222 between the single component of two <function>MkT</function> constructors:
2226 (MkT a) == (MkT b) = ???
2229 But <varname>a</varname> and <varname>b</varname> have distinct types, and so can't be compared.
2230 It's just about possible to imagine examples in which the derived instance
2231 would make sense, but it seems altogether simpler simply to prohibit such
2232 declarations. Define your own instances!
2243 <!-- ====================== Generalised algebraic data types ======================= -->
2245 <sect2 id="gadt-style">
2246 <title>Declaring data types with explicit constructor signatures</title>
2248 <para>GHC allows you to declare an algebraic data type by
2249 giving the type signatures of constructors explicitly. For example:
2253 Just :: a -> Maybe a
2255 The form is called a "GADT-style declaration"
2256 because Generalised Algebraic Data Types, described in <xref linkend="gadt"/>,
2257 can only be declared using this form.</para>
2258 <para>Notice that GADT-style syntax generalises existential types (<xref linkend="existential-quantification"/>).
2259 For example, these two declarations are equivalent:
2261 data Foo = forall a. MkFoo a (a -> Bool)
2262 data Foo' where { MKFoo :: a -> (a->Bool) -> Foo' }
2265 <para>Any data type that can be declared in standard Haskell-98 syntax
2266 can also be declared using GADT-style syntax.
2267 The choice is largely stylistic, but GADT-style declarations differ in one important respect:
2268 they treat class constraints on the data constructors differently.
2269 Specifically, if the constructor is given a type-class context, that
2270 context is made available by pattern matching. For example:
2273 MkSet :: Eq a => [a] -> Set a
2275 makeSet :: Eq a => [a] -> Set a
2276 makeSet xs = MkSet (nub xs)
2278 insert :: a -> Set a -> Set a
2279 insert a (MkSet as) | a `elem` as = MkSet as
2280 | otherwise = MkSet (a:as)
2282 A use of <literal>MkSet</literal> as a constructor (e.g. in the definition of <literal>makeSet</literal>)
2283 gives rise to a <literal>(Eq a)</literal>
2284 constraint, as you would expect. The new feature is that pattern-matching on <literal>MkSet</literal>
2285 (as in the definition of <literal>insert</literal>) makes <emphasis>available</emphasis> an <literal>(Eq a)</literal>
2286 context. In implementation terms, the <literal>MkSet</literal> constructor has a hidden field that stores
2287 the <literal>(Eq a)</literal> dictionary that is passed to <literal>MkSet</literal>; so
2288 when pattern-matching that dictionary becomes available for the right-hand side of the match.
2289 In the example, the equality dictionary is used to satisfy the equality constraint
2290 generated by the call to <literal>elem</literal>, so that the type of
2291 <literal>insert</literal> itself has no <literal>Eq</literal> constraint.
2294 For example, one possible application is to reify dictionaries:
2296 data NumInst a where
2297 MkNumInst :: Num a => NumInst a
2299 intInst :: NumInst Int
2302 plus :: NumInst a -> a -> a -> a
2303 plus MkNumInst p q = p + q
2305 Here, a value of type <literal>NumInst a</literal> is equivalent
2306 to an explicit <literal>(Num a)</literal> dictionary.
2309 All this applies to constructors declared using the syntax of <xref linkend="existential-with-context"/>.
2310 For example, the <literal>NumInst</literal> data type above could equivalently be declared
2314 = Num a => MkNumInst (NumInst a)
2316 Notice that, unlike the situation when declaring an existential, there is
2317 no <literal>forall</literal>, because the <literal>Num</literal> constrains the
2318 data type's universally quantified type variable <literal>a</literal>.
2319 A constructor may have both universal and existential type variables: for example,
2320 the following two declarations are equivalent:
2323 = forall b. (Num a, Eq b) => MkT1 a b
2325 MkT2 :: (Num a, Eq b) => a -> b -> T2 a
2328 <para>All this behaviour contrasts with Haskell 98's peculiar treatment of
2329 contexts on a data type declaration (Section 4.2.1 of the Haskell 98 Report).
2330 In Haskell 98 the definition
2332 data Eq a => Set' a = MkSet' [a]
2334 gives <literal>MkSet'</literal> the same type as <literal>MkSet</literal> above. But instead of
2335 <emphasis>making available</emphasis> an <literal>(Eq a)</literal> constraint, pattern-matching
2336 on <literal>MkSet'</literal> <emphasis>requires</emphasis> an <literal>(Eq a)</literal> constraint!
2337 GHC faithfully implements this behaviour, odd though it is. But for GADT-style declarations,
2338 GHC's behaviour is much more useful, as well as much more intuitive.
2342 The rest of this section gives further details about GADT-style data
2347 The result type of each data constructor must begin with the type constructor being defined.
2348 If the result type of all constructors
2349 has the form <literal>T a1 ... an</literal>, where <literal>a1 ... an</literal>
2350 are distinct type variables, then the data type is <emphasis>ordinary</emphasis>;
2351 otherwise is a <emphasis>generalised</emphasis> data type (<xref linkend="gadt"/>).
2355 As with other type signatures, you can give a single signature for several data constructors.
2356 In this example we give a single signature for <literal>T1</literal> and <literal>T2</literal>:
2365 The type signature of
2366 each constructor is independent, and is implicitly universally quantified as usual.
2367 Different constructors may have different universally-quantified type variables
2368 and different type-class constraints.
2369 For example, this is fine:
2372 T1 :: Eq b => b -> T b
2373 T2 :: (Show c, Ix c) => c -> [c] -> T c
2378 Unlike a Haskell-98-style
2379 data type declaration, the type variable(s) in the "<literal>data Set a where</literal>" header
2380 have no scope. Indeed, one can write a kind signature instead:
2382 data Set :: * -> * where ...
2384 or even a mixture of the two:
2386 data Foo a :: (* -> *) -> * where ...
2388 The type variables (if given) may be explicitly kinded, so we could also write the header for <literal>Foo</literal>
2391 data Foo a (b :: * -> *) where ...
2397 You can use strictness annotations, in the obvious places
2398 in the constructor type:
2401 Lit :: !Int -> Term Int
2402 If :: Term Bool -> !(Term a) -> !(Term a) -> Term a
2403 Pair :: Term a -> Term b -> Term (a,b)
2408 You can use a <literal>deriving</literal> clause on a GADT-style data type
2409 declaration. For example, these two declarations are equivalent
2411 data Maybe1 a where {
2412 Nothing1 :: Maybe1 a ;
2413 Just1 :: a -> Maybe1 a
2414 } deriving( Eq, Ord )
2416 data Maybe2 a = Nothing2 | Just2 a
2422 You can use record syntax on a GADT-style data type declaration:
2426 Adult { name :: String, children :: [Person] } :: Person
2427 Child { name :: String } :: Person
2429 As usual, for every constructor that has a field <literal>f</literal>, the type of
2430 field <literal>f</literal> must be the same (modulo alpha conversion).
2433 At the moment, record updates are not yet possible with GADT-style declarations,
2434 so support is limited to record construction, selection and pattern matching.
2437 aPerson = Adult { name = "Fred", children = [] }
2439 shortName :: Person -> Bool
2440 hasChildren (Adult { children = kids }) = not (null kids)
2441 hasChildren (Child {}) = False
2446 As in the case of existentials declared using the Haskell-98-like record syntax
2447 (<xref linkend="existential-records"/>),
2448 record-selector functions are generated only for those fields that have well-typed
2450 Here is the example of that section, in GADT-style syntax:
2452 data Counter a where
2453 NewCounter { _this :: self
2454 , _inc :: self -> self
2455 , _display :: self -> IO ()
2460 As before, only one selector function is generated here, that for <literal>tag</literal>.
2461 Nevertheless, you can still use all the field names in pattern matching and record construction.
2463 </itemizedlist></para>
2467 <title>Generalised Algebraic Data Types (GADTs)</title>
2469 <para>Generalised Algebraic Data Types generalise ordinary algebraic data types
2470 by allowing constructors to have richer return types. Here is an example:
2473 Lit :: Int -> Term Int
2474 Succ :: Term Int -> Term Int
2475 IsZero :: Term Int -> Term Bool
2476 If :: Term Bool -> Term a -> Term a -> Term a
2477 Pair :: Term a -> Term b -> Term (a,b)
2479 Notice that the return type of the constructors is not always <literal>Term a</literal>, as is the
2480 case with ordinary data types. This generality allows us to
2481 write a well-typed <literal>eval</literal> function
2482 for these <literal>Terms</literal>:
2486 eval (Succ t) = 1 + eval t
2487 eval (IsZero t) = eval t == 0
2488 eval (If b e1 e2) = if eval b then eval e1 else eval e2
2489 eval (Pair e1 e2) = (eval e1, eval e2)
2491 The key point about GADTs is that <emphasis>pattern matching causes type refinement</emphasis>.
2492 For example, in the right hand side of the equation
2497 the type <literal>a</literal> is refined to <literal>Int</literal>. That's the whole point!
2498 A precise specification of the type rules is beyond what this user manual aspires to,
2499 but the design closely follows that described in
2501 url="http://research.microsoft.com/%7Esimonpj/papers/gadt/">Simple
2502 unification-based type inference for GADTs</ulink>,
2504 The general principle is this: <emphasis>type refinement is only carried out
2505 based on user-supplied type annotations</emphasis>.
2506 So if no type signature is supplied for <literal>eval</literal>, no type refinement happens,
2507 and lots of obscure error messages will
2508 occur. However, the refinement is quite general. For example, if we had:
2510 eval :: Term a -> a -> a
2511 eval (Lit i) j = i+j
2513 the pattern match causes the type <literal>a</literal> to be refined to <literal>Int</literal> (because of the type
2514 of the constructor <literal>Lit</literal>), and that refinement also applies to the type of <literal>j</literal>, and
2515 the result type of the <literal>case</literal> expression. Hence the addition <literal>i+j</literal> is legal.
2518 These and many other examples are given in papers by Hongwei Xi, and
2519 Tim Sheard. There is a longer introduction
2520 <ulink url="http://www.haskell.org/haskellwiki/GADT">on the wiki</ulink>,
2522 <ulink url="http://www.informatik.uni-bonn.de/~ralf/publications/With.pdf">Fun with phantom types</ulink> also has a number of examples. Note that papers
2523 may use different notation to that implemented in GHC.
2526 The rest of this section outlines the extensions to GHC that support GADTs. The extension is enabled with
2527 <option>-XGADTs</option>. The <option>-XGADTs</option> flag also sets <option>-XRelaxedPolyRec</option>.
2530 A GADT can only be declared using GADT-style syntax (<xref linkend="gadt-style"/>);
2531 the old Haskell-98 syntax for data declarations always declares an ordinary data type.
2532 The result type of each constructor must begin with the type constructor being defined,
2533 but for a GADT the arguments to the type constructor can be arbitrary monotypes.
2534 For example, in the <literal>Term</literal> data
2535 type above, the type of each constructor must end with <literal>Term ty</literal>, but
2536 the <literal>ty</literal> need not be a type variable (e.g. the <literal>Lit</literal>
2541 It's is permitted to declare an ordinary algebraic data type using GADT-style syntax.
2542 What makes a GADT into a GADT is not the syntax, but rather the presence of data constructors
2543 whose result type is not just <literal>T a b</literal>.
2547 You cannot use a <literal>deriving</literal> clause for a GADT; only for
2548 an ordinary data type.
2552 As mentioned in <xref linkend="gadt-style"/>, record syntax is supported.
2556 Lit { val :: Int } :: Term Int
2557 Succ { num :: Term Int } :: Term Int
2558 Pred { num :: Term Int } :: Term Int
2559 IsZero { arg :: Term Int } :: Term Bool
2560 Pair { arg1 :: Term a
2563 If { cnd :: Term Bool
2568 However, for GADTs there is the following additional constraint:
2569 every constructor that has a field <literal>f</literal> must have
2570 the same result type (modulo alpha conversion)
2571 Hence, in the above example, we cannot merge the <literal>num</literal>
2572 and <literal>arg</literal> fields above into a
2573 single name. Although their field types are both <literal>Term Int</literal>,
2574 their selector functions actually have different types:
2577 num :: Term Int -> Term Int
2578 arg :: Term Bool -> Term Int
2583 When pattern-matching against data constructors drawn from a GADT,
2584 for example in a <literal>case</literal> expression, the following rules apply:
2586 <listitem><para>The type of the scrutinee must be rigid.</para></listitem>
2587 <listitem><para>The type of the entire <literal>case</literal> expression must be rigid.</para></listitem>
2588 <listitem><para>The type of any free variable mentioned in any of
2589 the <literal>case</literal> alternatives must be rigid.</para></listitem>
2591 A type is "rigid" if it is completely known to the compiler at its binding site. The easiest
2592 way to ensure that a variable a rigid type is to give it a type signature.
2593 For more precise details see <ulink url="http://research.microsoft.com/%7Esimonpj/papers/gadt">
2594 Simple unification-based type inference for GADTs
2595 </ulink>. The criteria implemented by GHC are given in the Appendix.
2605 <!-- ====================== End of Generalised algebraic data types ======================= -->
2607 <sect1 id="deriving">
2608 <title>Extensions to the "deriving" mechanism</title>
2610 <sect2 id="deriving-inferred">
2611 <title>Inferred context for deriving clauses</title>
2614 The Haskell Report is vague about exactly when a <literal>deriving</literal> clause is
2617 data T0 f a = MkT0 a deriving( Eq )
2618 data T1 f a = MkT1 (f a) deriving( Eq )
2619 data T2 f a = MkT2 (f (f a)) deriving( Eq )
2621 The natural generated <literal>Eq</literal> code would result in these instance declarations:
2623 instance Eq a => Eq (T0 f a) where ...
2624 instance Eq (f a) => Eq (T1 f a) where ...
2625 instance Eq (f (f a)) => Eq (T2 f a) where ...
2627 The first of these is obviously fine. The second is still fine, although less obviously.
2628 The third is not Haskell 98, and risks losing termination of instances.
2631 GHC takes a conservative position: it accepts the first two, but not the third. The rule is this:
2632 each constraint in the inferred instance context must consist only of type variables,
2633 with no repetitions.
2636 This rule is applied regardless of flags. If you want a more exotic context, you can write
2637 it yourself, using the <link linkend="stand-alone-deriving">standalone deriving mechanism</link>.
2641 <sect2 id="stand-alone-deriving">
2642 <title>Stand-alone deriving declarations</title>
2645 GHC now allows stand-alone <literal>deriving</literal> declarations, enabled by <literal>-XStandaloneDeriving</literal>:
2647 data Foo a = Bar a | Baz String
2649 deriving instance Eq a => Eq (Foo a)
2651 The syntax is identical to that of an ordinary instance declaration apart from (a) the keyword
2652 <literal>deriving</literal>, and (b) the absence of the <literal>where</literal> part.
2653 You must supply a context (in the example the context is <literal>(Eq a)</literal>),
2654 exactly as you would in an ordinary instance declaration.
2655 (In contrast the context is inferred in a <literal>deriving</literal> clause
2656 attached to a data type declaration.)
2658 A <literal>deriving instance</literal> declaration
2659 must obey the same rules concerning form and termination as ordinary instance declarations,
2660 controlled by the same flags; see <xref linkend="instance-decls"/>.
2663 Unlike a <literal>deriving</literal>
2664 declaration attached to a <literal>data</literal> declaration, the instance can be more specific
2665 than the data type (assuming you also use
2666 <literal>-XFlexibleInstances</literal>, <xref linkend="instance-rules"/>). Consider
2669 data Foo a = Bar a | Baz String
2671 deriving instance Eq a => Eq (Foo [a])
2672 deriving instance Eq a => Eq (Foo (Maybe a))
2674 This will generate a derived instance for <literal>(Foo [a])</literal> and <literal>(Foo (Maybe a))</literal>,
2675 but other types such as <literal>(Foo (Int,Bool))</literal> will not be an instance of <literal>Eq</literal>.
2678 <para>The stand-alone syntax is generalised for newtypes in exactly the same
2679 way that ordinary <literal>deriving</literal> clauses are generalised (<xref linkend="newtype-deriving"/>).
2682 newtype Foo a = MkFoo (State Int a)
2684 deriving instance MonadState Int Foo
2686 GHC always treats the <emphasis>last</emphasis> parameter of the instance
2687 (<literal>Foo</literal> in this example) as the type whose instance is being derived.
2693 <sect2 id="deriving-typeable">
2694 <title>Deriving clause for extra classes (<literal>Typeable</literal>, <literal>Data</literal>, etc)</title>
2697 Haskell 98 allows the programmer to add "<literal>deriving( Eq, Ord )</literal>" to a data type
2698 declaration, to generate a standard instance declaration for classes specified in the <literal>deriving</literal> clause.
2699 In Haskell 98, the only classes that may appear in the <literal>deriving</literal> clause are the standard
2700 classes <literal>Eq</literal>, <literal>Ord</literal>,
2701 <literal>Enum</literal>, <literal>Ix</literal>, <literal>Bounded</literal>, <literal>Read</literal>, and <literal>Show</literal>.
2704 GHC extends this list with several more classes that may be automatically derived:
2706 <listitem><para> With <option>-XDeriveDataTypeable</option>, you can derive instances of the classes
2707 <literal>Typeable</literal>, and <literal>Data</literal>, defined in the library
2708 modules <literal>Data.Typeable</literal> and <literal>Data.Generics</literal> respectively.
2710 <para>An instance of <literal>Typeable</literal> can only be derived if the
2711 data type has seven or fewer type parameters, all of kind <literal>*</literal>.
2712 The reason for this is that the <literal>Typeable</literal> class is derived using the scheme
2714 <ulink url="http://research.microsoft.com/%7Esimonpj/papers/hmap/gmap2.ps">
2715 Scrap More Boilerplate: Reflection, Zips, and Generalised Casts
2717 (Section 7.4 of the paper describes the multiple <literal>Typeable</literal> classes that
2718 are used, and only <literal>Typeable1</literal> up to
2719 <literal>Typeable7</literal> are provided in the library.)
2720 In other cases, there is nothing to stop the programmer writing a <literal>TypableX</literal>
2721 class, whose kind suits that of the data type constructor, and
2722 then writing the data type instance by hand.
2726 <listitem><para> With <option>-XDeriveFunctor</option>, you can derive instances of
2727 the class <literal>Functor</literal>,
2728 defined in <literal>GHC.Base</literal>.
2731 <listitem><para> With <option>-XDeriveFoldable</option>, you can derive instances of
2732 the class <literal>Foldable</literal>,
2733 defined in <literal>Data.Foldable</literal>.
2736 <listitem><para> With <option>-XDeriveTraversable</option>, you can derive instances of
2737 the class <literal>Traversable</literal>,
2738 defined in <literal>Data.Traversable</literal>.
2741 In each case the appropriate class must be in scope before it
2742 can be mentioned in the <literal>deriving</literal> clause.
2746 <sect2 id="newtype-deriving">
2747 <title>Generalised derived instances for newtypes</title>
2750 When you define an abstract type using <literal>newtype</literal>, you may want
2751 the new type to inherit some instances from its representation. In
2752 Haskell 98, you can inherit instances of <literal>Eq</literal>, <literal>Ord</literal>,
2753 <literal>Enum</literal> and <literal>Bounded</literal> by deriving them, but for any
2754 other classes you have to write an explicit instance declaration. For
2755 example, if you define
2758 newtype Dollars = Dollars Int
2761 and you want to use arithmetic on <literal>Dollars</literal>, you have to
2762 explicitly define an instance of <literal>Num</literal>:
2765 instance Num Dollars where
2766 Dollars a + Dollars b = Dollars (a+b)
2769 All the instance does is apply and remove the <literal>newtype</literal>
2770 constructor. It is particularly galling that, since the constructor
2771 doesn't appear at run-time, this instance declaration defines a
2772 dictionary which is <emphasis>wholly equivalent</emphasis> to the <literal>Int</literal>
2773 dictionary, only slower!
2777 <sect3> <title> Generalising the deriving clause </title>
2779 GHC now permits such instances to be derived instead,
2780 using the flag <option>-XGeneralizedNewtypeDeriving</option>,
2783 newtype Dollars = Dollars Int deriving (Eq,Show,Num)
2786 and the implementation uses the <emphasis>same</emphasis> <literal>Num</literal> dictionary
2787 for <literal>Dollars</literal> as for <literal>Int</literal>. Notionally, the compiler
2788 derives an instance declaration of the form
2791 instance Num Int => Num Dollars
2794 which just adds or removes the <literal>newtype</literal> constructor according to the type.
2798 We can also derive instances of constructor classes in a similar
2799 way. For example, suppose we have implemented state and failure monad
2800 transformers, such that
2803 instance Monad m => Monad (State s m)
2804 instance Monad m => Monad (Failure m)
2806 In Haskell 98, we can define a parsing monad by
2808 type Parser tok m a = State [tok] (Failure m) a
2811 which is automatically a monad thanks to the instance declarations
2812 above. With the extension, we can make the parser type abstract,
2813 without needing to write an instance of class <literal>Monad</literal>, via
2816 newtype Parser tok m a = Parser (State [tok] (Failure m) a)
2819 In this case the derived instance declaration is of the form
2821 instance Monad (State [tok] (Failure m)) => Monad (Parser tok m)
2824 Notice that, since <literal>Monad</literal> is a constructor class, the
2825 instance is a <emphasis>partial application</emphasis> of the new type, not the
2826 entire left hand side. We can imagine that the type declaration is
2827 "eta-converted" to generate the context of the instance
2832 We can even derive instances of multi-parameter classes, provided the
2833 newtype is the last class parameter. In this case, a ``partial
2834 application'' of the class appears in the <literal>deriving</literal>
2835 clause. For example, given the class
2838 class StateMonad s m | m -> s where ...
2839 instance Monad m => StateMonad s (State s m) where ...
2841 then we can derive an instance of <literal>StateMonad</literal> for <literal>Parser</literal>s by
2843 newtype Parser tok m a = Parser (State [tok] (Failure m) a)
2844 deriving (Monad, StateMonad [tok])
2847 The derived instance is obtained by completing the application of the
2848 class to the new type:
2851 instance StateMonad [tok] (State [tok] (Failure m)) =>
2852 StateMonad [tok] (Parser tok m)
2857 As a result of this extension, all derived instances in newtype
2858 declarations are treated uniformly (and implemented just by reusing
2859 the dictionary for the representation type), <emphasis>except</emphasis>
2860 <literal>Show</literal> and <literal>Read</literal>, which really behave differently for
2861 the newtype and its representation.
2865 <sect3> <title> A more precise specification </title>
2867 Derived instance declarations are constructed as follows. Consider the
2868 declaration (after expansion of any type synonyms)
2871 newtype T v1...vn = T' (t vk+1...vn) deriving (c1...cm)
2877 The <literal>ci</literal> are partial applications of
2878 classes of the form <literal>C t1'...tj'</literal>, where the arity of <literal>C</literal>
2879 is exactly <literal>j+1</literal>. That is, <literal>C</literal> lacks exactly one type argument.
2882 The <literal>k</literal> is chosen so that <literal>ci (T v1...vk)</literal> is well-kinded.
2885 The type <literal>t</literal> is an arbitrary type.
2888 The type variables <literal>vk+1...vn</literal> do not occur in <literal>t</literal>,
2889 nor in the <literal>ci</literal>, and
2892 None of the <literal>ci</literal> is <literal>Read</literal>, <literal>Show</literal>,
2893 <literal>Typeable</literal>, or <literal>Data</literal>. These classes
2894 should not "look through" the type or its constructor. You can still
2895 derive these classes for a newtype, but it happens in the usual way, not
2896 via this new mechanism.
2899 Then, for each <literal>ci</literal>, the derived instance
2902 instance ci t => ci (T v1...vk)
2904 As an example which does <emphasis>not</emphasis> work, consider
2906 newtype NonMonad m s = NonMonad (State s m s) deriving Monad
2908 Here we cannot derive the instance
2910 instance Monad (State s m) => Monad (NonMonad m)
2913 because the type variable <literal>s</literal> occurs in <literal>State s m</literal>,
2914 and so cannot be "eta-converted" away. It is a good thing that this
2915 <literal>deriving</literal> clause is rejected, because <literal>NonMonad m</literal> is
2916 not, in fact, a monad --- for the same reason. Try defining
2917 <literal>>>=</literal> with the correct type: you won't be able to.
2921 Notice also that the <emphasis>order</emphasis> of class parameters becomes
2922 important, since we can only derive instances for the last one. If the
2923 <literal>StateMonad</literal> class above were instead defined as
2926 class StateMonad m s | m -> s where ...
2929 then we would not have been able to derive an instance for the
2930 <literal>Parser</literal> type above. We hypothesise that multi-parameter
2931 classes usually have one "main" parameter for which deriving new
2932 instances is most interesting.
2934 <para>Lastly, all of this applies only for classes other than
2935 <literal>Read</literal>, <literal>Show</literal>, <literal>Typeable</literal>,
2936 and <literal>Data</literal>, for which the built-in derivation applies (section
2937 4.3.3. of the Haskell Report).
2938 (For the standard classes <literal>Eq</literal>, <literal>Ord</literal>,
2939 <literal>Ix</literal>, and <literal>Bounded</literal> it is immaterial whether
2940 the standard method is used or the one described here.)
2947 <!-- TYPE SYSTEM EXTENSIONS -->
2948 <sect1 id="type-class-extensions">
2949 <title>Class and instances declarations</title>
2951 <sect2 id="multi-param-type-classes">
2952 <title>Class declarations</title>
2955 This section, and the next one, documents GHC's type-class extensions.
2956 There's lots of background in the paper <ulink
2957 url="http://research.microsoft.com/~simonpj/Papers/type-class-design-space/">Type
2958 classes: exploring the design space</ulink> (Simon Peyton Jones, Mark
2959 Jones, Erik Meijer).
2962 All the extensions are enabled by the <option>-fglasgow-exts</option> flag.
2966 <title>Multi-parameter type classes</title>
2968 Multi-parameter type classes are permitted. For example:
2972 class Collection c a where
2973 union :: c a -> c a -> c a
2981 <title>The superclasses of a class declaration</title>
2984 There are no restrictions on the context in a class declaration
2985 (which introduces superclasses), except that the class hierarchy must
2986 be acyclic. So these class declarations are OK:
2990 class Functor (m k) => FiniteMap m k where
2993 class (Monad m, Monad (t m)) => Transform t m where
2994 lift :: m a -> (t m) a
3000 As in Haskell 98, The class hierarchy must be acyclic. However, the definition
3001 of "acyclic" involves only the superclass relationships. For example,
3007 op :: D b => a -> b -> b
3010 class C a => D a where { ... }
3014 Here, <literal>C</literal> is a superclass of <literal>D</literal>, but it's OK for a
3015 class operation <literal>op</literal> of <literal>C</literal> to mention <literal>D</literal>. (It
3016 would not be OK for <literal>D</literal> to be a superclass of <literal>C</literal>.)
3023 <sect3 id="class-method-types">
3024 <title>Class method types</title>
3027 Haskell 98 prohibits class method types to mention constraints on the
3028 class type variable, thus:
3031 fromList :: [a] -> s a
3032 elem :: Eq a => a -> s a -> Bool
3034 The type of <literal>elem</literal> is illegal in Haskell 98, because it
3035 contains the constraint <literal>Eq a</literal>, constrains only the
3036 class type variable (in this case <literal>a</literal>).
3037 GHC lifts this restriction (flag <option>-XConstrainedClassMethods</option>).
3044 <sect2 id="functional-dependencies">
3045 <title>Functional dependencies
3048 <para> Functional dependencies are implemented as described by Mark Jones
3049 in “<ulink url="http://citeseer.ist.psu.edu/jones00type.html">Type Classes with Functional Dependencies</ulink>”, Mark P. Jones,
3050 In Proceedings of the 9th European Symposium on Programming,
3051 ESOP 2000, Berlin, Germany, March 2000, Springer-Verlag LNCS 1782,
3055 Functional dependencies are introduced by a vertical bar in the syntax of a
3056 class declaration; e.g.
3058 class (Monad m) => MonadState s m | m -> s where ...
3060 class Foo a b c | a b -> c where ...
3062 There should be more documentation, but there isn't (yet). Yell if you need it.
3065 <sect3><title>Rules for functional dependencies </title>
3067 In a class declaration, all of the class type variables must be reachable (in the sense
3068 mentioned in <xref linkend="type-restrictions"/>)
3069 from the free variables of each method type.
3073 class Coll s a where
3075 insert :: s -> a -> s
3078 is not OK, because the type of <literal>empty</literal> doesn't mention
3079 <literal>a</literal>. Functional dependencies can make the type variable
3082 class Coll s a | s -> a where
3084 insert :: s -> a -> s
3087 Alternatively <literal>Coll</literal> might be rewritten
3090 class Coll s a where
3092 insert :: s a -> a -> s a
3096 which makes the connection between the type of a collection of
3097 <literal>a</literal>'s (namely <literal>(s a)</literal>) and the element type <literal>a</literal>.
3098 Occasionally this really doesn't work, in which case you can split the
3106 class CollE s => Coll s a where
3107 insert :: s -> a -> s
3114 <title>Background on functional dependencies</title>
3116 <para>The following description of the motivation and use of functional dependencies is taken
3117 from the Hugs user manual, reproduced here (with minor changes) by kind
3118 permission of Mark Jones.
3121 Consider the following class, intended as part of a
3122 library for collection types:
3124 class Collects e ce where
3126 insert :: e -> ce -> ce
3127 member :: e -> ce -> Bool
3129 The type variable e used here represents the element type, while ce is the type
3130 of the container itself. Within this framework, we might want to define
3131 instances of this class for lists or characteristic functions (both of which
3132 can be used to represent collections of any equality type), bit sets (which can
3133 be used to represent collections of characters), or hash tables (which can be
3134 used to represent any collection whose elements have a hash function). Omitting
3135 standard implementation details, this would lead to the following declarations:
3137 instance Eq e => Collects e [e] where ...
3138 instance Eq e => Collects e (e -> Bool) where ...
3139 instance Collects Char BitSet where ...
3140 instance (Hashable e, Collects a ce)
3141 => Collects e (Array Int ce) where ...
3143 All this looks quite promising; we have a class and a range of interesting
3144 implementations. Unfortunately, there are some serious problems with the class
3145 declaration. First, the empty function has an ambiguous type:
3147 empty :: Collects e ce => ce
3149 By "ambiguous" we mean that there is a type variable e that appears on the left
3150 of the <literal>=></literal> symbol, but not on the right. The problem with
3151 this is that, according to the theoretical foundations of Haskell overloading,
3152 we cannot guarantee a well-defined semantics for any term with an ambiguous
3156 We can sidestep this specific problem by removing the empty member from the
3157 class declaration. However, although the remaining members, insert and member,
3158 do not have ambiguous types, we still run into problems when we try to use
3159 them. For example, consider the following two functions:
3161 f x y = insert x . insert y
3164 for which GHC infers the following types:
3166 f :: (Collects a c, Collects b c) => a -> b -> c -> c
3167 g :: (Collects Bool c, Collects Char c) => c -> c
3169 Notice that the type for f allows the two parameters x and y to be assigned
3170 different types, even though it attempts to insert each of the two values, one
3171 after the other, into the same collection. If we're trying to model collections
3172 that contain only one type of value, then this is clearly an inaccurate
3173 type. Worse still, the definition for g is accepted, without causing a type
3174 error. As a result, the error in this code will not be flagged at the point
3175 where it appears. Instead, it will show up only when we try to use g, which
3176 might even be in a different module.
3179 <sect4><title>An attempt to use constructor classes</title>
3182 Faced with the problems described above, some Haskell programmers might be
3183 tempted to use something like the following version of the class declaration:
3185 class Collects e c where
3187 insert :: e -> c e -> c e
3188 member :: e -> c e -> Bool
3190 The key difference here is that we abstract over the type constructor c that is
3191 used to form the collection type c e, and not over that collection type itself,
3192 represented by ce in the original class declaration. This avoids the immediate
3193 problems that we mentioned above: empty has type <literal>Collects e c => c
3194 e</literal>, which is not ambiguous.
3197 The function f from the previous section has a more accurate type:
3199 f :: (Collects e c) => e -> e -> c e -> c e
3201 The function g from the previous section is now rejected with a type error as
3202 we would hope because the type of f does not allow the two arguments to have
3204 This, then, is an example of a multiple parameter class that does actually work
3205 quite well in practice, without ambiguity problems.
3206 There is, however, a catch. This version of the Collects class is nowhere near
3207 as general as the original class seemed to be: only one of the four instances
3208 for <literal>Collects</literal>
3209 given above can be used with this version of Collects because only one of
3210 them---the instance for lists---has a collection type that can be written in
3211 the form c e, for some type constructor c, and element type e.
3215 <sect4><title>Adding functional dependencies</title>
3218 To get a more useful version of the Collects class, Hugs provides a mechanism
3219 that allows programmers to specify dependencies between the parameters of a
3220 multiple parameter class (For readers with an interest in theoretical
3221 foundations and previous work: The use of dependency information can be seen
3222 both as a generalization of the proposal for `parametric type classes' that was
3223 put forward by Chen, Hudak, and Odersky, or as a special case of Mark Jones's
3224 later framework for "improvement" of qualified types. The
3225 underlying ideas are also discussed in a more theoretical and abstract setting
3226 in a manuscript [implparam], where they are identified as one point in a
3227 general design space for systems of implicit parameterization.).
3229 To start with an abstract example, consider a declaration such as:
3231 class C a b where ...
3233 which tells us simply that C can be thought of as a binary relation on types
3234 (or type constructors, depending on the kinds of a and b). Extra clauses can be
3235 included in the definition of classes to add information about dependencies
3236 between parameters, as in the following examples:
3238 class D a b | a -> b where ...
3239 class E a b | a -> b, b -> a where ...
3241 The notation <literal>a -> b</literal> used here between the | and where
3242 symbols --- not to be
3243 confused with a function type --- indicates that the a parameter uniquely
3244 determines the b parameter, and might be read as "a determines b." Thus D is
3245 not just a relation, but actually a (partial) function. Similarly, from the two
3246 dependencies that are included in the definition of E, we can see that E
3247 represents a (partial) one-one mapping between types.
3250 More generally, dependencies take the form <literal>x1 ... xn -> y1 ... ym</literal>,
3251 where x1, ..., xn, and y1, ..., yn are type variables with n>0 and
3252 m>=0, meaning that the y parameters are uniquely determined by the x
3253 parameters. Spaces can be used as separators if more than one variable appears
3254 on any single side of a dependency, as in <literal>t -> a b</literal>. Note that a class may be
3255 annotated with multiple dependencies using commas as separators, as in the
3256 definition of E above. Some dependencies that we can write in this notation are
3257 redundant, and will be rejected because they don't serve any useful
3258 purpose, and may instead indicate an error in the program. Examples of
3259 dependencies like this include <literal>a -> a </literal>,
3260 <literal>a -> a a </literal>,
3261 <literal>a -> </literal>, etc. There can also be
3262 some redundancy if multiple dependencies are given, as in
3263 <literal>a->b</literal>,
3264 <literal>b->c </literal>, <literal>a->c </literal>, and
3265 in which some subset implies the remaining dependencies. Examples like this are
3266 not treated as errors. Note that dependencies appear only in class
3267 declarations, and not in any other part of the language. In particular, the
3268 syntax for instance declarations, class constraints, and types is completely
3272 By including dependencies in a class declaration, we provide a mechanism for
3273 the programmer to specify each multiple parameter class more precisely. The
3274 compiler, on the other hand, is responsible for ensuring that the set of
3275 instances that are in scope at any given point in the program is consistent
3276 with any declared dependencies. For example, the following pair of instance
3277 declarations cannot appear together in the same scope because they violate the
3278 dependency for D, even though either one on its own would be acceptable:
3280 instance D Bool Int where ...
3281 instance D Bool Char where ...
3283 Note also that the following declaration is not allowed, even by itself:
3285 instance D [a] b where ...
3287 The problem here is that this instance would allow one particular choice of [a]
3288 to be associated with more than one choice for b, which contradicts the
3289 dependency specified in the definition of D. More generally, this means that,
3290 in any instance of the form:
3292 instance D t s where ...
3294 for some particular types t and s, the only variables that can appear in s are
3295 the ones that appear in t, and hence, if the type t is known, then s will be
3296 uniquely determined.
3299 The benefit of including dependency information is that it allows us to define
3300 more general multiple parameter classes, without ambiguity problems, and with
3301 the benefit of more accurate types. To illustrate this, we return to the
3302 collection class example, and annotate the original definition of <literal>Collects</literal>
3303 with a simple dependency:
3305 class Collects e ce | ce -> e where
3307 insert :: e -> ce -> ce
3308 member :: e -> ce -> Bool
3310 The dependency <literal>ce -> e</literal> here specifies that the type e of elements is uniquely
3311 determined by the type of the collection ce. Note that both parameters of
3312 Collects are of kind *; there are no constructor classes here. Note too that
3313 all of the instances of Collects that we gave earlier can be used
3314 together with this new definition.
3317 What about the ambiguity problems that we encountered with the original
3318 definition? The empty function still has type Collects e ce => ce, but it is no
3319 longer necessary to regard that as an ambiguous type: Although the variable e
3320 does not appear on the right of the => symbol, the dependency for class
3321 Collects tells us that it is uniquely determined by ce, which does appear on
3322 the right of the => symbol. Hence the context in which empty is used can still
3323 give enough information to determine types for both ce and e, without
3324 ambiguity. More generally, we need only regard a type as ambiguous if it
3325 contains a variable on the left of the => that is not uniquely determined
3326 (either directly or indirectly) by the variables on the right.
3329 Dependencies also help to produce more accurate types for user defined
3330 functions, and hence to provide earlier detection of errors, and less cluttered
3331 types for programmers to work with. Recall the previous definition for a
3334 f x y = insert x y = insert x . insert y
3336 for which we originally obtained a type:
3338 f :: (Collects a c, Collects b c) => a -> b -> c -> c
3340 Given the dependency information that we have for Collects, however, we can
3341 deduce that a and b must be equal because they both appear as the second
3342 parameter in a Collects constraint with the same first parameter c. Hence we
3343 can infer a shorter and more accurate type for f:
3345 f :: (Collects a c) => a -> a -> c -> c
3347 In a similar way, the earlier definition of g will now be flagged as a type error.
3350 Although we have given only a few examples here, it should be clear that the
3351 addition of dependency information can help to make multiple parameter classes
3352 more useful in practice, avoiding ambiguity problems, and allowing more general
3353 sets of instance declarations.
3359 <sect2 id="instance-decls">
3360 <title>Instance declarations</title>
3362 <para>An instance declaration has the form
3364 instance ( <replaceable>assertion</replaceable><subscript>1</subscript>, ..., <replaceable>assertion</replaceable><subscript>n</subscript>) => <replaceable>class</replaceable> <replaceable>type</replaceable><subscript>1</subscript> ... <replaceable>type</replaceable><subscript>m</subscript> where ...
3366 The part before the "<literal>=></literal>" is the
3367 <emphasis>context</emphasis>, while the part after the
3368 "<literal>=></literal>" is the <emphasis>head</emphasis> of the instance declaration.
3371 <sect3 id="flexible-instance-head">
3372 <title>Relaxed rules for the instance head</title>
3375 In Haskell 98 the head of an instance declaration
3376 must be of the form <literal>C (T a1 ... an)</literal>, where
3377 <literal>C</literal> is the class, <literal>T</literal> is a data type constructor,
3378 and the <literal>a1 ... an</literal> are distinct type variables.
3379 GHC relaxes these rules in two ways.
3383 The <option>-XFlexibleInstances</option> flag allows the head of the instance
3384 declaration to mention arbitrary nested types.
3385 For example, this becomes a legal instance declaration
3387 instance C (Maybe Int) where ...
3389 See also the <link linkend="instance-overlap">rules on overlap</link>.
3392 With the <option>-XTypeSynonymInstances</option> flag, instance heads may use type
3393 synonyms. As always, using a type synonym is just shorthand for
3394 writing the RHS of the type synonym definition. For example:
3398 type Point = (Int,Int)
3399 instance C Point where ...
3400 instance C [Point] where ...
3404 is legal. However, if you added
3408 instance C (Int,Int) where ...
3412 as well, then the compiler will complain about the overlapping
3413 (actually, identical) instance declarations. As always, type synonyms
3414 must be fully applied. You cannot, for example, write:
3418 instance Monad P where ...
3426 <sect3 id="instance-rules">
3427 <title>Relaxed rules for instance contexts</title>
3429 <para>In Haskell 98, the assertions in the context of the instance declaration
3430 must be of the form <literal>C a</literal> where <literal>a</literal>
3431 is a type variable that occurs in the head.
3435 The <option>-XFlexibleContexts</option> flag relaxes this rule, as well
3436 as the corresponding rule for type signatures (see <xref linkend="flexible-contexts"/>).
3437 With this flag the context of the instance declaration can each consist of arbitrary
3438 (well-kinded) assertions <literal>(C t1 ... tn)</literal> subject only to the
3442 The Paterson Conditions: for each assertion in the context
3444 <listitem><para>No type variable has more occurrences in the assertion than in the head</para></listitem>
3445 <listitem><para>The assertion has fewer constructors and variables (taken together
3446 and counting repetitions) than the head</para></listitem>
3450 <listitem><para>The Coverage Condition. For each functional dependency,
3451 <replaceable>tvs</replaceable><subscript>left</subscript> <literal>-></literal>
3452 <replaceable>tvs</replaceable><subscript>right</subscript>, of the class,
3453 every type variable in
3454 S(<replaceable>tvs</replaceable><subscript>right</subscript>) must appear in
3455 S(<replaceable>tvs</replaceable><subscript>left</subscript>), where S is the
3456 substitution mapping each type variable in the class declaration to the
3457 corresponding type in the instance declaration.
3460 These restrictions ensure that context reduction terminates: each reduction
3461 step makes the problem smaller by at least one
3462 constructor. Both the Paterson Conditions and the Coverage Condition are lifted
3463 if you give the <option>-XUndecidableInstances</option>
3464 flag (<xref linkend="undecidable-instances"/>).
3465 You can find lots of background material about the reason for these
3466 restrictions in the paper <ulink
3467 url="http://research.microsoft.com/%7Esimonpj/papers/fd%2Dchr/">
3468 Understanding functional dependencies via Constraint Handling Rules</ulink>.
3471 For example, these are OK:
3473 instance C Int [a] -- Multiple parameters
3474 instance Eq (S [a]) -- Structured type in head
3476 -- Repeated type variable in head
3477 instance C4 a a => C4 [a] [a]
3478 instance Stateful (ST s) (MutVar s)
3480 -- Head can consist of type variables only
3482 instance (Eq a, Show b) => C2 a b
3484 -- Non-type variables in context
3485 instance Show (s a) => Show (Sized s a)
3486 instance C2 Int a => C3 Bool [a]
3487 instance C2 Int a => C3 [a] b
3491 -- Context assertion no smaller than head
3492 instance C a => C a where ...
3493 -- (C b b) has more more occurrences of b than the head
3494 instance C b b => Foo [b] where ...
3499 The same restrictions apply to instances generated by
3500 <literal>deriving</literal> clauses. Thus the following is accepted:
3502 data MinHeap h a = H a (h a)
3505 because the derived instance
3507 instance (Show a, Show (h a)) => Show (MinHeap h a)
3509 conforms to the above rules.
3513 A useful idiom permitted by the above rules is as follows.
3514 If one allows overlapping instance declarations then it's quite
3515 convenient to have a "default instance" declaration that applies if
3516 something more specific does not:
3524 <sect3 id="undecidable-instances">
3525 <title>Undecidable instances</title>
3528 Sometimes even the rules of <xref linkend="instance-rules"/> are too onerous.
3529 For example, sometimes you might want to use the following to get the
3530 effect of a "class synonym":
3532 class (C1 a, C2 a, C3 a) => C a where { }
3534 instance (C1 a, C2 a, C3 a) => C a where { }
3536 This allows you to write shorter signatures:
3542 f :: (C1 a, C2 a, C3 a) => ...
3544 The restrictions on functional dependencies (<xref
3545 linkend="functional-dependencies"/>) are particularly troublesome.
3546 It is tempting to introduce type variables in the context that do not appear in
3547 the head, something that is excluded by the normal rules. For example:
3549 class HasConverter a b | a -> b where
3552 data Foo a = MkFoo a
3554 instance (HasConverter a b,Show b) => Show (Foo a) where
3555 show (MkFoo value) = show (convert value)
3557 This is dangerous territory, however. Here, for example, is a program that would make the