[project @ 2001-02-15 17:33:53 by simonmar]
[ghc-hetmet.git] / ghc / docs / users_guide / glasgow_exts.sgml
1 <Para>
2 <IndexTerm><Primary>language, GHC</Primary></IndexTerm>
3 <IndexTerm><Primary>extensions, GHC</Primary></IndexTerm>
4 As with all known Haskell systems, GHC implements some extensions to
5 the language.  To use them, you'll need to give a <Option>-fglasgow-exts</Option>
6 <IndexTerm><Primary>-fglasgow-exts option</Primary></IndexTerm> option.
7 </Para>
8
9 <Para>
10 Virtually all of the Glasgow extensions serve to give you access to
11 the underlying facilities with which we implement Haskell.  Thus, you
12 can get at the Raw Iron, if you are willing to write some non-standard
13 code at a more primitive level.  You need not be &ldquo;stuck&rdquo; on
14 performance because of the implementation costs of Haskell's
15 &ldquo;high-level&rdquo; features&mdash;you can always code &ldquo;under&rdquo; them.  In an extreme case, you can write all your time-critical code in C, and then just glue it together with Haskell!
16 </Para>
17
18 <Para>
19 Executive summary of our extensions:
20 </Para>
21
22 <Para>
23 <VariableList>
24
25 <VarListEntry>
26 <Term>Unboxed types and primitive operations:</Term>
27 <ListItem>
28 <Para>
29 You can get right down to the raw machine types and operations;
30 included in this are &ldquo;primitive arrays&rdquo; (direct access to Big Wads
31 of Bytes).  Please see <XRef LinkEnd="glasgow-unboxed"> and following.
32 </Para>
33 </ListItem>
34 </VarListEntry>
35
36 <VarListEntry>
37 <Term>Multi-parameter type classes:</Term>
38 <ListItem>
39 <Para>
40 GHC's type system supports extended type classes with multiple
41 parameters.  Please see <XRef LinkEnd="multi-param-type-classes">.
42 </Para>
43 </ListItem>
44 </VarListEntry>
45
46 <VarListEntry>
47 <Term>Local universal quantification:</Term>
48 <ListItem>
49 <Para>
50 GHC's type system supports explicit universal quantification in
51 constructor fields and function arguments.  This is useful for things
52 like defining <Literal>runST</Literal> from the state-thread world.  See <XRef LinkEnd="universal-quantification">.
53 </Para>
54 </ListItem>
55 </VarListEntry>
56
57 <VarListEntry>
58 <Term>Extistentially quantification in data types:</Term>
59 <ListItem>
60 <Para>
61 Some or all of the type variables in a datatype declaration may be
62 <Emphasis>existentially quantified</Emphasis>.  More details in <XRef LinkEnd="existential-quantification">.
63 </Para>
64 </ListItem>
65 </VarListEntry>
66
67 <VarListEntry>
68 <Term>Scoped type variables:</Term>
69 <ListItem>
70 <Para>
71 Scoped type variables enable the programmer to supply type signatures
72 for some nested declarations, where this would not be legal in Haskell
73 98.  Details in <XRef LinkEnd="scoped-type-variables">.
74 </Para>
75 </ListItem>
76 </VarListEntry>
77
78 <VarListEntry>
79 <Term>Pattern guards</Term>
80 <ListItem>
81 <Para>
82 Instead of being a boolean expression, a guard is a list of qualifiers, exactly as in a list comprehension. See <XRef LinkEnd="pattern-guards">.
83 </Para>
84 </ListItem>
85 </VarListEntry>
86
87 <VarListEntry>
88 <Term>Foreign calling:</Term>
89 <ListItem>
90 <Para>
91 Just what it sounds like.  We provide <Emphasis>lots</Emphasis> of rope that you
92 can dangle around your neck.  Please see <XRef LinkEnd="ffi">.
93 </Para>
94 </ListItem>
95 </VarListEntry>
96
97 <VarListEntry>
98 <Term>Pragmas</Term>
99 <ListItem>
100 <Para>
101 Pragmas are special instructions to the compiler placed in the source
102 file.  The pragmas GHC supports are described in <XRef LinkEnd="pragmas">.
103 </Para>
104 </ListItem>
105 </VarListEntry>
106
107 <VarListEntry>
108 <Term>Rewrite rules:</Term>
109 <ListItem>
110 <Para>
111 The programmer can specify rewrite rules as part of the source program
112 (in a pragma).  GHC applies these rewrite rules wherever it can.
113 Details in <XRef LinkEnd="rewrite-rules">.
114 </Para>
115 </ListItem>
116 </VarListEntry>
117
118 <VarListEntry>
119 <Term>Generic classes:</Term>
120 <ListItem>
121 <Para>
122 Generic class declarations allow you to define a class
123 whose methods say how to work over an arbitrary data type.
124 Then it's really easy to make any new type into an instance of
125 the class.  This generalises the rather ad-hoc "deriving" feature
126 of Haskell 98.
127 Details in <XRef LinkEnd="generic-classes">.
128 </Para>
129 </ListItem>
130 </VarListEntry>
131 </VariableList>
132 </Para>
133
134 <Para>
135 Before you get too carried away working at the lowest level (e.g.,
136 sloshing <Literal>MutableByteArray&num;</Literal>s around your
137 program), you may wish to check if there are libraries that provide a
138 &ldquo;Haskellised veneer&rdquo; over the features you want.  See
139 <xref linkend="book-hslibs">.
140 </Para>
141
142   <sect1 id="options-language">
143     <title>Language options</title>
144
145     <indexterm><primary>language</primary><secondary>option</secondary>
146     </indexterm>
147     <indexterm><primary>options</primary><secondary>language</secondary>
148     </indexterm>
149     <indexterm><primary>extensions</primary><secondary>options controlling</secondary>
150     </indexterm>
151
152     <para> These flags control what variation of the language are
153     permitted.  Leaving out all of them gives you standard Haskell
154     98.</Para>
155
156     <variablelist>
157
158       <varlistentry>
159         <term><option>-fglasgow-exts</option>:</term>
160         <indexterm><primary><option>-fglasgow-exts</option></primary></indexterm>
161         <listitem>
162           <para>This simultaneously enables all of the extensions to
163           Haskell 98 described in <xref
164           linkend="ghc-language-features">, except where otherwise
165           noted. </para>
166         </listitem>
167       </varlistentry>
168
169       <varlistentry>
170         <term><option>-fno-monomorphism-restriction</option>:</term>
171         <indexterm><primary><option>-fno-monomorphism-restriction</option></primary></indexterm>
172         <listitem>
173           <para> Switch off the Haskell 98 monomorphism restriction.
174           Independent of the <Option>-fglasgow-exts</Option>
175           flag. </para>
176         </listitem>
177       </varlistentry>
178
179       <varlistentry>
180         <term><option>-fallow-overlapping-instances</option></term>
181         <term><option>-fallow-undecidable-instances</option></term>
182         <term><option>-fcontext-stack</option></term>
183         <indexterm><primary><option>-fallow-overlapping-instances</option></primary></indexterm>
184         <indexterm><primary><option>-fallow-undecidable-instances</option></primary></indexterm>
185         <indexterm><primary><option>-fcontext-stack</option></primary></indexterm>
186         <listitem>
187           <para> See <XRef LinkEnd="instance-decls">.  Only relevant
188           if you also use <option>-fglasgow-exts</option>.</para>
189         </listitem>
190       </varlistentry>
191
192       <varlistentry>
193         <term><option>-fignore-asserts</option>:</term>
194         <indexterm><primary><option>-fignore-asserts</option></primary></indexterm>
195         <listitem>
196           <para>See <XRef LinkEnd="sec-assertions">.  Only relevant if
197           you also use <option>-fglasgow-exts</option>.</Para>
198         </listitem>
199       </varlistentry>
200
201       <varlistentry>
202         <term><option>-finline-phase</option></term>
203         <indexterm><primary><option>-finline-phase</option></primary></indexterm>
204         <listitem>
205           <para>See <XRef LinkEnd="rewrite-rules">.  Only relevant if
206           you also use <Option>-fglasgow-exts</Option>.</para>
207         </listitem>
208       </varlistentry>
209
210       <varlistentry>
211         <term><option>-fgenerics</option></term>
212         <indexterm><primary><option>-fgenerics</option></primary></indexterm>
213         <listitem>
214           <para>See <XRef LinkEnd="generic-classes">.  Independent of
215           <Option>-fglasgow-exts</Option>.</para>
216         </listitem>
217       </varlistentry>
218
219         <varlistentry>
220           <term><option>-fno-implicit-prelude</option></term>
221           <listitem>
222             <para><indexterm><primary>-fno-implicit-prelude
223             option</primary></indexterm> GHC normally imports
224             <filename>Prelude.hi</filename> files for you.  If you'd
225             rather it didn't, then give it a
226             <option>-fno-implicit-prelude</option> option.  The idea
227             is that you can then import a Prelude of your own.  (But
228             don't call it <literal>Prelude</literal>; the Haskell
229             module namespace is flat, and you must not conflict with
230             any Prelude module.)</para>
231
232             <para>Even though you have not imported the Prelude, all
233             the built-in syntax still refers to the built-in Haskell
234             Prelude types and values, as specified by the Haskell
235             Report.  For example, the type <literal>[Int]</literal>
236             still means <literal>Prelude.[] Int</literal>; tuples
237             continue to refer to the standard Prelude tuples; the
238             translation for list comprehensions continues to use
239             <literal>Prelude.map</literal> etc.</para>
240
241             <para> With one group of exceptions!  You may want to
242             define your own numeric class hierarchy.  It completely
243             defeats that purpose if the literal "1" means
244             "<literal>Prelude.fromInteger 1</literal>", which is what
245             the Haskell Report specifies.  So the
246             <option>-fno-implicit-prelude</option> flag causes the
247             following pieces of built-in syntax to refer to whatever
248             is in scope, not the Prelude versions:</para>
249
250             <itemizedlist>
251               <listitem>
252                 <para>Integer and fractional literals mean
253                 "<literal>fromInteger 1</literal>" and
254                 "<literal>fromRational 3.2</literal>", not the
255                 Prelude-qualified versions; both in expressions and in
256                 patterns.</para>
257               </listitem>
258
259               <listitem>
260                 <para>Negation (e.g. "<literal>- (f x)</literal>")
261                 means "<literal>negate (f x)</literal>" (not
262                 <literal>Prelude.negate</literal>).</para>
263               </listitem>
264
265               <listitem>
266                 <para>In an n+k pattern, the standard Prelude
267                 <literal>Ord</literal> class is used for comparison,
268                 but the necessary subtraction uses whatever
269                 "<literal>(-)</literal>" is in scope (not
270                 "<literal>Prelude.(-)</literal>").</para>
271               </listitem>
272             </itemizedlist>
273
274           </listitem>
275         </varlistentry>
276
277     </variablelist>
278   </sect1>
279
280 <Sect1 id="primitives">
281 <Title>Unboxed types and primitive operations
282 </Title>
283 <IndexTerm><Primary>PrelGHC module</Primary></IndexTerm>
284
285 <Para>
286 This module defines all the types which are primitive in Glasgow
287 Haskell, and the operations provided for them.
288 </Para>
289
290 <Sect2 id="glasgow-unboxed">
291 <Title>Unboxed types
292 </Title>
293
294 <Para>
295 <IndexTerm><Primary>Unboxed types (Glasgow extension)</Primary></IndexTerm>
296 </Para>
297
298 <para>Most types in GHC are <firstterm>boxed</firstterm>, which means
299 that values of that type are represented by a pointer to a heap
300 object.  The representation of a Haskell <literal>Int</literal>, for
301 example, is a two-word heap object.  An <firstterm>unboxed</firstterm>
302 type, however, is represented by the value itself, no pointers or heap
303 allocation are involved.
304 </para>
305
306 <Para>
307 Unboxed types correspond to the &ldquo;raw machine&rdquo; types you
308 would use in C: <Literal>Int&num;</Literal> (long int),
309 <Literal>Double&num;</Literal> (double), <Literal>Addr&num;</Literal>
310 (void *), etc.  The <Emphasis>primitive operations</Emphasis>
311 (PrimOps) on these types are what you might expect; e.g.,
312 <Literal>(+&num;)</Literal> is addition on
313 <Literal>Int&num;</Literal>s, and is the machine-addition that we all
314 know and love&mdash;usually one instruction.
315 </Para>
316
317 <Para>
318 Primitive (unboxed) types cannot be defined in Haskell, and are
319 therefore built into the language and compiler.  Primitive types are
320 always unlifted; that is, a value of a primitive type cannot be
321 bottom.  We use the convention that primitive types, values, and
322 operations have a <Literal>&num;</Literal> suffix.
323 </Para>
324
325 <Para>
326 Primitive values are often represented by a simple bit-pattern, such
327 as <Literal>Int&num;</Literal>, <Literal>Float&num;</Literal>,
328 <Literal>Double&num;</Literal>.  But this is not necessarily the case:
329 a primitive value might be represented by a pointer to a
330 heap-allocated object.  Examples include
331 <Literal>Array&num;</Literal>, the type of primitive arrays.  A
332 primitive array is heap-allocated because it is too big a value to fit
333 in a register, and would be too expensive to copy around; in a sense,
334 it is accidental that it is represented by a pointer.  If a pointer
335 represents a primitive value, then it really does point to that value:
336 no unevaluated thunks, no indirections&hellip;nothing can be at the
337 other end of the pointer than the primitive value.
338 </Para>
339
340 <Para>
341 There are some restrictions on the use of primitive types, the main
342 one being that you can't pass a primitive value to a polymorphic
343 function or store one in a polymorphic data type.  This rules out
344 things like <Literal>[Int&num;]</Literal> (i.e. lists of primitive
345 integers).  The reason for this restriction is that polymorphic
346 arguments and constructor fields are assumed to be pointers: if an
347 unboxed integer is stored in one of these, the garbage collector would
348 attempt to follow it, leading to unpredictable space leaks.  Or a
349 <Function>seq</Function> operation on the polymorphic component may
350 attempt to dereference the pointer, with disastrous results.  Even
351 worse, the unboxed value might be larger than a pointer
352 (<Literal>Double&num;</Literal> for instance).
353 </Para>
354
355 <Para>
356 Nevertheless, A numerically-intensive program using unboxed types can
357 go a <Emphasis>lot</Emphasis> faster than its &ldquo;standard&rdquo;
358 counterpart&mdash;we saw a threefold speedup on one example.
359 </Para>
360
361 </sect2>
362
363 <Sect2 id="unboxed-tuples">
364 <Title>Unboxed Tuples
365 </Title>
366
367 <Para>
368 Unboxed tuples aren't really exported by <Literal>PrelGHC</Literal>,
369 they're available by default with <Option>-fglasgow-exts</Option>.  An
370 unboxed tuple looks like this:
371 </Para>
372
373 <Para>
374
375 <ProgramListing>
376 (# e_1, ..., e_n #)
377 </ProgramListing>
378
379 </Para>
380
381 <Para>
382 where <Literal>e&lowbar;1..e&lowbar;n</Literal> are expressions of any
383 type (primitive or non-primitive).  The type of an unboxed tuple looks
384 the same.
385 </Para>
386
387 <Para>
388 Unboxed tuples are used for functions that need to return multiple
389 values, but they avoid the heap allocation normally associated with
390 using fully-fledged tuples.  When an unboxed tuple is returned, the
391 components are put directly into registers or on the stack; the
392 unboxed tuple itself does not have a composite representation.  Many
393 of the primitive operations listed in this section return unboxed
394 tuples.
395 </Para>
396
397 <Para>
398 There are some pretty stringent restrictions on the use of unboxed tuples:
399 </Para>
400
401 <Para>
402
403 <ItemizedList>
404 <ListItem>
405
406 <Para>
407  Unboxed tuple types are subject to the same restrictions as
408 other unboxed types; i.e. they may not be stored in polymorphic data
409 structures or passed to polymorphic functions.
410
411 </Para>
412 </ListItem>
413 <ListItem>
414
415 <Para>
416  Unboxed tuples may only be constructed as the direct result of
417 a function, and may only be deconstructed with a <Literal>case</Literal> expression.
418 eg. the following are valid:
419
420
421 <ProgramListing>
422 f x y = (# x+1, y-1 #)
423 g x = case f x x of { (# a, b #) -&#62; a + b }
424 </ProgramListing>
425
426
427 but the following are invalid:
428
429
430 <ProgramListing>
431 f x y = g (# x, y #)
432 g (# x, y #) = x + y
433 </ProgramListing>
434
435
436 </Para>
437 </ListItem>
438 <ListItem>
439
440 <Para>
441  No variable can have an unboxed tuple type.  This is illegal:
442
443
444 <ProgramListing>
445 f :: (# Int, Int #) -&#62; (# Int, Int #)
446 f x = x
447 </ProgramListing>
448
449
450 because <VarName>x</VarName> has an unboxed tuple type.
451
452 </Para>
453 </ListItem>
454
455 </ItemizedList>
456
457 </Para>
458
459 <Para>
460 Note: we may relax some of these restrictions in the future.
461 </Para>
462
463 <Para>
464 The <Literal>IO</Literal> and <Literal>ST</Literal> monads use unboxed
465 tuples to avoid unnecessary allocation during sequences of operations.
466 </Para>
467
468 </Sect2>
469
470 <Sect2>
471 <Title>Character and numeric types</Title>
472
473 <IndexTerm><Primary>character types, primitive</Primary></IndexTerm>
474 <IndexTerm><Primary>numeric types, primitive</Primary></IndexTerm>
475 <IndexTerm><Primary>integer types, primitive</Primary></IndexTerm>
476 <IndexTerm><Primary>floating point types, primitive</Primary></IndexTerm>
477 <Para>
478 There are the following obvious primitive types:
479 </Para>
480
481 <ProgramListing>
482 type Char#
483 type Int#
484 type Word#
485 type Addr#
486 type Float#
487 type Double#
488 type Int64#
489 type Word64#
490 </ProgramListing>
491
492 <IndexTerm><Primary><literal>Char&num;</literal></Primary></IndexTerm>
493 <IndexTerm><Primary><literal>Int&num;</literal></Primary></IndexTerm>
494 <IndexTerm><Primary><literal>Word&num;</literal></Primary></IndexTerm>
495 <IndexTerm><Primary><literal>Addr&num;</literal></Primary></IndexTerm>
496 <IndexTerm><Primary><literal>Float&num;</literal></Primary></IndexTerm>
497 <IndexTerm><Primary><literal>Double&num;</literal></Primary></IndexTerm>
498 <IndexTerm><Primary><literal>Int64&num;</literal></Primary></IndexTerm>
499 <IndexTerm><Primary><literal>Word64&num;</literal></Primary></IndexTerm>
500
501 <Para>
502 If you really want to know their exact equivalents in C, see
503 <Filename>ghc/includes/StgTypes.h</Filename> in the GHC source tree.
504 </Para>
505
506 <Para>
507 Literals for these types may be written as follows:
508 </Para>
509
510 <Para>
511
512 <ProgramListing>
513 1#              an Int#
514 1.2#            a Float#
515 1.34##          a Double#
516 'a'#            a Char#; for weird characters, use e.g. '\o&#60;octal&#62;'#
517 "a"#            an Addr# (a `char *'); only characters '\0'..'\255' allowed
518 </ProgramListing>
519
520 <IndexTerm><Primary>literals, primitive</Primary></IndexTerm>
521 <IndexTerm><Primary>constants, primitive</Primary></IndexTerm>
522 <IndexTerm><Primary>numbers, primitive</Primary></IndexTerm>
523 </Para>
524
525 </Sect2>
526
527 <Sect2>
528 <Title>Comparison operations</Title>
529
530 <Para>
531 <IndexTerm><Primary>comparisons, primitive</Primary></IndexTerm>
532 <IndexTerm><Primary>operators, comparison</Primary></IndexTerm>
533 </Para>
534
535 <Para>
536
537 <ProgramListing>
538 {&#62;,&#62;=,==,/=,&#60;,&#60;=}# :: Int# -&#62; Int# -&#62; Bool
539
540 {gt,ge,eq,ne,lt,le}Char# :: Char# -&#62; Char# -&#62; Bool
541     -- ditto for Word# and Addr#
542 </ProgramListing>
543
544 <IndexTerm><Primary><literal>&#62;&num;</literal></Primary></IndexTerm>
545 <IndexTerm><Primary><literal>&#62;=&num;</literal></Primary></IndexTerm>
546 <IndexTerm><Primary><literal>==&num;</literal></Primary></IndexTerm>
547 <IndexTerm><Primary><literal>/=&num;</literal></Primary></IndexTerm>
548 <IndexTerm><Primary><literal>&#60;&num;</literal></Primary></IndexTerm>
549 <IndexTerm><Primary><literal>&#60;=&num;</literal></Primary></IndexTerm>
550 <IndexTerm><Primary><literal>gt&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
551 <IndexTerm><Primary><literal>ge&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
552 <IndexTerm><Primary><literal>eq&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
553 <IndexTerm><Primary><literal>ne&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
554 <IndexTerm><Primary><literal>lt&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
555 <IndexTerm><Primary><literal>le&lcub;Char,Word,Addr&rcub;&num;</literal></Primary></IndexTerm>
556 </Para>
557
558 </Sect2>
559
560 <Sect2>
561 <Title>Primitive-character operations</Title>
562
563 <Para>
564 <IndexTerm><Primary>characters, primitive operations</Primary></IndexTerm>
565 <IndexTerm><Primary>operators, primitive character</Primary></IndexTerm>
566 </Para>
567
568 <Para>
569
570 <ProgramListing>
571 ord# :: Char# -&#62; Int#
572 chr# :: Int# -&#62; Char#
573 </ProgramListing>
574
575 <IndexTerm><Primary><literal>ord&num;</literal></Primary></IndexTerm>
576 <IndexTerm><Primary><literal>chr&num;</literal></Primary></IndexTerm>
577 </Para>
578
579 </Sect2>
580
581 <Sect2>
582 <Title>Primitive-<Literal>Int</Literal> operations</Title>
583
584 <Para>
585 <IndexTerm><Primary>integers, primitive operations</Primary></IndexTerm>
586 <IndexTerm><Primary>operators, primitive integer</Primary></IndexTerm>
587 </Para>
588
589 <Para>
590
591 <ProgramListing>
592 {+,-,*,quotInt,remInt,gcdInt}# :: Int# -&#62; Int# -&#62; Int#
593 negateInt# :: Int# -&#62; Int#
594
595 iShiftL#, iShiftRA#, iShiftRL# :: Int# -&#62; Int# -&#62; Int#
596         -- shift left, right arithmetic, right logical
597
598 addIntC#, subIntC#, mulIntC# :: Int# -> Int# -> (# Int#, Int# #)
599         -- add, subtract, multiply with carry
600 </ProgramListing>
601
602 <IndexTerm><Primary><literal>+&num;</literal></Primary></IndexTerm>
603 <IndexTerm><Primary><literal>-&num;</literal></Primary></IndexTerm>
604 <IndexTerm><Primary><literal>*&num;</literal></Primary></IndexTerm>
605 <IndexTerm><Primary><literal>quotInt&num;</literal></Primary></IndexTerm>
606 <IndexTerm><Primary><literal>remInt&num;</literal></Primary></IndexTerm>
607 <IndexTerm><Primary><literal>gcdInt&num;</literal></Primary></IndexTerm>
608 <IndexTerm><Primary><literal>iShiftL&num;</literal></Primary></IndexTerm>
609 <IndexTerm><Primary><literal>iShiftRA&num;</literal></Primary></IndexTerm>
610 <IndexTerm><Primary><literal>iShiftRL&num;</literal></Primary></IndexTerm>
611 <IndexTerm><Primary><literal>addIntC&num;</literal></Primary></IndexTerm>
612 <IndexTerm><Primary><literal>subIntC&num;</literal></Primary></IndexTerm>
613 <IndexTerm><Primary><literal>mulIntC&num;</literal></Primary></IndexTerm>
614 <IndexTerm><Primary>shift operations, integer</Primary></IndexTerm>
615 </Para>
616
617 <Para>
618 <Emphasis>Note:</Emphasis> No error/overflow checking!
619 </Para>
620
621 </Sect2>
622
623 <Sect2>
624 <Title>Primitive-<Literal>Double</Literal> and <Literal>Float</Literal> operations</Title>
625
626 <Para>
627 <IndexTerm><Primary>floating point numbers, primitive</Primary></IndexTerm>
628 <IndexTerm><Primary>operators, primitive floating point</Primary></IndexTerm>
629 </Para>
630
631 <Para>
632
633 <ProgramListing>
634 {+,-,*,/}##         :: Double# -&#62; Double# -&#62; Double#
635 {&#60;,&#60;=,==,/=,&#62;=,&#62;}## :: Double# -&#62; Double# -&#62; Bool
636 negateDouble#       :: Double# -&#62; Double#
637 double2Int#         :: Double# -&#62; Int#
638 int2Double#         :: Int#    -&#62; Double#
639
640 {plus,minux,times,divide}Float# :: Float# -&#62; Float# -&#62; Float#
641 {gt,ge,eq,ne,lt,le}Float# :: Float# -&#62; Float# -&#62; Bool
642 negateFloat#        :: Float# -&#62; Float#
643 float2Int#          :: Float# -&#62; Int#
644 int2Float#          :: Int#   -&#62; Float#
645 </ProgramListing>
646
647 </Para>
648
649 <Para>
650 <IndexTerm><Primary><literal>+&num;&num;</literal></Primary></IndexTerm>
651 <IndexTerm><Primary><literal>-&num;&num;</literal></Primary></IndexTerm>
652 <IndexTerm><Primary><literal>*&num;&num;</literal></Primary></IndexTerm>
653 <IndexTerm><Primary><literal>/&num;&num;</literal></Primary></IndexTerm>
654 <IndexTerm><Primary><literal>&#60;&num;&num;</literal></Primary></IndexTerm>
655 <IndexTerm><Primary><literal>&#60;=&num;&num;</literal></Primary></IndexTerm>
656 <IndexTerm><Primary><literal>==&num;&num;</literal></Primary></IndexTerm>
657 <IndexTerm><Primary><literal>=/&num;&num;</literal></Primary></IndexTerm>
658 <IndexTerm><Primary><literal>&#62;=&num;&num;</literal></Primary></IndexTerm>
659 <IndexTerm><Primary><literal>&#62;&num;&num;</literal></Primary></IndexTerm>
660 <IndexTerm><Primary><literal>negateDouble&num;</literal></Primary></IndexTerm>
661 <IndexTerm><Primary><literal>double2Int&num;</literal></Primary></IndexTerm>
662 <IndexTerm><Primary><literal>int2Double&num;</literal></Primary></IndexTerm>
663 </Para>
664
665 <Para>
666 <IndexTerm><Primary><literal>plusFloat&num;</literal></Primary></IndexTerm>
667 <IndexTerm><Primary><literal>minusFloat&num;</literal></Primary></IndexTerm>
668 <IndexTerm><Primary><literal>timesFloat&num;</literal></Primary></IndexTerm>
669 <IndexTerm><Primary><literal>divideFloat&num;</literal></Primary></IndexTerm>
670 <IndexTerm><Primary><literal>gtFloat&num;</literal></Primary></IndexTerm>
671 <IndexTerm><Primary><literal>geFloat&num;</literal></Primary></IndexTerm>
672 <IndexTerm><Primary><literal>eqFloat&num;</literal></Primary></IndexTerm>
673 <IndexTerm><Primary><literal>neFloat&num;</literal></Primary></IndexTerm>
674 <IndexTerm><Primary><literal>ltFloat&num;</literal></Primary></IndexTerm>
675 <IndexTerm><Primary><literal>leFloat&num;</literal></Primary></IndexTerm>
676 <IndexTerm><Primary><literal>negateFloat&num;</literal></Primary></IndexTerm>
677 <IndexTerm><Primary><literal>float2Int&num;</literal></Primary></IndexTerm>
678 <IndexTerm><Primary><literal>int2Float&num;</literal></Primary></IndexTerm>
679 </Para>
680
681 <Para>
682 And a full complement of trigonometric functions:
683 </Para>
684
685 <Para>
686
687 <ProgramListing>
688 expDouble#      :: Double# -&#62; Double#
689 logDouble#      :: Double# -&#62; Double#
690 sqrtDouble#     :: Double# -&#62; Double#
691 sinDouble#      :: Double# -&#62; Double#
692 cosDouble#      :: Double# -&#62; Double#
693 tanDouble#      :: Double# -&#62; Double#
694 asinDouble#     :: Double# -&#62; Double#
695 acosDouble#     :: Double# -&#62; Double#
696 atanDouble#     :: Double# -&#62; Double#
697 sinhDouble#     :: Double# -&#62; Double#
698 coshDouble#     :: Double# -&#62; Double#
699 tanhDouble#     :: Double# -&#62; Double#
700 powerDouble#    :: Double# -&#62; Double# -&#62; Double#
701 </ProgramListing>
702
703 <IndexTerm><Primary>trigonometric functions, primitive</Primary></IndexTerm>
704 </Para>
705
706 <Para>
707 similarly for <Literal>Float&num;</Literal>.
708 </Para>
709
710 <Para>
711 There are two coercion functions for <Literal>Float&num;</Literal>/<Literal>Double&num;</Literal>:
712 </Para>
713
714 <Para>
715
716 <ProgramListing>
717 float2Double#   :: Float# -&#62; Double#
718 double2Float#   :: Double# -&#62; Float#
719 </ProgramListing>
720
721 <IndexTerm><Primary><literal>float2Double&num;</literal></Primary></IndexTerm>
722 <IndexTerm><Primary><literal>double2Float&num;</literal></Primary></IndexTerm>
723 </Para>
724
725 <Para>
726 The primitive version of <Function>decodeDouble</Function>
727 (<Function>encodeDouble</Function> is implemented as an external C
728 function):
729 </Para>
730
731 <Para>
732
733 <ProgramListing>
734 decodeDouble#   :: Double# -&#62; PrelNum.ReturnIntAndGMP
735 </ProgramListing>
736
737 <IndexTerm><Primary><literal>encodeDouble&num;</literal></Primary></IndexTerm>
738 <IndexTerm><Primary><literal>decodeDouble&num;</literal></Primary></IndexTerm>
739 </Para>
740
741 <Para>
742 (And the same for <Literal>Float&num;</Literal>s.)
743 </Para>
744
745 </Sect2>
746
747 <Sect2 id="integer-operations">
748 <Title>Operations on/for <Literal>Integers</Literal> (interface to GMP)
749 </Title>
750
751 <Para>
752 <IndexTerm><Primary>arbitrary precision integers</Primary></IndexTerm>
753 <IndexTerm><Primary>Integer, operations on</Primary></IndexTerm>
754 </Para>
755
756 <Para>
757 We implement <Literal>Integers</Literal> (arbitrary-precision
758 integers) using the GNU multiple-precision (GMP) package (version
759 2.0.2).
760 </Para>
761
762 <Para>
763 The data type for <Literal>Integer</Literal> is either a small
764 integer, represented by an <Literal>Int</Literal>, or a large integer
765 represented using the pieces required by GMP's
766 <Literal>MP&lowbar;INT</Literal> in <Filename>gmp.h</Filename> (see
767 <Filename>gmp.info</Filename> in
768 <Filename>ghc/includes/runtime/gmp</Filename>).  It comes out as:
769 </Para>
770
771 <Para>
772
773 <ProgramListing>
774 data Integer = S# Int#             -- small integers
775              | J# Int# ByteArray#  -- large integers
776 </ProgramListing>
777
778 <IndexTerm><Primary>Integer type</Primary></IndexTerm> The primitive
779 ops to support large <Literal>Integers</Literal> use the
780 &ldquo;pieces&rdquo; of the representation, and are as follows:
781 </Para>
782
783 <Para>
784
785 <ProgramListing>
786 negateInteger#  :: Int# -&#62; ByteArray# -&#62; Integer
787
788 {plus,minus,times}Integer#, gcdInteger#, 
789   quotInteger#, remInteger#, divExactInteger#
790         :: Int# -> ByteArray#
791         -> Int# -> ByteArray#
792         -> (# Int#, ByteArray# #)
793
794 cmpInteger# 
795         :: Int# -> ByteArray#
796         -> Int# -> ByteArray#
797         -> Int# -- -1 for &#60;; 0 for ==; +1 for >
798
799 cmpIntegerInt# 
800         :: Int# -> ByteArray#
801         -> Int#
802         -> Int# -- -1 for &#60;; 0 for ==; +1 for >
803
804 gcdIntegerInt# :: 
805         :: Int# -> ByteArray#
806         -> Int#
807         -> Int#
808
809 divModInteger#, quotRemInteger#
810         :: Int# -> ByteArray#
811         -> Int# -> ByteArray#
812         -> (# Int#, ByteArray#,
813                   Int#, ByteArray# #)
814
815 integer2Int# :: Int# -> ByteArray# -> Int#
816
817 int2Integer#  :: Int#  -> Integer -- NB: no error-checking on these two!
818 word2Integer# :: Word# -> Integer
819
820 addr2Integer# :: Addr# -> Integer
821         -- the Addr# is taken to be a `char *' string
822         -- to be converted into an Integer.
823 </ProgramListing>
824
825 <IndexTerm><Primary><literal>negateInteger&num;</literal></Primary></IndexTerm>
826 <IndexTerm><Primary><literal>plusInteger&num;</literal></Primary></IndexTerm>
827 <IndexTerm><Primary><literal>minusInteger&num;</literal></Primary></IndexTerm>
828 <IndexTerm><Primary><literal>timesInteger&num;</literal></Primary></IndexTerm>
829 <IndexTerm><Primary><literal>quotInteger&num;</literal></Primary></IndexTerm>
830 <IndexTerm><Primary><literal>remInteger&num;</literal></Primary></IndexTerm>
831 <IndexTerm><Primary><literal>gcdInteger&num;</literal></Primary></IndexTerm>
832 <IndexTerm><Primary><literal>gcdIntegerInt&num;</literal></Primary></IndexTerm>
833 <IndexTerm><Primary><literal>divExactInteger&num;</literal></Primary></IndexTerm>
834 <IndexTerm><Primary><literal>cmpInteger&num;</literal></Primary></IndexTerm>
835 <IndexTerm><Primary><literal>divModInteger&num;</literal></Primary></IndexTerm>
836 <IndexTerm><Primary><literal>quotRemInteger&num;</literal></Primary></IndexTerm>
837 <IndexTerm><Primary><literal>integer2Int&num;</literal></Primary></IndexTerm>
838 <IndexTerm><Primary><literal>int2Integer&num;</literal></Primary></IndexTerm>
839 <IndexTerm><Primary><literal>word2Integer&num;</literal></Primary></IndexTerm>
840 <IndexTerm><Primary><literal>addr2Integer&num;</literal></Primary></IndexTerm>
841 </Para>
842
843 </Sect2>
844
845 <Sect2>
846 <Title>Words and addresses</Title>
847
848 <Para>
849 <IndexTerm><Primary>word, primitive type</Primary></IndexTerm>
850 <IndexTerm><Primary>address, primitive type</Primary></IndexTerm>
851 <IndexTerm><Primary>unsigned integer, primitive type</Primary></IndexTerm>
852 <IndexTerm><Primary>pointer, primitive type</Primary></IndexTerm>
853 </Para>
854
855 <Para>
856 A <Literal>Word&num;</Literal> is used for bit-twiddling operations.
857 It is the same size as an <Literal>Int&num;</Literal>, but has no sign
858 nor any arithmetic operations.
859
860 <ProgramListing>
861 type Word#      -- Same size/etc as Int# but *unsigned*
862 type Addr#      -- A pointer from outside the "Haskell world" (from C, probably);
863                 -- described under "arrays"
864 </ProgramListing>
865
866 <IndexTerm><Primary><literal>Word&num;</literal></Primary></IndexTerm>
867 <IndexTerm><Primary><literal>Addr&num;</literal></Primary></IndexTerm>
868 </Para>
869
870 <Para>
871 <Literal>Word&num;</Literal>s and <Literal>Addr&num;</Literal>s have
872 the usual comparison operations.  Other
873 unboxed-<Literal>Word</Literal> ops (bit-twiddling and coercions):
874 </Para>
875
876 <Para>
877
878 <ProgramListing>
879 {gt,ge,eq,ne,lt,le}Word# :: Word# -> Word# -> Bool
880
881 and#, or#, xor# :: Word# -> Word# -> Word#
882         -- standard bit ops.
883
884 quotWord#, remWord# :: Word# -> Word# -> Word#
885         -- word (i.e. unsigned) versions are different from int
886         -- versions, so we have to provide these explicitly.
887
888 not# :: Word# -> Word#
889
890 shiftL#, shiftRL# :: Word# -> Int# -> Word#
891         -- shift left, right logical
892
893 int2Word#       :: Int#  -> Word# -- just a cast, really
894 word2Int#       :: Word# -> Int#
895 </ProgramListing>
896
897 <IndexTerm><Primary>bit operations, Word and Addr</Primary></IndexTerm>
898 <IndexTerm><Primary><literal>gtWord&num;</literal></Primary></IndexTerm>
899 <IndexTerm><Primary><literal>geWord&num;</literal></Primary></IndexTerm>
900 <IndexTerm><Primary><literal>eqWord&num;</literal></Primary></IndexTerm>
901 <IndexTerm><Primary><literal>neWord&num;</literal></Primary></IndexTerm>
902 <IndexTerm><Primary><literal>ltWord&num;</literal></Primary></IndexTerm>
903 <IndexTerm><Primary><literal>leWord&num;</literal></Primary></IndexTerm>
904 <IndexTerm><Primary><literal>and&num;</literal></Primary></IndexTerm>
905 <IndexTerm><Primary><literal>or&num;</literal></Primary></IndexTerm>
906 <IndexTerm><Primary><literal>xor&num;</literal></Primary></IndexTerm>
907 <IndexTerm><Primary><literal>not&num;</literal></Primary></IndexTerm>
908 <IndexTerm><Primary><literal>quotWord&num;</literal></Primary></IndexTerm>
909 <IndexTerm><Primary><literal>remWord&num;</literal></Primary></IndexTerm>
910 <IndexTerm><Primary><literal>shiftL&num;</literal></Primary></IndexTerm>
911 <IndexTerm><Primary><literal>shiftRA&num;</literal></Primary></IndexTerm>
912 <IndexTerm><Primary><literal>shiftRL&num;</literal></Primary></IndexTerm>
913 <IndexTerm><Primary><literal>int2Word&num;</literal></Primary></IndexTerm>
914 <IndexTerm><Primary><literal>word2Int&num;</literal></Primary></IndexTerm>
915 </Para>
916
917 <Para>
918 Unboxed-<Literal>Addr</Literal> ops (C casts, really):
919
920 <ProgramListing>
921 {gt,ge,eq,ne,lt,le}Addr# :: Addr# -> Addr# -> Bool
922
923 int2Addr#       :: Int#  -> Addr#
924 addr2Int#       :: Addr# -> Int#
925 addr2Integer#   :: Addr# -> (# Int#, ByteArray# #)
926 </ProgramListing>
927
928 <IndexTerm><Primary><literal>gtAddr&num;</literal></Primary></IndexTerm>
929 <IndexTerm><Primary><literal>geAddr&num;</literal></Primary></IndexTerm>
930 <IndexTerm><Primary><literal>eqAddr&num;</literal></Primary></IndexTerm>
931 <IndexTerm><Primary><literal>neAddr&num;</literal></Primary></IndexTerm>
932 <IndexTerm><Primary><literal>ltAddr&num;</literal></Primary></IndexTerm>
933 <IndexTerm><Primary><literal>leAddr&num;</literal></Primary></IndexTerm>
934 <IndexTerm><Primary><literal>int2Addr&num;</literal></Primary></IndexTerm>
935 <IndexTerm><Primary><literal>addr2Int&num;</literal></Primary></IndexTerm>
936 <IndexTerm><Primary><literal>addr2Integer&num;</literal></Primary></IndexTerm>
937 </Para>
938
939 <Para>
940 The casts between <Literal>Int&num;</Literal>,
941 <Literal>Word&num;</Literal> and <Literal>Addr&num;</Literal>
942 correspond to null operations at the machine level, but are required
943 to keep the Haskell type checker happy.
944 </Para>
945
946 <Para>
947 Operations for indexing off of C pointers
948 (<Literal>Addr&num;</Literal>s) to snatch values are listed under
949 &ldquo;arrays&rdquo;.
950 </Para>
951
952 </Sect2>
953
954 <Sect2>
955 <Title>Arrays</Title>
956
957 <Para>
958 <IndexTerm><Primary>arrays, primitive</Primary></IndexTerm>
959 </Para>
960
961 <Para>
962 The type <Literal>Array&num; elt</Literal> is the type of primitive,
963 unpointed arrays of values of type <Literal>elt</Literal>.
964 </Para>
965
966 <Para>
967
968 <ProgramListing>
969 type Array# elt
970 </ProgramListing>
971
972 <IndexTerm><Primary><literal>Array&num;</literal></Primary></IndexTerm>
973 </Para>
974
975 <Para>
976 <Literal>Array&num;</Literal> is more primitive than a Haskell
977 array&mdash;indeed, the Haskell <Literal>Array</Literal> interface is
978 implemented using <Literal>Array&num;</Literal>&mdash;in that an
979 <Literal>Array&num;</Literal> is indexed only by
980 <Literal>Int&num;</Literal>s, starting at zero.  It is also more
981 primitive by virtue of being unboxed.  That doesn't mean that it isn't
982 a heap-allocated object&mdash;of course, it is.  Rather, being unboxed
983 means that it is represented by a pointer to the array itself, and not
984 to a thunk which will evaluate to the array (or to bottom).  The
985 components of an <Literal>Array&num;</Literal> are themselves boxed.
986 </Para>
987
988 <Para>
989 The type <Literal>ByteArray&num;</Literal> is similar to
990 <Literal>Array&num;</Literal>, except that it contains just a string
991 of (non-pointer) bytes.
992 </Para>
993
994 <Para>
995
996 <ProgramListing>
997 type ByteArray#
998 </ProgramListing>
999
1000 <IndexTerm><Primary><literal>ByteArray&num;</literal></Primary></IndexTerm>
1001 </Para>
1002
1003 <Para>
1004 Arrays of these types are useful when a Haskell program wishes to
1005 construct a value to pass to a C procedure. It is also possible to use
1006 them to build (say) arrays of unboxed characters for internal use in a
1007 Haskell program.  Given these uses, <Literal>ByteArray&num;</Literal>
1008 is deliberately a bit vague about the type of its components.
1009 Operations are provided to extract values of type
1010 <Literal>Char&num;</Literal>, <Literal>Int&num;</Literal>,
1011 <Literal>Float&num;</Literal>, <Literal>Double&num;</Literal>, and
1012 <Literal>Addr&num;</Literal> from arbitrary offsets within a
1013 <Literal>ByteArray&num;</Literal>.  (For type
1014 <Literal>Foo&num;</Literal>, the $i$th offset gets you the $i$th
1015 <Literal>Foo&num;</Literal>, not the <Literal>Foo&num;</Literal> at
1016 byte-position $i$.  Mumble.)  (If you want a
1017 <Literal>Word&num;</Literal>, grab an <Literal>Int&num;</Literal>,
1018 then coerce it.)
1019 </Para>
1020
1021 <Para>
1022 Lastly, we have static byte-arrays, of type
1023 <Literal>Addr&num;</Literal> &lsqb;mentioned previously].  (Remember
1024 the duality between arrays and pointers in C.)  Arrays of this types
1025 are represented by a pointer to an array in the world outside Haskell,
1026 so this pointer is not followed by the garbage collector.  In other
1027 respects they are just like <Literal>ByteArray&num;</Literal>.  They
1028 are only needed in order to pass values from C to Haskell.
1029 </Para>
1030
1031 </Sect2>
1032
1033 <Sect2>
1034 <Title>Reading and writing</Title>
1035
1036 <Para>
1037 Primitive arrays are linear, and indexed starting at zero.
1038 </Para>
1039
1040 <Para>
1041 The size and indices of a <Literal>ByteArray&num;</Literal>, <Literal>Addr&num;</Literal>, and
1042 <Literal>MutableByteArray&num;</Literal> are all in bytes.  It's up to the program to
1043 calculate the correct byte offset from the start of the array.  This
1044 allows a <Literal>ByteArray&num;</Literal> to contain a mixture of values of different
1045 type, which is often needed when preparing data for and unpicking
1046 results from C.  (Umm&hellip;not true of indices&hellip;WDP 95/09)
1047 </Para>
1048
1049 <Para>
1050 <Emphasis>Should we provide some <Literal>sizeOfDouble&num;</Literal> constants?</Emphasis>
1051 </Para>
1052
1053 <Para>
1054 Out-of-range errors on indexing should be caught by the code which
1055 uses the primitive operation; the primitive operations themselves do
1056 <Emphasis>not</Emphasis> check for out-of-range indexes. The intention is that the
1057 primitive ops compile to one machine instruction or thereabouts.
1058 </Para>
1059
1060 <Para>
1061 We use the terms &ldquo;reading&rdquo; and &ldquo;writing&rdquo; to refer to accessing
1062 <Emphasis>mutable</Emphasis> arrays (see <XRef LinkEnd="sect-mutable">), and
1063 &ldquo;indexing&rdquo; to refer to reading a value from an <Emphasis>immutable</Emphasis>
1064 array.
1065 </Para>
1066
1067 <Para>
1068 Immutable byte arrays are straightforward to index (all indices in bytes):
1069
1070 <ProgramListing>
1071 indexCharArray#   :: ByteArray# -> Int# -> Char#
1072 indexIntArray#    :: ByteArray# -> Int# -> Int#
1073 indexAddrArray#   :: ByteArray# -> Int# -> Addr#
1074 indexFloatArray#  :: ByteArray# -> Int# -> Float#
1075 indexDoubleArray# :: ByteArray# -> Int# -> Double#
1076
1077 indexCharOffAddr#   :: Addr# -> Int# -> Char#
1078 indexIntOffAddr#    :: Addr# -> Int# -> Int#
1079 indexFloatOffAddr#  :: Addr# -> Int# -> Float#
1080 indexDoubleOffAddr# :: Addr# -> Int# -> Double#
1081 indexAddrOffAddr#   :: Addr# -> Int# -> Addr#
1082  -- Get an Addr# from an Addr# offset
1083 </ProgramListing>
1084
1085 <IndexTerm><Primary><literal>indexCharArray&num;</literal></Primary></IndexTerm>
1086 <IndexTerm><Primary><literal>indexIntArray&num;</literal></Primary></IndexTerm>
1087 <IndexTerm><Primary><literal>indexAddrArray&num;</literal></Primary></IndexTerm>
1088 <IndexTerm><Primary><literal>indexFloatArray&num;</literal></Primary></IndexTerm>
1089 <IndexTerm><Primary><literal>indexDoubleArray&num;</literal></Primary></IndexTerm>
1090 <IndexTerm><Primary><literal>indexCharOffAddr&num;</literal></Primary></IndexTerm>
1091 <IndexTerm><Primary><literal>indexIntOffAddr&num;</literal></Primary></IndexTerm>
1092 <IndexTerm><Primary><literal>indexFloatOffAddr&num;</literal></Primary></IndexTerm>
1093 <IndexTerm><Primary><literal>indexDoubleOffAddr&num;</literal></Primary></IndexTerm>
1094 <IndexTerm><Primary><literal>indexAddrOffAddr&num;</literal></Primary></IndexTerm>
1095 </Para>
1096
1097 <Para>
1098 The last of these, <Function>indexAddrOffAddr&num;</Function>, extracts an <Literal>Addr&num;</Literal> using an offset
1099 from another <Literal>Addr&num;</Literal>, thereby providing the ability to follow a chain of
1100 C pointers.
1101 </Para>
1102
1103 <Para>
1104 Something a bit more interesting goes on when indexing arrays of boxed
1105 objects, because the result is simply the boxed object. So presumably
1106 it should be entered&mdash;we never usually return an unevaluated
1107 object!  This is a pain: primitive ops aren't supposed to do
1108 complicated things like enter objects.  The current solution is to
1109 return a single element unboxed tuple (see <XRef LinkEnd="unboxed-tuples">).
1110 </Para>
1111
1112 <Para>
1113
1114 <ProgramListing>
1115 indexArray#       :: Array# elt -> Int# -> (# elt #)
1116 </ProgramListing>
1117
1118 <IndexTerm><Primary><literal>indexArray&num;</literal></Primary></IndexTerm>
1119 </Para>
1120
1121 </Sect2>
1122
1123 <Sect2>
1124 <Title>The state type</Title>
1125
1126 <Para>
1127 <IndexTerm><Primary><literal>state, primitive type</literal></Primary></IndexTerm>
1128 <IndexTerm><Primary><literal>State&num;</literal></Primary></IndexTerm>
1129 </Para>
1130
1131 <Para>
1132 The primitive type <Literal>State&num;</Literal> represents the state of a state
1133 transformer.  It is parameterised on the desired type of state, which
1134 serves to keep states from distinct threads distinct from one another.
1135 But the <Emphasis>only</Emphasis> effect of this parameterisation is in the type
1136 system: all values of type <Literal>State&num;</Literal> are represented in the same way.
1137 Indeed, they are all represented by nothing at all!  The code
1138 generator &ldquo;knows&rdquo; to generate no code, and allocate no registers
1139 etc, for primitive states.
1140 </Para>
1141
1142 <Para>
1143
1144 <ProgramListing>
1145 type State# s
1146 </ProgramListing>
1147
1148 </Para>
1149
1150 <Para>
1151 The type <Literal>GHC.RealWorld</Literal> is truly opaque: there are no values defined
1152 of this type, and no operations over it.  It is &ldquo;primitive&rdquo; in that
1153 sense - but it is <Emphasis>not unlifted!</Emphasis> Its only role in life is to be
1154 the type which distinguishes the <Literal>IO</Literal> state transformer.
1155 </Para>
1156
1157 <Para>
1158
1159 <ProgramListing>
1160 data RealWorld
1161 </ProgramListing>
1162
1163 </Para>
1164
1165 </Sect2>
1166
1167 <Sect2>
1168 <Title>State of the world</Title>
1169
1170 <Para>
1171 A single, primitive, value of type <Literal>State&num; RealWorld</Literal> is provided.
1172 </Para>
1173
1174 <Para>
1175
1176 <ProgramListing>
1177 realWorld# :: State# RealWorld
1178 </ProgramListing>
1179
1180 <IndexTerm><Primary>realWorld&num; state object</Primary></IndexTerm>
1181 </Para>
1182
1183 <Para>
1184 (Note: in the compiler, not a <Literal>PrimOp</Literal>; just a mucho magic
1185 <Literal>Id</Literal>. Exported from <Literal>GHC</Literal>, though).
1186 </Para>
1187
1188 </Sect2>
1189
1190 <Sect2 id="sect-mutable">
1191 <Title>Mutable arrays</Title>
1192
1193 <Para>
1194 <IndexTerm><Primary>mutable arrays</Primary></IndexTerm>
1195 <IndexTerm><Primary>arrays, mutable</Primary></IndexTerm>
1196 Corresponding to <Literal>Array&num;</Literal> and <Literal>ByteArray&num;</Literal>, we have the types of
1197 mutable versions of each.  In each case, the representation is a
1198 pointer to a suitable block of (mutable) heap-allocated storage.
1199 </Para>
1200
1201 <Para>
1202
1203 <ProgramListing>
1204 type MutableArray# s elt
1205 type MutableByteArray# s
1206 </ProgramListing>
1207
1208 <IndexTerm><Primary><literal>MutableArray&num;</literal></Primary></IndexTerm>
1209 <IndexTerm><Primary><literal>MutableByteArray&num;</literal></Primary></IndexTerm>
1210 </Para>
1211
1212 <Sect3>
1213 <Title>Allocation</Title>
1214
1215 <Para>
1216 <IndexTerm><Primary>mutable arrays, allocation</Primary></IndexTerm>
1217 <IndexTerm><Primary>arrays, allocation</Primary></IndexTerm>
1218 <IndexTerm><Primary>allocation, of mutable arrays</Primary></IndexTerm>
1219 </Para>
1220
1221 <Para>
1222 Mutable arrays can be allocated. Only pointer-arrays are initialised;
1223 arrays of non-pointers are filled in by &ldquo;user code&rdquo; rather than by
1224 the array-allocation primitive.  Reason: only the pointer case has to
1225 worry about GC striking with a partly-initialised array.
1226 </Para>
1227
1228 <Para>
1229
1230 <ProgramListing>
1231 newArray#       :: Int# -> elt -> State# s -> (# State# s, MutableArray# s elt #)
1232
1233 newCharArray#   :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1234 newIntArray#    :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1235 newAddrArray#   :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1236 newFloatArray#  :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1237 newDoubleArray# :: Int# -> State# s -> (# State# s, MutableByteArray# s elt #)
1238 </ProgramListing>
1239
1240 <IndexTerm><Primary><literal>newArray&num;</literal></Primary></IndexTerm>
1241 <IndexTerm><Primary><literal>newCharArray&num;</literal></Primary></IndexTerm>
1242 <IndexTerm><Primary><literal>newIntArray&num;</literal></Primary></IndexTerm>
1243 <IndexTerm><Primary><literal>newAddrArray&num;</literal></Primary></IndexTerm>
1244 <IndexTerm><Primary><literal>newFloatArray&num;</literal></Primary></IndexTerm>
1245 <IndexTerm><Primary><literal>newDoubleArray&num;</literal></Primary></IndexTerm>
1246 </Para>
1247
1248 <Para>
1249 The size of a <Literal>ByteArray&num;</Literal> is given in bytes.
1250 </Para>
1251
1252 </Sect3>
1253
1254 <Sect3>
1255 <Title>Reading and writing</Title>
1256
1257 <Para>
1258 <IndexTerm><Primary>arrays, reading and writing</Primary></IndexTerm>
1259 </Para>
1260
1261 <Para>
1262
1263 <ProgramListing>
1264 readArray#       :: MutableArray# s elt -> Int# -> State# s -> (# State# s, elt #)
1265 readCharArray#   :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Char# #)
1266 readIntArray#    :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Int# #)
1267 readAddrArray#   :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Addr# #)
1268 readFloatArray#  :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Float# #)
1269 readDoubleArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Double# #)
1270
1271 writeArray#       :: MutableArray# s elt -> Int# -> elt     -> State# s -> State# s
1272 writeCharArray#   :: MutableByteArray# s -> Int# -> Char#   -> State# s -> State# s
1273 writeIntArray#    :: MutableByteArray# s -> Int# -> Int#    -> State# s -> State# s
1274 writeAddrArray#   :: MutableByteArray# s -> Int# -> Addr#   -> State# s -> State# s
1275 writeFloatArray#  :: MutableByteArray# s -> Int# -> Float#  -> State# s -> State# s
1276 writeDoubleArray# :: MutableByteArray# s -> Int# -> Double# -> State# s -> State# s
1277 </ProgramListing>
1278
1279 <IndexTerm><Primary><literal>readArray&num;</literal></Primary></IndexTerm>
1280 <IndexTerm><Primary><literal>readCharArray&num;</literal></Primary></IndexTerm>
1281 <IndexTerm><Primary><literal>readIntArray&num;</literal></Primary></IndexTerm>
1282 <IndexTerm><Primary><literal>readAddrArray&num;</literal></Primary></IndexTerm>
1283 <IndexTerm><Primary><literal>readFloatArray&num;</literal></Primary></IndexTerm>
1284 <IndexTerm><Primary><literal>readDoubleArray&num;</literal></Primary></IndexTerm>
1285 <IndexTerm><Primary><literal>writeArray&num;</literal></Primary></IndexTerm>
1286 <IndexTerm><Primary><literal>writeCharArray&num;</literal></Primary></IndexTerm>
1287 <IndexTerm><Primary><literal>writeIntArray&num;</literal></Primary></IndexTerm>
1288 <IndexTerm><Primary><literal>writeAddrArray&num;</literal></Primary></IndexTerm>
1289 <IndexTerm><Primary><literal>writeFloatArray&num;</literal></Primary></IndexTerm>
1290 <IndexTerm><Primary><literal>writeDoubleArray&num;</literal></Primary></IndexTerm>
1291 </Para>
1292
1293 </Sect3>
1294
1295 <Sect3>
1296 <Title>Equality</Title>
1297
1298 <Para>
1299 <IndexTerm><Primary>arrays, testing for equality</Primary></IndexTerm>
1300 </Para>
1301
1302 <Para>
1303 One can take &ldquo;equality&rdquo; of mutable arrays.  What is compared is the
1304 <Emphasis>name</Emphasis> or reference to the mutable array, not its contents.
1305 </Para>
1306
1307 <Para>
1308
1309 <ProgramListing>
1310 sameMutableArray#     :: MutableArray# s elt -> MutableArray# s elt -> Bool
1311 sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool
1312 </ProgramListing>
1313
1314 <IndexTerm><Primary><literal>sameMutableArray&num;</literal></Primary></IndexTerm>
1315 <IndexTerm><Primary><literal>sameMutableByteArray&num;</literal></Primary></IndexTerm>
1316 </Para>
1317
1318 </Sect3>
1319
1320 <Sect3>
1321 <Title>Freezing mutable arrays</Title>
1322
1323 <Para>
1324 <IndexTerm><Primary>arrays, freezing mutable</Primary></IndexTerm>
1325 <IndexTerm><Primary>freezing mutable arrays</Primary></IndexTerm>
1326 <IndexTerm><Primary>mutable arrays, freezing</Primary></IndexTerm>
1327 </Para>
1328
1329 <Para>
1330 Only unsafe-freeze has a primitive.  (Safe freeze is done directly in Haskell
1331 by copying the array and then using <Function>unsafeFreeze</Function>.)
1332 </Para>
1333
1334 <Para>
1335
1336 <ProgramListing>
1337 unsafeFreezeArray#     :: MutableArray# s elt -> State# s -> (# State# s, Array# s elt #)
1338 unsafeFreezeByteArray# :: MutableByteArray# s -> State# s -> (# State# s, ByteArray# #)
1339 </ProgramListing>
1340
1341 <IndexTerm><Primary><literal>unsafeFreezeArray&num;</literal></Primary></IndexTerm>
1342 <IndexTerm><Primary><literal>unsafeFreezeByteArray&num;</literal></Primary></IndexTerm>
1343 </Para>
1344
1345 </Sect3>
1346
1347 </Sect2>
1348
1349 <Sect2>
1350 <Title>Synchronizing variables (M-vars)</Title>
1351
1352 <Para>
1353 <IndexTerm><Primary>synchronising variables (M-vars)</Primary></IndexTerm>
1354 <IndexTerm><Primary>M-Vars</Primary></IndexTerm>
1355 </Para>
1356
1357 <Para>
1358 Synchronising variables are the primitive type used to implement
1359 Concurrent Haskell's MVars (see the Concurrent Haskell paper for
1360 the operational behaviour of these operations).
1361 </Para>
1362
1363 <Para>
1364
1365 <ProgramListing>
1366 type MVar# s elt        -- primitive
1367
1368 newMVar#    :: State# s -> (# State# s, MVar# s elt #)
1369 takeMVar#   :: SynchVar# s elt -> State# s -> (# State# s, elt #)
1370 putMVar#    :: SynchVar# s elt -> State# s -> State# s
1371 </ProgramListing>
1372
1373 <IndexTerm><Primary><literal>SynchVar&num;</literal></Primary></IndexTerm>
1374 <IndexTerm><Primary><literal>newSynchVar&num;</literal></Primary></IndexTerm>
1375 <IndexTerm><Primary><literal>takeMVar</literal></Primary></IndexTerm>
1376 <IndexTerm><Primary><literal>putMVar</literal></Primary></IndexTerm>
1377 </Para>
1378
1379 </Sect2>
1380
1381 </Sect1>
1382
1383 <Sect1 id="glasgow-ST-monad">
1384 <Title>Primitive state-transformer monad
1385 </Title>
1386
1387 <Para>
1388 <IndexTerm><Primary>state transformers (Glasgow extensions)</Primary></IndexTerm>
1389 <IndexTerm><Primary>ST monad (Glasgow extension)</Primary></IndexTerm>
1390 </Para>
1391
1392 <Para>
1393 This monad underlies our implementation of arrays, mutable and
1394 immutable, and our implementation of I/O, including &ldquo;C calls&rdquo;.
1395 </Para>
1396
1397 <Para>
1398 The <Literal>ST</Literal> library, which provides access to the
1399 <Function>ST</Function> monad, is described in <xref
1400 linkend="sec-ST">.
1401 </Para>
1402
1403 </Sect1>
1404
1405 <Sect1 id="glasgow-prim-arrays">
1406 <Title>Primitive arrays, mutable and otherwise
1407 </Title>
1408
1409 <Para>
1410 <IndexTerm><Primary>primitive arrays (Glasgow extension)</Primary></IndexTerm>
1411 <IndexTerm><Primary>arrays, primitive (Glasgow extension)</Primary></IndexTerm>
1412 </Para>
1413
1414 <Para>
1415 GHC knows about quite a few flavours of Large Swathes of Bytes.
1416 </Para>
1417
1418 <Para>
1419 First, GHC distinguishes between primitive arrays of (boxed) Haskell
1420 objects (type <Literal>Array&num; obj</Literal>) and primitive arrays of bytes (type
1421 <Literal>ByteArray&num;</Literal>).
1422 </Para>
1423
1424 <Para>
1425 Second, it distinguishes between&hellip;
1426 <VariableList>
1427
1428 <VarListEntry>
1429 <Term>Immutable:</Term>
1430 <ListItem>
1431 <Para>
1432 Arrays that do not change (as with &ldquo;standard&rdquo; Haskell arrays); you
1433 can only read from them.  Obviously, they do not need the care and
1434 attention of the state-transformer monad.
1435 </Para>
1436 </ListItem>
1437 </VarListEntry>
1438 <VarListEntry>
1439 <Term>Mutable:</Term>
1440 <ListItem>
1441 <Para>
1442 Arrays that may be changed or &ldquo;mutated.&rdquo;  All the operations on them
1443 live within the state-transformer monad and the updates happen
1444 <Emphasis>in-place</Emphasis>.
1445 </Para>
1446 </ListItem>
1447 </VarListEntry>
1448 <VarListEntry>
1449 <Term>&ldquo;Static&rdquo; (in C land):</Term>
1450 <ListItem>
1451 <Para>
1452 A C routine may pass an <Literal>Addr&num;</Literal> pointer back into Haskell land.  There
1453 are then primitive operations with which you may merrily grab values
1454 over in C land, by indexing off the &ldquo;static&rdquo; pointer.
1455 </Para>
1456 </ListItem>
1457 </VarListEntry>
1458 <VarListEntry>
1459 <Term>&ldquo;Stable&rdquo; pointers:</Term>
1460 <ListItem>
1461 <Para>
1462 If, for some reason, you wish to hand a Haskell pointer (i.e.,
1463 <Emphasis>not</Emphasis> an unboxed value) to a C routine, you first make the
1464 pointer &ldquo;stable,&rdquo; so that the garbage collector won't forget that it
1465 exists.  That is, GHC provides a safe way to pass Haskell pointers to
1466 C.
1467 </Para>
1468
1469 <Para>
1470 Please see <XRef LinkEnd="sec-stable-pointers"> for more details.
1471 </Para>
1472 </ListItem>
1473 </VarListEntry>
1474 <VarListEntry>
1475 <Term>&ldquo;Foreign objects&rdquo;:</Term>
1476 <ListItem>
1477 <Para>
1478 A &ldquo;foreign object&rdquo; is a safe way to pass an external object (a
1479 C-allocated pointer, say) to Haskell and have Haskell do the Right
1480 Thing when it no longer references the object.  So, for example, C
1481 could pass a large bitmap over to Haskell and say &ldquo;please free this
1482 memory when you're done with it.&rdquo;
1483 </Para>
1484
1485 <Para>
1486 Please see <XRef LinkEnd="sec-ForeignObj"> for more details.
1487 </Para>
1488 </ListItem>
1489 </VarListEntry>
1490 </VariableList>
1491 </Para>
1492
1493 <Para>
1494 The libraries documentatation gives more details on all these
1495 &ldquo;primitive array&rdquo; types and the operations on them.
1496 </Para>
1497
1498 </Sect1>
1499
1500
1501 <Sect1 id="pattern-guards">
1502 <Title>Pattern guards</Title>
1503
1504 <Para>
1505 <IndexTerm><Primary>Pattern guards (Glasgow extension)</Primary></IndexTerm>
1506 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.)
1507 </Para>
1508
1509 <Para>
1510 Suppose we have an abstract data type of finite maps, with a
1511 lookup operation:
1512
1513 <ProgramListing>
1514 lookup :: FiniteMap -> Int -> Maybe Int
1515 </ProgramListing>
1516
1517 The lookup returns <Function>Nothing</Function> if the supplied key is not in the domain of the mapping, and <Function>(Just v)</Function> otherwise,
1518 where <VarName>v</VarName> is the value that the key maps to.  Now consider the following definition:
1519 </Para>
1520
1521 <ProgramListing>
1522 clunky env var1 var2 | ok1 && ok2 = val1 + val2
1523 | otherwise  = var1 + var2
1524 where
1525   m1 = lookup env var1
1526   m2 = lookup env var2
1527   ok1 = maybeToBool m1
1528   ok2 = maybeToBool m2
1529   val1 = expectJust m1
1530   val2 = expectJust m2
1531 </ProgramListing>
1532
1533 <Para>
1534 The auxiliary functions are 
1535 </Para>
1536
1537 <ProgramListing>
1538 maybeToBool :: Maybe a -&gt; Bool
1539 maybeToBool (Just x) = True
1540 maybeToBool Nothing  = False
1541
1542 expectJust :: Maybe a -&gt; a
1543 expectJust (Just x) = x
1544 expectJust Nothing  = error "Unexpected Nothing"
1545 </ProgramListing>
1546
1547 <Para>
1548 What is <Function>clunky</Function> doing? The guard <Literal>ok1 &&
1549 ok2</Literal> checks that both lookups succeed, using
1550 <Function>maybeToBool</Function> to convert the <Function>Maybe</Function>
1551 types to booleans. The (lazily evaluated) <Function>expectJust</Function>
1552 calls extract the values from the results of the lookups, and binds the
1553 returned values to <VarName>val1</VarName> and <VarName>val2</VarName>
1554 respectively.  If either lookup fails, then clunky takes the
1555 <Literal>otherwise</Literal> case and returns the sum of its arguments.
1556 </Para>
1557
1558 <Para>
1559 This is certainly legal Haskell, but it is a tremendously verbose and
1560 un-obvious way to achieve the desired effect.  Arguably, a more direct way
1561 to write clunky would be to use case expressions:
1562 </Para>
1563
1564 <ProgramListing>
1565 clunky env var1 var1 = case lookup env var1 of
1566   Nothing -&gt; fail
1567   Just val1 -&gt; case lookup env var2 of
1568     Nothing -&gt; fail
1569     Just val2 -&gt; val1 + val2
1570 where
1571   fail = val1 + val2
1572 </ProgramListing>
1573
1574 <Para>
1575 This is a bit shorter, but hardly better.  Of course, we can rewrite any set
1576 of pattern-matching, guarded equations as case expressions; that is
1577 precisely what the compiler does when compiling equations! The reason that
1578 Haskell provides guarded equations is because they allow us to write down
1579 the cases we want to consider, one at a time, independently of each other. 
1580 This structure is hidden in the case version.  Two of the right-hand sides
1581 are really the same (<Function>fail</Function>), and the whole expression
1582 tends to become more and more indented. 
1583 </Para>
1584
1585 <Para>
1586 Here is how I would write clunky:
1587 </Para>
1588
1589 <ProgramListing>
1590 clunky env var1 var1
1591   | Just val1 &lt;- lookup env var1
1592   , Just val2 &lt;- lookup env var2
1593   = val1 + val2
1594 ...other equations for clunky...
1595 </ProgramListing>
1596
1597 <Para>
1598 The semantics should be clear enough.  The qualifers are matched in order. 
1599 For a <Literal>&lt;-</Literal> qualifier, which I call a pattern guard, the
1600 right hand side is evaluated and matched against the pattern on the left. 
1601 If the match fails then the whole guard fails and the next equation is
1602 tried.  If it succeeds, then the appropriate binding takes place, and the
1603 next qualifier is matched, in the augmented environment.  Unlike list
1604 comprehensions, however, the type of the expression to the right of the
1605 <Literal>&lt;-</Literal> is the same as the type of the pattern to its
1606 left.  The bindings introduced by pattern guards scope over all the
1607 remaining guard qualifiers, and over the right hand side of the equation.
1608 </Para>
1609
1610 <Para>
1611 Just as with list comprehensions, boolean expressions can be freely mixed
1612 with among the pattern guards.  For example:
1613 </Para>
1614
1615 <ProgramListing>
1616 f x | [y] <- x
1617     , y > 3
1618     , Just z <- h y
1619     = ...
1620 </ProgramListing>
1621
1622 <Para>
1623 Haskell's current guards therefore emerge as a special case, in which the
1624 qualifier list has just one element, a boolean expression.
1625 </Para>
1626 </Sect1>
1627
1628   <sect1 id="sec-ffi">
1629     <title>The foreign interface</title>
1630
1631     <para>The foreign interface consists of the following components:</para>
1632
1633     <itemizedlist>
1634       <listitem>
1635         <para>The Foreign Function Interface language specification
1636         (included in this manual, in <xref linkend="ffi">).</para>
1637       </listitem>
1638
1639       <listitem>
1640         <para>The <literal>Foreign</literal> module (see <xref
1641         linkend="sec-Foreign">) collects together several interfaces
1642         which are useful in specifying foreign language
1643         interfaces, including the following:</para>
1644
1645         <itemizedlist>
1646           <listitem>
1647             <para>The <literal>ForeignObj</literal> module (see <xref
1648             linkend="sec-ForeignObj">), for managing pointers from
1649             Haskell into the outside world.</para>
1650           </listitem>
1651       
1652           <listitem>
1653             <para>The <literal>StablePtr</literal> module (see <xref
1654             linkend="sec-stable-pointers">), for managing pointers
1655             into Haskell from the outside world.</para>
1656           </listitem>
1657       
1658           <listitem>
1659             <para>The <literal>CTypes</literal> module (see <xref
1660             linkend="sec-CTypes">) gives Haskell equivalents for the
1661             standard C datatypes, for use in making Haskell bindings
1662             to existing C libraries.</para>
1663           </listitem>
1664       
1665           <listitem>
1666             <para>The <literal>CTypesISO</literal> module (see <xref
1667             linkend="sec-CTypesISO">) gives Haskell equivalents for C
1668             types defined by the ISO C standard.</para>
1669           </listitem>
1670       
1671           <listitem>
1672             <para>The <literal>Storable</literal> library, for
1673             primitive marshalling of data types between Haskell and
1674             the foreign language.</para>
1675           </listitem>
1676         </itemizedlist>
1677
1678       </listitem>
1679     </itemizedlist>
1680
1681 <para>The following sections also give some hints and tips on the use
1682 of the foreign function interface in GHC.</para>
1683
1684 <Sect2 id="glasgow-foreign-headers">
1685 <Title>Using function headers
1686 </Title>
1687
1688 <Para>
1689 <IndexTerm><Primary>C calls, function headers</Primary></IndexTerm>
1690 </Para>
1691
1692 <Para>
1693 When generating C (using the <Option>-fvia-C</Option> directive), one can assist the
1694 C compiler in detecting type errors by using the <Command>-&num;include</Command> directive
1695 to provide <Filename>.h</Filename> files containing function headers.
1696 </Para>
1697
1698 <Para>
1699 For example,
1700 </Para>
1701
1702 <Para>
1703
1704 <ProgramListing>
1705 #include "HsFFI.h"
1706
1707 void         initialiseEFS (HsInt size);
1708 HsInt        terminateEFS (void);
1709 HsForeignObj emptyEFS(void);
1710 HsForeignObj updateEFS (HsForeignObj a, HsInt i, HsInt x);
1711 HsInt        lookupEFS (HsForeignObj a, HsInt i);
1712 </ProgramListing>
1713 </Para>
1714
1715       <para>The types <literal>HsInt</literal>,
1716       <literal>HsForeignObj</literal> etc. are described in <xref
1717       linkend="sec-mapping-table">.</Para>
1718
1719       <Para>Note that this approach is only
1720       <Emphasis>essential</Emphasis> for returning
1721       <Literal>float</Literal>s (or if <Literal>sizeof(int) !=
1722       sizeof(int *)</Literal> on your architecture) but is a Good
1723       Thing for anyone who cares about writing solid code.  You're
1724       crazy not to do it.</Para>
1725
1726 </Sect2>
1727
1728 </Sect1>
1729
1730 <Sect1 id="multi-param-type-classes">
1731 <Title>Multi-parameter type classes
1732 </Title>
1733
1734 <Para>
1735 This section documents GHC's implementation of multi-parameter type
1736 classes.  There's lots of background in the paper <ULink
1737 URL="http://research.microsoft.com/~simonpj/multi.ps.gz" >Type
1738 classes: exploring the design space</ULink > (Simon Peyton Jones, Mark
1739 Jones, Erik Meijer).
1740 </Para>
1741
1742 <Para>
1743 I'd like to thank people who reported shorcomings in the GHC 3.02
1744 implementation.  Our default decisions were all conservative ones, and
1745 the experience of these heroic pioneers has given useful concrete
1746 examples to support several generalisations.  (These appear below as
1747 design choices not implemented in 3.02.)
1748 </Para>
1749
1750 <Para>
1751 I've discussed these notes with Mark Jones, and I believe that Hugs
1752 will migrate towards the same design choices as I outline here.
1753 Thanks to him, and to many others who have offered very useful
1754 feedback.
1755 </Para>
1756
1757 <Sect2>
1758 <Title>Types</Title>
1759
1760 <Para>
1761 There are the following restrictions on the form of a qualified
1762 type:
1763 </Para>
1764
1765 <Para>
1766
1767 <ProgramListing>
1768   forall tv1..tvn (c1, ...,cn) => type
1769 </ProgramListing>
1770
1771 </Para>
1772
1773 <Para>
1774 (Here, I write the "foralls" explicitly, although the Haskell source
1775 language omits them; in Haskell 1.4, all the free type variables of an
1776 explicit source-language type signature are universally quantified,
1777 except for the class type variables in a class declaration.  However,
1778 in GHC, you can give the foralls if you want.  See <XRef LinkEnd="universal-quantification">).
1779 </Para>
1780
1781 <Para>
1782
1783 <OrderedList>
1784 <ListItem>
1785
1786 <Para>
1787  <Emphasis>Each universally quantified type variable
1788 <Literal>tvi</Literal> must be mentioned (i.e. appear free) in <Literal>type</Literal></Emphasis>.
1789
1790 The reason for this is that a value with a type that does not obey
1791 this restriction could not be used without introducing
1792 ambiguity. Here, for example, is an illegal type:
1793
1794
1795 <ProgramListing>
1796   forall a. Eq a => Int
1797 </ProgramListing>
1798
1799
1800 When a value with this type was used, the constraint <Literal>Eq tv</Literal>
1801 would be introduced where <Literal>tv</Literal> is a fresh type variable, and
1802 (in the dictionary-translation implementation) the value would be
1803 applied to a dictionary for <Literal>Eq tv</Literal>.  The difficulty is that we
1804 can never know which instance of <Literal>Eq</Literal> to use because we never
1805 get any more information about <Literal>tv</Literal>.
1806
1807 </Para>
1808 </ListItem>
1809 <ListItem>
1810
1811 <Para>
1812  <Emphasis>Every constraint <Literal>ci</Literal> must mention at least one of the
1813 universally quantified type variables <Literal>tvi</Literal></Emphasis>.
1814
1815 For example, this type is OK because <Literal>C a b</Literal> mentions the
1816 universally quantified type variable <Literal>b</Literal>:
1817
1818
1819 <ProgramListing>
1820   forall a. C a b => burble
1821 </ProgramListing>
1822
1823
1824 The next type is illegal because the constraint <Literal>Eq b</Literal> does not
1825 mention <Literal>a</Literal>:
1826
1827
1828 <ProgramListing>
1829   forall a. Eq b => burble
1830 </ProgramListing>
1831
1832
1833 The reason for this restriction is milder than the other one.  The
1834 excluded types are never useful or necessary (because the offending
1835 context doesn't need to be witnessed at this point; it can be floated
1836 out).  Furthermore, floating them out increases sharing. Lastly,
1837 excluding them is a conservative choice; it leaves a patch of
1838 territory free in case we need it later.
1839
1840 </Para>
1841 </ListItem>
1842
1843 </OrderedList>
1844
1845 </Para>
1846
1847 <Para>
1848 These restrictions apply to all types, whether declared in a type signature
1849 or inferred.
1850 </Para>
1851
1852 <Para>
1853 Unlike Haskell 1.4, constraints in types do <Emphasis>not</Emphasis> have to be of
1854 the form <Emphasis>(class type-variables)</Emphasis>.  Thus, these type signatures
1855 are perfectly OK
1856 </Para>
1857
1858 <Para>
1859
1860 <ProgramListing>
1861   f :: Eq (m a) => [m a] -> [m a]
1862   g :: Eq [a] => ...
1863 </ProgramListing>
1864
1865 </Para>
1866
1867 <Para>
1868 This choice recovers principal types, a property that Haskell 1.4 does not have.
1869 </Para>
1870
1871 </Sect2>
1872
1873 <Sect2>
1874 <Title>Class declarations</Title>
1875
1876 <Para>
1877
1878 <OrderedList>
1879 <ListItem>
1880
1881 <Para>
1882  <Emphasis>Multi-parameter type classes are permitted</Emphasis>. For example:
1883
1884
1885 <ProgramListing>
1886   class Collection c a where
1887     union :: c a -> c a -> c a
1888     ...etc.
1889 </ProgramListing>
1890
1891
1892
1893 </Para>
1894 </ListItem>
1895 <ListItem>
1896
1897 <Para>
1898  <Emphasis>The class hierarchy must be acyclic</Emphasis>.  However, the definition
1899 of "acyclic" involves only the superclass relationships.  For example,
1900 this is OK:
1901
1902
1903 <ProgramListing>
1904   class C a where {
1905     op :: D b => a -> b -> b
1906   }
1907
1908   class C a => D a where { ... }
1909 </ProgramListing>
1910
1911
1912 Here, <Literal>C</Literal> is a superclass of <Literal>D</Literal>, but it's OK for a
1913 class operation <Literal>op</Literal> of <Literal>C</Literal> to mention <Literal>D</Literal>.  (It
1914 would not be OK for <Literal>D</Literal> to be a superclass of <Literal>C</Literal>.)
1915
1916 </Para>
1917 </ListItem>
1918 <ListItem>
1919
1920 <Para>
1921  <Emphasis>There are no restrictions on the context in a class declaration
1922 (which introduces superclasses), except that the class hierarchy must
1923 be acyclic</Emphasis>.  So these class declarations are OK:
1924
1925
1926 <ProgramListing>
1927   class Functor (m k) => FiniteMap m k where
1928     ...
1929
1930   class (Monad m, Monad (t m)) => Transform t m where
1931     lift :: m a -> (t m) a
1932 </ProgramListing>
1933
1934
1935 </Para>
1936 </ListItem>
1937 <ListItem>
1938
1939 <Para>
1940  <Emphasis>In the signature of a class operation, every constraint
1941 must mention at least one type variable that is not a class type
1942 variable</Emphasis>.
1943
1944 Thus:
1945
1946
1947 <ProgramListing>
1948   class Collection c a where
1949     mapC :: Collection c b => (a->b) -> c a -> c b
1950 </ProgramListing>
1951
1952
1953 is OK because the constraint <Literal>(Collection a b)</Literal> mentions
1954 <Literal>b</Literal>, even though it also mentions the class variable
1955 <Literal>a</Literal>.  On the other hand:
1956
1957
1958 <ProgramListing>
1959   class C a where
1960     op :: Eq a => (a,b) -> (a,b)
1961 </ProgramListing>
1962
1963
1964 is not OK because the constraint <Literal>(Eq a)</Literal> mentions on the class
1965 type variable <Literal>a</Literal>, but not <Literal>b</Literal>.  However, any such
1966 example is easily fixed by moving the offending context up to the
1967 superclass context:
1968
1969
1970 <ProgramListing>
1971   class Eq a => C a where
1972     op ::(a,b) -> (a,b)
1973 </ProgramListing>
1974
1975
1976 A yet more relaxed rule would allow the context of a class-op signature
1977 to mention only class type variables.  However, that conflicts with
1978 Rule 1(b) for types above.
1979
1980 </Para>
1981 </ListItem>
1982 <ListItem>
1983
1984 <Para>
1985  <Emphasis>The type of each class operation must mention <Emphasis>all</Emphasis> of
1986 the class type variables</Emphasis>.  For example:
1987
1988
1989 <ProgramListing>
1990   class Coll s a where
1991     empty  :: s
1992     insert :: s -> a -> s
1993 </ProgramListing>
1994
1995
1996 is not OK, because the type of <Literal>empty</Literal> doesn't mention
1997 <Literal>a</Literal>.  This rule is a consequence of Rule 1(a), above, for
1998 types, and has the same motivation.
1999
2000 Sometimes, offending class declarations exhibit misunderstandings.  For
2001 example, <Literal>Coll</Literal> might be rewritten
2002
2003
2004 <ProgramListing>
2005   class Coll s a where
2006     empty  :: s a
2007     insert :: s a -> a -> s a
2008 </ProgramListing>
2009
2010
2011 which makes the connection between the type of a collection of
2012 <Literal>a</Literal>'s (namely <Literal>(s a)</Literal>) and the element type <Literal>a</Literal>.
2013 Occasionally this really doesn't work, in which case you can split the
2014 class like this:
2015
2016
2017 <ProgramListing>
2018   class CollE s where
2019     empty  :: s
2020
2021   class CollE s => Coll s a where
2022     insert :: s -> a -> s
2023 </ProgramListing>
2024
2025
2026 </Para>
2027 </ListItem>
2028
2029 </OrderedList>
2030
2031 </Para>
2032
2033 </Sect2>
2034
2035 <Sect2 id="instance-decls">
2036 <Title>Instance declarations</Title>
2037
2038 <Para>
2039
2040 <OrderedList>
2041 <ListItem>
2042
2043 <Para>
2044  <Emphasis>Instance declarations may not overlap</Emphasis>.  The two instance
2045 declarations
2046
2047
2048 <ProgramListing>
2049   instance context1 => C type1 where ...
2050   instance context2 => C type2 where ...
2051 </ProgramListing>
2052
2053
2054 "overlap" if <Literal>type1</Literal> and <Literal>type2</Literal> unify
2055
2056 However, if you give the command line option
2057 <Option>-fallow-overlapping-instances</Option><IndexTerm><Primary>-fallow-overlapping-instances
2058 option</Primary></IndexTerm> then two overlapping instance declarations are permitted
2059 iff
2060
2061
2062 <ItemizedList>
2063 <ListItem>
2064
2065 <Para>
2066  EITHER <Literal>type1</Literal> and <Literal>type2</Literal> do not unify
2067 </Para>
2068 </ListItem>
2069 <ListItem>
2070
2071 <Para>
2072  OR <Literal>type2</Literal> is a substitution instance of <Literal>type1</Literal>
2073 (but not identical to <Literal>type1</Literal>)
2074 </Para>
2075 </ListItem>
2076 <ListItem>
2077
2078 <Para>
2079  OR vice versa
2080 </Para>
2081 </ListItem>
2082
2083 </ItemizedList>
2084
2085
2086 Notice that these rules
2087
2088
2089 <ItemizedList>
2090 <ListItem>
2091
2092 <Para>
2093  make it clear which instance decl to use
2094 (pick the most specific one that matches)
2095
2096 </Para>
2097 </ListItem>
2098 <ListItem>
2099
2100 <Para>
2101  do not mention the contexts <Literal>context1</Literal>, <Literal>context2</Literal>
2102 Reason: you can pick which instance decl
2103 "matches" based on the type.
2104 </Para>
2105 </ListItem>
2106
2107 </ItemizedList>
2108
2109
2110 Regrettably, GHC doesn't guarantee to detect overlapping instance
2111 declarations if they appear in different modules.  GHC can "see" the
2112 instance declarations in the transitive closure of all the modules
2113 imported by the one being compiled, so it can "see" all instance decls
2114 when it is compiling <Literal>Main</Literal>.  However, it currently chooses not
2115 to look at ones that can't possibly be of use in the module currently
2116 being compiled, in the interests of efficiency.  (Perhaps we should
2117 change that decision, at least for <Literal>Main</Literal>.)
2118
2119 </Para>
2120 </ListItem>
2121 <ListItem>
2122
2123 <Para>
2124  <Emphasis>There are no restrictions on the type in an instance
2125 <Emphasis>head</Emphasis>, except that at least one must not be a type variable</Emphasis>.
2126 The instance "head" is the bit after the "=>" in an instance decl. For
2127 example, these are OK:
2128
2129
2130 <ProgramListing>
2131   instance C Int a where ...
2132
2133   instance D (Int, Int) where ...
2134
2135   instance E [[a]] where ...
2136 </ProgramListing>
2137
2138
2139 Note that instance heads <Emphasis>may</Emphasis> contain repeated type variables.
2140 For example, this is OK:
2141
2142
2143 <ProgramListing>
2144   instance Stateful (ST s) (MutVar s) where ...
2145 </ProgramListing>
2146
2147
2148 The "at least one not a type variable" restriction is to ensure that
2149 context reduction terminates: each reduction step removes one type
2150 constructor.  For example, the following would make the type checker
2151 loop if it wasn't excluded:
2152
2153
2154 <ProgramListing>
2155   instance C a => C a where ...
2156 </ProgramListing>
2157
2158
2159 There are two situations in which the rule is a bit of a pain. First,
2160 if one allows overlapping instance declarations then it's quite
2161 convenient to have a "default instance" declaration that applies if
2162 something more specific does not:
2163
2164
2165 <ProgramListing>
2166   instance C a where
2167     op = ... -- Default
2168 </ProgramListing>
2169
2170
2171 Second, sometimes you might want to use the following to get the
2172 effect of a "class synonym":
2173
2174
2175 <ProgramListing>
2176   class (C1 a, C2 a, C3 a) => C a where { }
2177
2178   instance (C1 a, C2 a, C3 a) => C a where { }
2179 </ProgramListing>
2180
2181
2182 This allows you to write shorter signatures:
2183
2184
2185 <ProgramListing>
2186   f :: C a => ...
2187 </ProgramListing>
2188
2189
2190 instead of
2191
2192
2193 <ProgramListing>
2194   f :: (C1 a, C2 a, C3 a) => ...
2195 </ProgramListing>
2196
2197
2198 I'm on the lookout for a simple rule that preserves decidability while
2199 allowing these idioms.  The experimental flag
2200 <Option>-fallow-undecidable-instances</Option><IndexTerm><Primary>-fallow-undecidable-instances
2201 option</Primary></IndexTerm> lifts this restriction, allowing all the types in an
2202 instance head to be type variables.
2203
2204 </Para>
2205 </ListItem>
2206 <ListItem>
2207
2208 <Para>
2209  <Emphasis>Unlike Haskell 1.4, instance heads may use type
2210 synonyms</Emphasis>.  As always, using a type synonym is just shorthand for
2211 writing the RHS of the type synonym definition.  For example:
2212
2213
2214 <ProgramListing>
2215   type Point = (Int,Int)
2216   instance C Point   where ...
2217   instance C [Point] where ...
2218 </ProgramListing>
2219
2220
2221 is legal.  However, if you added
2222
2223
2224 <ProgramListing>
2225   instance C (Int,Int) where ...
2226 </ProgramListing>
2227
2228
2229 as well, then the compiler will complain about the overlapping
2230 (actually, identical) instance declarations.  As always, type synonyms
2231 must be fully applied.  You cannot, for example, write:
2232
2233
2234 <ProgramListing>
2235   type P a = [[a]]
2236   instance Monad P where ...
2237 </ProgramListing>
2238
2239
2240 This design decision is independent of all the others, and easily
2241 reversed, but it makes sense to me.
2242
2243 </Para>
2244 </ListItem>
2245 <ListItem>
2246
2247 <Para>
2248 <Emphasis>The types in an instance-declaration <Emphasis>context</Emphasis> must all
2249 be type variables</Emphasis>. Thus
2250
2251
2252 <ProgramListing>
2253 instance C a b => Eq (a,b) where ...
2254 </ProgramListing>
2255
2256
2257 is OK, but
2258
2259
2260 <ProgramListing>
2261 instance C Int b => Foo b where ...
2262 </ProgramListing>
2263
2264
2265 is not OK.  Again, the intent here is to make sure that context
2266 reduction terminates.
2267
2268 Voluminous correspondence on the Haskell mailing list has convinced me
2269 that it's worth experimenting with a more liberal rule.  If you use
2270 the flag <Option>-fallow-undecidable-instances</Option> can use arbitrary
2271 types in an instance context.  Termination is ensured by having a
2272 fixed-depth recursion stack.  If you exceed the stack depth you get a
2273 sort of backtrace, and the opportunity to increase the stack depth
2274 with <Option>-fcontext-stack</Option><Emphasis>N</Emphasis>.
2275
2276 </Para>
2277 </ListItem>
2278
2279 </OrderedList>
2280
2281 </Para>
2282
2283 </Sect2>
2284
2285 </Sect1>
2286
2287 <Sect1 id="universal-quantification">
2288 <Title>Explicit universal quantification
2289 </Title>
2290
2291 <Para>
2292 GHC now allows you to write explicitly quantified types.  GHC's
2293 syntax for this now agrees with Hugs's, namely:
2294 </Para>
2295
2296 <Para>
2297
2298 <ProgramListing>
2299         forall a b. (Ord a, Eq  b) => a -> b -> a
2300 </ProgramListing>
2301
2302 </Para>
2303
2304 <Para>
2305 The context is, of course, optional.  You can't use <Literal>forall</Literal> as
2306 a type variable any more!
2307 </Para>
2308
2309 <Para>
2310 Haskell type signatures are implicitly quantified.  The <Literal>forall</Literal>
2311 allows us to say exactly what this means.  For example:
2312 </Para>
2313
2314 <Para>
2315
2316 <ProgramListing>
2317         g :: b -> b
2318 </ProgramListing>
2319
2320 </Para>
2321
2322 <Para>
2323 means this:
2324 </Para>
2325
2326 <Para>
2327
2328 <ProgramListing>
2329         g :: forall b. (b -> b)
2330 </ProgramListing>
2331
2332 </Para>
2333
2334 <Para>
2335 The two are treated identically.
2336 </Para>
2337
2338 <Sect2 id="univ">
2339 <Title>Universally-quantified data type fields
2340 </Title>
2341
2342 <Para>
2343 In a <Literal>data</Literal> or <Literal>newtype</Literal> declaration one can quantify
2344 the types of the constructor arguments.  Here are several examples:
2345 </Para>
2346
2347 <Para>
2348
2349 <ProgramListing>
2350 data T a = T1 (forall b. b -> b -> b) a
2351
2352 data MonadT m = MkMonad { return :: forall a. a -> m a,
2353                           bind   :: forall a b. m a -> (a -> m b) -> m b
2354                         }
2355
2356 newtype Swizzle = MkSwizzle (Ord a => [a] -> [a])
2357 </ProgramListing>
2358
2359 </Para>
2360
2361 <Para>
2362 The constructors now have so-called <Emphasis>rank 2</Emphasis> polymorphic
2363 types, in which there is a for-all in the argument types.:
2364 </Para>
2365
2366 <Para>
2367
2368 <ProgramListing>
2369 T1 :: forall a. (forall b. b -> b -> b) -> a -> T a
2370 MkMonad :: forall m. (forall a. a -> m a)
2371                   -> (forall a b. m a -> (a -> m b) -> m b)
2372                   -> MonadT m
2373 MkSwizzle :: (Ord a => [a] -> [a]) -> Swizzle
2374 </ProgramListing>
2375
2376 </Para>
2377
2378 <Para>
2379 Notice that you don't need to use a <Literal>forall</Literal> if there's an
2380 explicit context.  For example in the first argument of the
2381 constructor <Function>MkSwizzle</Function>, an implicit "<Literal>forall a.</Literal>" is
2382 prefixed to the argument type.  The implicit <Literal>forall</Literal>
2383 quantifies all type variables that are not already in scope, and are
2384 mentioned in the type quantified over.
2385 </Para>
2386
2387 <Para>
2388 As for type signatures, implicit quantification happens for non-overloaded
2389 types too.  So if you write this:
2390
2391 <ProgramListing>
2392   data T a = MkT (Either a b) (b -> b)
2393 </ProgramListing>
2394
2395 it's just as if you had written this:
2396
2397 <ProgramListing>
2398   data T a = MkT (forall b. Either a b) (forall b. b -> b)
2399 </ProgramListing>
2400
2401 That is, since the type variable <Literal>b</Literal> isn't in scope, it's
2402 implicitly universally quantified.  (Arguably, it would be better
2403 to <Emphasis>require</Emphasis> explicit quantification on constructor arguments
2404 where that is what is wanted.  Feedback welcomed.)
2405 </Para>
2406
2407 </Sect2>
2408
2409 <Sect2>
2410 <Title>Construction </Title>
2411
2412 <Para>
2413 You construct values of types <Literal>T1, MonadT, Swizzle</Literal> by applying
2414 the constructor to suitable values, just as usual.  For example,
2415 </Para>
2416
2417 <Para>
2418
2419 <ProgramListing>
2420 (T1 (\xy->x) 3) :: T Int
2421
2422 (MkSwizzle sort)    :: Swizzle
2423 (MkSwizzle reverse) :: Swizzle
2424
2425 (let r x = Just x
2426      b m k = case m of
2427                 Just y -> k y
2428                 Nothing -> Nothing
2429   in
2430   MkMonad r b) :: MonadT Maybe
2431 </ProgramListing>
2432
2433 </Para>
2434
2435 <Para>
2436 The type of the argument can, as usual, be more general than the type
2437 required, as <Literal>(MkSwizzle reverse)</Literal> shows.  (<Function>reverse</Function>
2438 does not need the <Literal>Ord</Literal> constraint.)
2439 </Para>
2440
2441 </Sect2>
2442
2443 <Sect2>
2444 <Title>Pattern matching</Title>
2445
2446 <Para>
2447 When you use pattern matching, the bound variables may now have
2448 polymorphic types.  For example:
2449 </Para>
2450
2451 <Para>
2452
2453 <ProgramListing>
2454         f :: T a -> a -> (a, Char)
2455         f (T1 f k) x = (f k x, f 'c' 'd')
2456
2457         g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b]
2458         g (MkSwizzle s) xs f = s (map f (s xs))
2459
2460         h :: MonadT m -> [m a] -> m [a]
2461         h m [] = return m []
2462         h m (x:xs) = bind m x           $ \y ->
2463                       bind m (h m xs)   $ \ys ->
2464                       return m (y:ys)
2465 </ProgramListing>
2466
2467 </Para>
2468
2469 <Para>
2470 In the function <Function>h</Function> we use the record selectors <Literal>return</Literal>
2471 and <Literal>bind</Literal> to extract the polymorphic bind and return functions
2472 from the <Literal>MonadT</Literal> data structure, rather than using pattern
2473 matching.
2474 </Para>
2475
2476 <Para>
2477 You cannot pattern-match against an argument that is polymorphic.
2478 For example:
2479
2480 <ProgramListing>
2481         newtype TIM s a = TIM (ST s (Maybe a))
2482
2483         runTIM :: (forall s. TIM s a) -> Maybe a
2484         runTIM (TIM m) = runST m
2485 </ProgramListing>
2486
2487 </Para>
2488
2489 <Para>
2490 Here the pattern-match fails, because you can't pattern-match against
2491 an argument of type <Literal>(forall s. TIM s a)</Literal>.  Instead you
2492 must bind the variable and pattern match in the right hand side:
2493
2494 <ProgramListing>
2495         runTIM :: (forall s. TIM s a) -> Maybe a
2496         runTIM tm = case tm of { TIM m -> runST m }
2497 </ProgramListing>
2498
2499 The <Literal>tm</Literal> on the right hand side is (invisibly) instantiated, like
2500 any polymorphic value at its occurrence site, and now you can pattern-match
2501 against it.
2502 </Para>
2503
2504 </Sect2>
2505
2506 <Sect2>
2507 <Title>The partial-application restriction</Title>
2508
2509 <Para>
2510 There is really only one way in which data structures with polymorphic
2511 components might surprise you: you must not partially apply them.
2512 For example, this is illegal:
2513 </Para>
2514
2515 <Para>
2516
2517 <ProgramListing>
2518         map MkSwizzle [sort, reverse]
2519 </ProgramListing>
2520
2521 </Para>
2522
2523 <Para>
2524 The restriction is this: <Emphasis>every subexpression of the program must
2525 have a type that has no for-alls, except that in a function
2526 application (f e1&hellip;en) the partial applications are not subject to
2527 this rule</Emphasis>.  The restriction makes type inference feasible.
2528 </Para>
2529
2530 <Para>
2531 In the illegal example, the sub-expression <Literal>MkSwizzle</Literal> has the
2532 polymorphic type <Literal>(Ord b => [b] -> [b]) -> Swizzle</Literal> and is not
2533 a sub-expression of an enclosing application.  On the other hand, this
2534 expression is OK:
2535 </Para>
2536
2537 <Para>
2538
2539 <ProgramListing>
2540         map (T1 (\a b -> a)) [1,2,3]
2541 </ProgramListing>
2542
2543 </Para>
2544
2545 <Para>
2546 even though it involves a partial application of <Function>T1</Function>, because
2547 the sub-expression <Literal>T1 (\a b -> a)</Literal> has type <Literal>Int -> T
2548 Int</Literal>.
2549 </Para>
2550
2551 </Sect2>
2552
2553 <Sect2 id="sigs">
2554 <Title>Type signatures
2555 </Title>
2556
2557 <Para>
2558 Once you have data constructors with universally-quantified fields, or
2559 constants such as <Constant>runST</Constant> that have rank-2 types, it isn't long
2560 before you discover that you need more!  Consider:
2561 </Para>
2562
2563 <Para>
2564
2565 <ProgramListing>
2566   mkTs f x y = [T1 f x, T1 f y]
2567 </ProgramListing>
2568
2569 </Para>
2570
2571 <Para>
2572 <Function>mkTs</Function> is a fuction that constructs some values of type
2573 <Literal>T</Literal>, using some pieces passed to it.  The trouble is that since
2574 <Literal>f</Literal> is a function argument, Haskell assumes that it is
2575 monomorphic, so we'll get a type error when applying <Function>T1</Function> to
2576 it.  This is a rather silly example, but the problem really bites in
2577 practice.  Lots of people trip over the fact that you can't make
2578 "wrappers functions" for <Constant>runST</Constant> for exactly the same reason.
2579 In short, it is impossible to build abstractions around functions with
2580 rank-2 types.
2581 </Para>
2582
2583 <Para>
2584 The solution is fairly clear.  We provide the ability to give a rank-2
2585 type signature for <Emphasis>ordinary</Emphasis> functions (not only data
2586 constructors), thus:
2587 </Para>
2588
2589 <Para>
2590
2591 <ProgramListing>
2592   mkTs :: (forall b. b -> b -> b) -> a -> [T a]
2593   mkTs f x y = [T1 f x, T1 f y]
2594 </ProgramListing>
2595
2596 </Para>
2597
2598 <Para>
2599 This type signature tells the compiler to attribute <Literal>f</Literal> with
2600 the polymorphic type <Literal>(forall b. b -> b -> b)</Literal> when type
2601 checking the body of <Function>mkTs</Function>, so now the application of
2602 <Function>T1</Function> is fine.
2603 </Para>
2604
2605 <Para>
2606 There are two restrictions:
2607 </Para>
2608
2609 <Para>
2610
2611 <ItemizedList>
2612 <ListItem>
2613
2614 <Para>
2615  You can only define a rank 2 type, specified by the following
2616 grammar:
2617
2618
2619 <ProgramListing>
2620 rank2type ::= [forall tyvars .] [context =>] funty
2621 funty     ::= ([forall tyvars .] [context =>] ty) -> funty
2622             | ty
2623 ty        ::= ...current Haskell monotype syntax...
2624 </ProgramListing>
2625
2626
2627 Informally, the universal quantification must all be right at the beginning,
2628 or at the top level of a function argument.
2629
2630 </Para>
2631 </ListItem>
2632 <ListItem>
2633
2634 <Para>
2635  There is a restriction on the definition of a function whose
2636 type signature is a rank-2 type: the polymorphic arguments must be
2637 matched on the left hand side of the "<Literal>=</Literal>" sign.  You can't
2638 define <Function>mkTs</Function> like this:
2639
2640
2641 <ProgramListing>
2642 mkTs :: (forall b. b -> b -> b) -> a -> [T a]
2643 mkTs = \ f x y -> [T1 f x, T1 f y]
2644 </ProgramListing>
2645
2646
2647
2648 The same partial-application rule applies to ordinary functions with
2649 rank-2 types as applied to data constructors.
2650
2651 </Para>
2652 </ListItem>
2653
2654 </ItemizedList>
2655
2656 </Para>
2657
2658 </Sect2>
2659
2660
2661 <Sect2 id="hoist">
2662 <Title>Type synonyms and hoisting
2663 </Title>
2664
2665 <Para>
2666 GHC also allows you to write a <Literal>forall</Literal> in a type synonym, thus:
2667 <ProgramListing>
2668   type Discard a = forall b. a -> b -> a
2669
2670   f :: Discard a
2671   f x y = x
2672 </ProgramListing>
2673 However, it is often convenient to use these sort of synonyms at the right hand
2674 end of an arrow, thus:
2675 <ProgramListing>
2676   type Discard a = forall b. a -> b -> a
2677
2678   g :: Int -> Discard Int
2679   g x y z = x+y
2680 </ProgramListing>
2681 Simply expanding the type synonym would give
2682 <ProgramListing>
2683   g :: Int -> (forall b. Int -> b -> Int)
2684 </ProgramListing>
2685 but GHC "hoists" the <Literal>forall</Literal> to give the isomorphic type
2686 <ProgramListing>
2687   g :: forall b. Int -> Int -> b -> Int
2688 </ProgramListing>
2689 In general, the rule is this: <Emphasis>to determine the type specified by any explicit
2690 user-written type (e.g. in a type signature), GHC expands type synonyms and then repeatedly
2691 performs the transformation:</Emphasis>
2692 <ProgramListing>
2693   <Emphasis>type1</Emphasis> -> forall a. <Emphasis>type2</Emphasis>
2694 ==>
2695   forall a. <Emphasis>type1</Emphasis> -> <Emphasis>type2</Emphasis>
2696 </ProgramListing>
2697 (In fact, GHC tries to retain as much synonym information as possible for use in
2698 error messages, but that is a usability issue.)  This rule applies, of course, whether
2699 or not the <Literal>forall</Literal> comes from a synonym. For example, here is another
2700 valid way to write <Literal>g</Literal>'s type signature:
2701 <ProgramListing>
2702   g :: Int -> Int -> forall b. b -> Int
2703 </ProgramListing>
2704 </Para>
2705 </Sect2>
2706
2707 </Sect1>
2708
2709 <Sect1 id="existential-quantification">
2710 <Title>Existentially quantified data constructors
2711 </Title>
2712
2713 <Para>
2714 The idea of using existential quantification in data type declarations
2715 was suggested by Laufer (I believe, thought doubtless someone will
2716 correct me), and implemented in Hope+. It's been in Lennart
2717 Augustsson's <Command>hbc</Command> Haskell compiler for several years, and
2718 proved very useful.  Here's the idea.  Consider the declaration:
2719 </Para>
2720
2721 <Para>
2722
2723 <ProgramListing>
2724   data Foo = forall a. MkFoo a (a -> Bool)
2725            | Nil
2726 </ProgramListing>
2727
2728 </Para>
2729
2730 <Para>
2731 The data type <Literal>Foo</Literal> has two constructors with types:
2732 </Para>
2733
2734 <Para>
2735
2736 <ProgramListing>
2737   MkFoo :: forall a. a -> (a -> Bool) -> Foo
2738   Nil   :: Foo
2739 </ProgramListing>
2740
2741 </Para>
2742
2743 <Para>
2744 Notice that the type variable <Literal>a</Literal> in the type of <Function>MkFoo</Function>
2745 does not appear in the data type itself, which is plain <Literal>Foo</Literal>.
2746 For example, the following expression is fine:
2747 </Para>
2748
2749 <Para>
2750
2751 <ProgramListing>
2752   [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
2753 </ProgramListing>
2754
2755 </Para>
2756
2757 <Para>
2758 Here, <Literal>(MkFoo 3 even)</Literal> packages an integer with a function
2759 <Function>even</Function> that maps an integer to <Literal>Bool</Literal>; and <Function>MkFoo 'c'
2760 isUpper</Function> packages a character with a compatible function.  These
2761 two things are each of type <Literal>Foo</Literal> and can be put in a list.
2762 </Para>
2763
2764 <Para>
2765 What can we do with a value of type <Literal>Foo</Literal>?.  In particular,
2766 what happens when we pattern-match on <Function>MkFoo</Function>?
2767 </Para>
2768
2769 <Para>
2770
2771 <ProgramListing>
2772   f (MkFoo val fn) = ???
2773 </ProgramListing>
2774
2775 </Para>
2776
2777 <Para>
2778 Since all we know about <Literal>val</Literal> and <Function>fn</Function> is that they
2779 are compatible, the only (useful) thing we can do with them is to
2780 apply <Function>fn</Function> to <Literal>val</Literal> to get a boolean.  For example:
2781 </Para>
2782
2783 <Para>
2784
2785 <ProgramListing>
2786   f :: Foo -> Bool
2787   f (MkFoo val fn) = fn val
2788 </ProgramListing>
2789
2790 </Para>
2791
2792 <Para>
2793 What this allows us to do is to package heterogenous values
2794 together with a bunch of functions that manipulate them, and then treat
2795 that collection of packages in a uniform manner.  You can express
2796 quite a bit of object-oriented-like programming this way.
2797 </Para>
2798
2799 <Sect2 id="existential">
2800 <Title>Why existential?
2801 </Title>
2802
2803 <Para>
2804 What has this to do with <Emphasis>existential</Emphasis> quantification?
2805 Simply that <Function>MkFoo</Function> has the (nearly) isomorphic type
2806 </Para>
2807
2808 <Para>
2809
2810 <ProgramListing>
2811   MkFoo :: (exists a . (a, a -> Bool)) -> Foo
2812 </ProgramListing>
2813
2814 </Para>
2815
2816 <Para>
2817 But Haskell programmers can safely think of the ordinary
2818 <Emphasis>universally</Emphasis> quantified type given above, thereby avoiding
2819 adding a new existential quantification construct.
2820 </Para>
2821
2822 </Sect2>
2823
2824 <Sect2>
2825 <Title>Type classes</Title>
2826
2827 <Para>
2828 An easy extension (implemented in <Command>hbc</Command>) is to allow
2829 arbitrary contexts before the constructor.  For example:
2830 </Para>
2831
2832 <Para>
2833
2834 <ProgramListing>
2835 data Baz = forall a. Eq a => Baz1 a a
2836          | forall b. Show b => Baz2 b (b -> b)
2837 </ProgramListing>
2838
2839 </Para>
2840
2841 <Para>
2842 The two constructors have the types you'd expect:
2843 </Para>
2844
2845 <Para>
2846
2847 <ProgramListing>
2848 Baz1 :: forall a. Eq a => a -> a -> Baz
2849 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
2850 </ProgramListing>
2851
2852 </Para>
2853
2854 <Para>
2855 But when pattern matching on <Function>Baz1</Function> the matched values can be compared
2856 for equality, and when pattern matching on <Function>Baz2</Function> the first matched
2857 value can be converted to a string (as well as applying the function to it).
2858 So this program is legal:
2859 </Para>
2860
2861 <Para>
2862
2863 <ProgramListing>
2864   f :: Baz -> String
2865   f (Baz1 p q) | p == q    = "Yes"
2866                | otherwise = "No"
2867   f (Baz1 v fn)            = show (fn v)
2868 </ProgramListing>
2869
2870 </Para>
2871
2872 <Para>
2873 Operationally, in a dictionary-passing implementation, the
2874 constructors <Function>Baz1</Function> and <Function>Baz2</Function> must store the
2875 dictionaries for <Literal>Eq</Literal> and <Literal>Show</Literal> respectively, and
2876 extract it on pattern matching.
2877 </Para>
2878
2879 <Para>
2880 Notice the way that the syntax fits smoothly with that used for
2881 universal quantification earlier.
2882 </Para>
2883
2884 </Sect2>
2885
2886 <Sect2>
2887 <Title>Restrictions</Title>
2888
2889 <Para>
2890 There are several restrictions on the ways in which existentially-quantified
2891 constructors can be use.
2892 </Para>
2893
2894 <Para>
2895
2896 <ItemizedList>
2897 <ListItem>
2898
2899 <Para>
2900  When pattern matching, each pattern match introduces a new,
2901 distinct, type for each existential type variable.  These types cannot
2902 be unified with any other type, nor can they escape from the scope of
2903 the pattern match.  For example, these fragments are incorrect:
2904
2905
2906 <ProgramListing>
2907 f1 (MkFoo a f) = a
2908 </ProgramListing>
2909
2910
2911 Here, the type bound by <Function>MkFoo</Function> "escapes", because <Literal>a</Literal>
2912 is the result of <Function>f1</Function>.  One way to see why this is wrong is to
2913 ask what type <Function>f1</Function> has:
2914
2915
2916 <ProgramListing>
2917   f1 :: Foo -> a             -- Weird!
2918 </ProgramListing>
2919
2920
2921 What is this "<Literal>a</Literal>" in the result type? Clearly we don't mean
2922 this:
2923
2924
2925 <ProgramListing>
2926   f1 :: forall a. Foo -> a   -- Wrong!
2927 </ProgramListing>
2928
2929
2930 The original program is just plain wrong.  Here's another sort of error
2931
2932
2933 <ProgramListing>
2934   f2 (Baz1 a b) (Baz1 p q) = a==q
2935 </ProgramListing>
2936
2937
2938 It's ok to say <Literal>a==b</Literal> or <Literal>p==q</Literal>, but
2939 <Literal>a==q</Literal> is wrong because it equates the two distinct types arising
2940 from the two <Function>Baz1</Function> constructors.
2941
2942
2943 </Para>
2944 </ListItem>
2945 <ListItem>
2946
2947 <Para>
2948 You can't pattern-match on an existentially quantified
2949 constructor in a <Literal>let</Literal> or <Literal>where</Literal> group of
2950 bindings. So this is illegal:
2951
2952
2953 <ProgramListing>
2954   f3 x = a==b where { Baz1 a b = x }
2955 </ProgramListing>
2956
2957
2958 You can only pattern-match
2959 on an existentially-quantified constructor in a <Literal>case</Literal> expression or
2960 in the patterns of a function definition.
2961
2962 The reason for this restriction is really an implementation one.
2963 Type-checking binding groups is already a nightmare without
2964 existentials complicating the picture.  Also an existential pattern
2965 binding at the top level of a module doesn't make sense, because it's
2966 not clear how to prevent the existentially-quantified type "escaping".
2967 So for now, there's a simple-to-state restriction.  We'll see how
2968 annoying it is.
2969
2970 </Para>
2971 </ListItem>
2972 <ListItem>
2973
2974 <Para>
2975 You can't use existential quantification for <Literal>newtype</Literal>
2976 declarations.  So this is illegal:
2977
2978
2979 <ProgramListing>
2980   newtype T = forall a. Ord a => MkT a
2981 </ProgramListing>
2982
2983
2984 Reason: a value of type <Literal>T</Literal> must be represented as a pair
2985 of a dictionary for <Literal>Ord t</Literal> and a value of type <Literal>t</Literal>.
2986 That contradicts the idea that <Literal>newtype</Literal> should have no
2987 concrete representation.  You can get just the same efficiency and effect
2988 by using <Literal>data</Literal> instead of <Literal>newtype</Literal>.  If there is no
2989 overloading involved, then there is more of a case for allowing
2990 an existentially-quantified <Literal>newtype</Literal>, because the <Literal>data</Literal>
2991 because the <Literal>data</Literal> version does carry an implementation cost,
2992 but single-field existentially quantified constructors aren't much
2993 use.  So the simple restriction (no existential stuff on <Literal>newtype</Literal>)
2994 stands, unless there are convincing reasons to change it.
2995
2996
2997 </Para>
2998 </ListItem>
2999 <ListItem>
3000
3001 <Para>
3002  You can't use <Literal>deriving</Literal> to define instances of a
3003 data type with existentially quantified data constructors.
3004
3005 Reason: in most cases it would not make sense. For example:&num;
3006
3007 <ProgramListing>
3008 data T = forall a. MkT [a] deriving( Eq )
3009 </ProgramListing>
3010
3011 To derive <Literal>Eq</Literal> in the standard way we would need to have equality
3012 between the single component of two <Function>MkT</Function> constructors:
3013
3014 <ProgramListing>
3015 instance Eq T where
3016   (MkT a) == (MkT b) = ???
3017 </ProgramListing>
3018
3019 But <VarName>a</VarName> and <VarName>b</VarName> have distinct types, and so can't be compared.
3020 It's just about possible to imagine examples in which the derived instance
3021 would make sense, but it seems altogether simpler simply to prohibit such
3022 declarations.  Define your own instances!
3023 </Para>
3024 </ListItem>
3025
3026 </ItemizedList>
3027
3028 </Para>
3029
3030 </Sect2>
3031
3032 </Sect1>
3033
3034 <Sect1 id="sec-assertions">
3035 <Title>Assertions
3036 <IndexTerm><Primary>Assertions</Primary></IndexTerm>
3037 </Title>
3038
3039 <Para>
3040 If you want to make use of assertions in your standard Haskell code, you
3041 could define a function like the following:
3042 </Para>
3043
3044 <Para>
3045
3046 <ProgramListing>
3047 assert :: Bool -> a -> a
3048 assert False x = error "assertion failed!"
3049 assert _     x = x
3050 </ProgramListing>
3051
3052 </Para>
3053
3054 <Para>
3055 which works, but gives you back a less than useful error message --
3056 an assertion failed, but which and where?
3057 </Para>
3058
3059 <Para>
3060 One way out is to define an extended <Function>assert</Function> function which also
3061 takes a descriptive string to include in the error message and
3062 perhaps combine this with the use of a pre-processor which inserts
3063 the source location where <Function>assert</Function> was used.
3064 </Para>
3065
3066 <Para>
3067 Ghc offers a helping hand here, doing all of this for you. For every
3068 use of <Function>assert</Function> in the user's source:
3069 </Para>
3070
3071 <Para>
3072
3073 <ProgramListing>
3074 kelvinToC :: Double -> Double
3075 kelvinToC k = assert (k &gt;= 0.0) (k+273.15)
3076 </ProgramListing>
3077
3078 </Para>
3079
3080 <Para>
3081 Ghc will rewrite this to also include the source location where the
3082 assertion was made,
3083 </Para>
3084
3085 <Para>
3086
3087 <ProgramListing>
3088 assert pred val ==> assertError "Main.hs|15" pred val
3089 </ProgramListing>
3090
3091 </Para>
3092
3093 <Para>
3094 The rewrite is only performed by the compiler when it spots
3095 applications of <Function>Exception.assert</Function>, so you can still define and
3096 use your own versions of <Function>assert</Function>, should you so wish. If not,
3097 import <Literal>Exception</Literal> to make use <Function>assert</Function> in your code.
3098 </Para>
3099
3100 <Para>
3101 To have the compiler ignore uses of assert, use the compiler option
3102 <Option>-fignore-asserts</Option>. <IndexTerm><Primary>-fignore-asserts option</Primary></IndexTerm> That is,
3103 expressions of the form <Literal>assert pred e</Literal> will be rewritten to <Literal>e</Literal>.
3104 </Para>
3105
3106 <Para>
3107 Assertion failures can be caught, see the documentation for the
3108 <literal>Exception</literal> library (<xref linkend="sec-Exception">)
3109 for the details.
3110 </Para>
3111
3112 </Sect1>
3113
3114 <Sect1 id="scoped-type-variables">
3115 <Title>Scoped Type Variables
3116 </Title>
3117
3118 <Para>
3119 A <Emphasis>pattern type signature</Emphasis> can introduce a <Emphasis>scoped type
3120 variable</Emphasis>.  For example
3121 </Para>
3122
3123 <Para>
3124
3125 <ProgramListing>
3126 f (xs::[a]) = ys ++ ys
3127            where
3128               ys :: [a]
3129               ys = reverse xs
3130 </ProgramListing>
3131
3132 </Para>
3133
3134 <Para>
3135 The pattern <Literal>(xs::[a])</Literal> includes a type signature for <VarName>xs</VarName>.
3136 This brings the type variable <Literal>a</Literal> into scope; it scopes over
3137 all the patterns and right hand sides for this equation for <Function>f</Function>.
3138 In particular, it is in scope at the type signature for <VarName>y</VarName>.
3139 </Para>
3140
3141 <Para>
3142 At ordinary type signatures, such as that for <VarName>ys</VarName>, any type variables
3143 mentioned in the type signature <Emphasis>that are not in scope</Emphasis> are
3144 implicitly universally quantified.  (If there are no type variables in
3145 scope, all type variables mentioned in the signature are universally
3146 quantified, which is just as in Haskell 98.)  In this case, since <VarName>a</VarName>
3147 is in scope, it is not universally quantified, so the type of <VarName>ys</VarName> is
3148 the same as that of <VarName>xs</VarName>.  In Haskell 98 it is not possible to declare
3149 a type for <VarName>ys</VarName>; a major benefit of scoped type variables is that
3150 it becomes possible to do so.
3151 </Para>
3152
3153 <Para>
3154 Scoped type variables are implemented in both GHC and Hugs.  Where the
3155 implementations differ from the specification below, those differences
3156 are noted.
3157 </Para>
3158
3159 <Para>
3160 So much for the basic idea.  Here are the details.
3161 </Para>
3162
3163 <Sect2>
3164 <Title>Scope and implicit quantification</Title>
3165
3166 <Para>
3167
3168 <ItemizedList>
3169 <ListItem>
3170
3171 <Para>
3172  All the type variables mentioned in the patterns for a single
3173 function definition equation, that are not already in scope,
3174 are brought into scope by the patterns.  We describe this set as
3175 the <Emphasis>type variables bound by the equation</Emphasis>.
3176
3177 </Para>
3178 </ListItem>
3179 <ListItem>
3180
3181 <Para>
3182  The type variables thus brought into scope may be mentioned
3183 in ordinary type signatures or pattern type signatures anywhere within
3184 their scope.
3185
3186 </Para>
3187 </ListItem>
3188 <ListItem>
3189
3190 <Para>
3191  In ordinary type signatures, any type variable mentioned in the
3192 signature that is in scope is <Emphasis>not</Emphasis> universally quantified.
3193
3194 </Para>
3195 </ListItem>
3196 <ListItem>
3197
3198 <Para>
3199  Ordinary type signatures do not bring any new type variables
3200 into scope (except in the type signature itself!). So this is illegal:
3201
3202
3203 <ProgramListing>
3204   f :: a -> a
3205   f x = x::a
3206 </ProgramListing>
3207
3208
3209 It's illegal because <VarName>a</VarName> is not in scope in the body of <Function>f</Function>,
3210 so the ordinary signature <Literal>x::a</Literal> is equivalent to <Literal>x::forall a.a</Literal>;
3211 and that is an incorrect typing.
3212
3213 </Para>
3214 </ListItem>
3215 <ListItem>
3216
3217 <Para>
3218  There is no implicit universal quantification on pattern type
3219 signatures, nor may one write an explicit <Literal>forall</Literal> type in a pattern
3220 type signature.  The pattern type signature is a monotype.
3221
3222 </Para>
3223 </ListItem>
3224 <ListItem>
3225
3226 <Para>
3227
3228 The type variables in the head of a <Literal>class</Literal> or <Literal>instance</Literal> declaration
3229 scope over the methods defined in the <Literal>where</Literal> part.  For example:
3230
3231
3232 <ProgramListing>
3233   class C a where
3234     op :: [a] -> a
3235
3236     op xs = let ys::[a]
3237                 ys = reverse xs
3238             in
3239             head ys
3240 </ProgramListing>
3241
3242
3243 (Not implemented in Hugs yet, Dec 98).
3244 </Para>
3245 </ListItem>
3246
3247 </ItemizedList>
3248
3249 </Para>
3250
3251 </Sect2>
3252
3253 <Sect2>
3254 <Title>Polymorphism</Title>
3255
3256 <Para>
3257
3258 <ItemizedList>
3259 <ListItem>
3260
3261 <Para>
3262  Pattern type signatures are completely orthogonal to ordinary, separate
3263 type signatures.  The two can be used independently or together.  There is
3264 no scoping associated with the names of the type variables in a separate type signature.
3265
3266
3267 <ProgramListing>
3268    f :: [a] -> [a]
3269    f (xs::[b]) = reverse xs
3270 </ProgramListing>
3271
3272
3273 </Para>
3274 </ListItem>
3275 <ListItem>
3276
3277 <Para>
3278  The function must be polymorphic in the type variables
3279 bound by all its equations.  Operationally, the type variables bound
3280 by one equation must not:
3281
3282
3283 <ItemizedList>
3284 <ListItem>
3285
3286 <Para>
3287  Be unified with a type (such as <Literal>Int</Literal>, or <Literal>[a]</Literal>).
3288 </Para>
3289 </ListItem>
3290 <ListItem>
3291
3292 <Para>
3293  Be unified with a type variable free in the environment.
3294 </Para>
3295 </ListItem>
3296 <ListItem>
3297
3298 <Para>
3299  Be unified with each other.  (They may unify with the type variables
3300 bound by another equation for the same function, of course.)
3301 </Para>
3302 </ListItem>
3303
3304 </ItemizedList>
3305
3306
3307 For example, the following all fail to type check:
3308
3309
3310 <ProgramListing>
3311   f (x::a) (y::b) = [x,y]       -- a unifies with b
3312
3313   g (x::a) = x + 1::Int         -- a unifies with Int
3314
3315   h x = let k (y::a) = [x,y]    -- a is free in the
3316         in k x                  -- environment
3317
3318   k (x::a) True    = ...        -- a unifies with Int
3319   k (x::Int) False = ...
3320
3321   w :: [b] -> [b]
3322   w (x::a) = x                  -- a unifies with [b]
3323 </ProgramListing>
3324
3325
3326 </Para>
3327 </ListItem>
3328 <ListItem>
3329
3330 <Para>
3331  The pattern-bound type variable may, however, be constrained
3332 by the context of the principal type, thus:
3333
3334
3335 <ProgramListing>
3336   f (x::a) (y::a) = x+y*2
3337 </ProgramListing>
3338
3339
3340 gets the inferred type: <Literal>forall a. Num a =&gt; a -&gt; a -&gt; a</Literal>.
3341 </Para>
3342 </ListItem>
3343
3344 </ItemizedList>
3345
3346 </Para>
3347
3348 </Sect2>
3349
3350 <Sect2>
3351 <Title>Result type signatures</Title>
3352
3353 <Para>
3354
3355 <ItemizedList>
3356 <ListItem>
3357
3358 <Para>
3359  The result type of a function can be given a signature,
3360 thus:
3361
3362
3363 <ProgramListing>
3364   f (x::a) :: [a] = [x,x,x]
3365 </ProgramListing>
3366
3367
3368 The final <Literal>:: [a]</Literal> after all the patterns gives a signature to the
3369 result type.  Sometimes this is the only way of naming the type variable
3370 you want:
3371
3372
3373 <ProgramListing>
3374   f :: Int -> [a] -> [a]
3375   f n :: ([a] -> [a]) = let g (x::a, y::a) = (y,x)
3376                         in \xs -> map g (reverse xs `zip` xs)
3377 </ProgramListing>
3378
3379
3380 </Para>
3381 </ListItem>
3382
3383 </ItemizedList>
3384
3385 </Para>
3386
3387 <Para>
3388 Result type signatures are not yet implemented in Hugs.
3389 </Para>
3390
3391 </Sect2>
3392
3393 <Sect2>
3394 <Title>Pattern signatures on other constructs</Title>
3395
3396 <Para>
3397
3398 <ItemizedList>
3399 <ListItem>
3400
3401 <Para>
3402  A pattern type signature can be on an arbitrary sub-pattern, not
3403 just on a variable:
3404
3405
3406 <ProgramListing>
3407   f ((x,y)::(a,b)) = (y,x) :: (b,a)
3408 </ProgramListing>
3409
3410
3411 </Para>
3412 </ListItem>
3413 <ListItem>
3414
3415 <Para>
3416  Pattern type signatures, including the result part, can be used
3417 in lambda abstractions:
3418
3419
3420 <ProgramListing>
3421   (\ (x::a, y) :: a -> x)
3422 </ProgramListing>
3423
3424
3425 Type variables bound by these patterns must be polymorphic in
3426 the sense defined above.
3427 For example:
3428
3429
3430 <ProgramListing>
3431   f1 (x::c) = f1 x      -- ok
3432   f2 = \(x::c) -> f2 x  -- not ok
3433 </ProgramListing>
3434
3435
3436 Here, <Function>f1</Function> is OK, but <Function>f2</Function> is not, because <VarName>c</VarName> gets unified
3437 with a type variable free in the environment, in this
3438 case, the type of <Function>f2</Function>, which is in the environment when
3439 the lambda abstraction is checked.
3440
3441 </Para>
3442 </ListItem>
3443 <ListItem>
3444
3445 <Para>
3446  Pattern type signatures, including the result part, can be used
3447 in <Literal>case</Literal> expressions:
3448
3449
3450 <ProgramListing>
3451   case e of { (x::a, y) :: a -> x }
3452 </ProgramListing>
3453
3454
3455 The pattern-bound type variables must, as usual,
3456 be polymorphic in the following sense: each case alternative,
3457 considered as a lambda abstraction, must be polymorphic.
3458 Thus this is OK:
3459
3460
3461 <ProgramListing>
3462   case (True,False) of { (x::a, y) -> x }
3463 </ProgramListing>
3464
3465
3466 Even though the context is that of a pair of booleans,
3467 the alternative itself is polymorphic.  Of course, it is
3468 also OK to say:
3469
3470
3471 <ProgramListing>
3472   case (True,False) of { (x::Bool, y) -> x }
3473 </ProgramListing>
3474
3475
3476 </Para>
3477 </ListItem>
3478 <ListItem>
3479
3480 <Para>
3481 To avoid ambiguity, the type after the &ldquo;<Literal>::</Literal>&rdquo; in a result
3482 pattern signature on a lambda or <Literal>case</Literal> must be atomic (i.e. a single
3483 token or a parenthesised type of some sort).  To see why,
3484 consider how one would parse this:
3485
3486
3487 <ProgramListing>
3488   \ x :: a -> b -> x
3489 </ProgramListing>
3490
3491
3492 </Para>
3493 </ListItem>
3494 <ListItem>
3495
3496 <Para>
3497  Pattern type signatures that bind new type variables
3498 may not be used in pattern bindings at all.
3499 So this is illegal:
3500
3501
3502 <ProgramListing>
3503   f x = let (y, z::a) = x in ...
3504 </ProgramListing>
3505
3506
3507 But these are OK, because they do not bind fresh type variables:
3508
3509
3510 <ProgramListing>
3511   f1 x            = let (y, z::Int) = x in ...
3512   f2 (x::(Int,a)) = let (y, z::a)   = x in ...
3513 </ProgramListing>
3514
3515
3516 However a single variable is considered a degenerate function binding,
3517 rather than a degerate pattern binding, so this is permitted, even
3518 though it binds a type variable:
3519
3520
3521 <ProgramListing>
3522   f :: (b->b) = \(x::b) -> x
3523 </ProgramListing>
3524
3525
3526 </Para>
3527 </ListItem>
3528
3529 </ItemizedList>
3530
3531 Such degnerate function bindings do not fall under the monomorphism
3532 restriction.  Thus:
3533 </Para>
3534
3535 <Para>
3536
3537 <ProgramListing>
3538   g :: a -> a -> Bool = \x y. x==y
3539 </ProgramListing>
3540
3541 </Para>
3542
3543 <Para>
3544 Here <Function>g</Function> has type <Literal>forall a. Eq a =&gt; a -&gt; a -&gt; Bool</Literal>, just as if
3545 <Function>g</Function> had a separate type signature.  Lacking a type signature, <Function>g</Function>
3546 would get a monomorphic type.
3547 </Para>
3548
3549 </Sect2>
3550
3551 <Sect2>
3552 <Title>Existentials</Title>
3553
3554 <Para>
3555
3556 <ItemizedList>
3557 <ListItem>
3558
3559 <Para>
3560  Pattern type signatures can bind existential type variables.
3561 For example:
3562
3563
3564 <ProgramListing>
3565   data T = forall a. MkT [a]
3566
3567   f :: T -> T
3568   f (MkT [t::a]) = MkT t3
3569                  where
3570                    t3::[a] = [t,t,t]
3571 </ProgramListing>
3572
3573
3574 </Para>
3575 </ListItem>
3576
3577 </ItemizedList>
3578
3579 </Para>
3580
3581 </Sect2>
3582
3583 </Sect1>
3584
3585 <Sect1 id="pragmas">
3586 <Title>Pragmas
3587 </Title>
3588
3589 <Para>
3590 GHC supports several pragmas, or instructions to the compiler placed
3591 in the source code.  Pragmas don't affect the meaning of the program,
3592 but they might affect the efficiency of the generated code.
3593 </Para>
3594
3595 <Sect2 id="inline-pragma">
3596 <Title>INLINE pragma
3597
3598 <IndexTerm><Primary>INLINE pragma</Primary></IndexTerm>
3599 <IndexTerm><Primary>pragma, INLINE</Primary></IndexTerm></Title>
3600
3601 <Para>
3602 GHC (with <Option>-O</Option>, as always) tries to inline (or &ldquo;unfold&rdquo;)
3603 functions/values that are &ldquo;small enough,&rdquo; thus avoiding the call
3604 overhead and possibly exposing other more-wonderful optimisations.
3605 </Para>
3606
3607 <Para>
3608 You will probably see these unfoldings (in Core syntax) in your
3609 interface files.
3610 </Para>
3611
3612 <Para>
3613 Normally, if GHC decides a function is &ldquo;too expensive&rdquo; to inline, it
3614 will not do so, nor will it export that unfolding for other modules to
3615 use.
3616 </Para>
3617
3618 <Para>
3619 The sledgehammer you can bring to bear is the
3620 <Literal>INLINE</Literal><IndexTerm><Primary>INLINE pragma</Primary></IndexTerm> pragma, used thusly:
3621
3622 <ProgramListing>
3623 key_function :: Int -> String -> (Bool, Double)
3624
3625 #ifdef __GLASGOW_HASKELL__
3626 {-# INLINE key_function #-}
3627 #endif
3628 </ProgramListing>
3629
3630 (You don't need to do the C pre-processor carry-on unless you're going
3631 to stick the code through HBC&mdash;it doesn't like <Literal>INLINE</Literal> pragmas.)
3632 </Para>
3633
3634 <Para>
3635 The major effect of an <Literal>INLINE</Literal> pragma is to declare a function's
3636 &ldquo;cost&rdquo; to be very low.  The normal unfolding machinery will then be
3637 very keen to inline it.
3638 </Para>
3639
3640 <Para>
3641 An <Literal>INLINE</Literal> pragma for a function can be put anywhere its type
3642 signature could be put.
3643 </Para>
3644
3645 <Para>
3646 <Literal>INLINE</Literal> pragmas are a particularly good idea for the
3647 <Literal>then</Literal>/<Literal>return</Literal> (or <Literal>bind</Literal>/<Literal>unit</Literal>) functions in a monad.
3648 For example, in GHC's own <Literal>UniqueSupply</Literal> monad code, we have:
3649
3650 <ProgramListing>
3651 #ifdef __GLASGOW_HASKELL__
3652 {-# INLINE thenUs #-}
3653 {-# INLINE returnUs #-}
3654 #endif
3655 </ProgramListing>
3656
3657 </Para>
3658
3659 </Sect2>
3660
3661 <Sect2 id="noinline-pragma">
3662 <Title>NOINLINE pragma
3663 </Title>
3664
3665 <Para>
3666 <IndexTerm><Primary>NOINLINE pragma</Primary></IndexTerm>
3667 <IndexTerm><Primary>pragma, NOINLINE</Primary></IndexTerm>
3668 </Para>
3669
3670 <Para>
3671 The <Literal>NOINLINE</Literal> pragma does exactly what you'd expect: it stops the
3672 named function from being inlined by the compiler.  You shouldn't ever
3673 need to do this, unless you're very cautious about code size.
3674 </Para>
3675
3676 </Sect2>
3677
3678 <Sect2 id="specialize-pragma">
3679 <Title>SPECIALIZE pragma
3680 </Title>
3681
3682 <Para>
3683 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3684 <IndexTerm><Primary>pragma, SPECIALIZE</Primary></IndexTerm>
3685 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3686 </Para>
3687
3688 <Para>
3689 (UK spelling also accepted.)  For key overloaded functions, you can
3690 create extra versions (NB: more code space) specialised to particular
3691 types.  Thus, if you have an overloaded function:
3692 </Para>
3693
3694 <Para>
3695
3696 <ProgramListing>
3697 hammeredLookup :: Ord key => [(key, value)] -> key -> value
3698 </ProgramListing>
3699
3700 </Para>
3701
3702 <Para>
3703 If it is heavily used on lists with <Literal>Widget</Literal> keys, you could
3704 specialise it as follows:
3705
3706 <ProgramListing>
3707 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
3708 </ProgramListing>
3709
3710 </Para>
3711
3712 <Para>
3713 To get very fancy, you can also specify a named function to use for
3714 the specialised value, by adding <Literal>= blah</Literal>, as in:
3715
3716 <ProgramListing>
3717 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
3718 </ProgramListing>
3719
3720 It's <Emphasis>Your Responsibility</Emphasis> to make sure that <Function>blah</Function> really
3721 behaves as a specialised version of <Function>hammeredLookup</Function>!!!
3722 </Para>
3723
3724 <Para>
3725 NOTE: the <Literal>=blah</Literal> feature isn't implemented in GHC 4.xx.
3726 </Para>
3727
3728 <Para>
3729 An example in which the <Literal>= blah</Literal> form will Win Big:
3730
3731 <ProgramListing>
3732 toDouble :: Real a => a -> Double
3733 toDouble = fromRational . toRational
3734
3735 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
3736 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
3737 </ProgramListing>
3738
3739 The <Function>i2d</Function> function is virtually one machine instruction; the
3740 default conversion&mdash;via an intermediate <Literal>Rational</Literal>&mdash;is obscenely
3741 expensive by comparison.
3742 </Para>
3743
3744 <Para>
3745 By using the US spelling, your <Literal>SPECIALIZE</Literal> pragma will work with
3746 HBC, too.  Note that HBC doesn't support the <Literal>= blah</Literal> form.
3747 </Para>
3748
3749 <Para>
3750 A <Literal>SPECIALIZE</Literal> pragma for a function can be put anywhere its type
3751 signature could be put.
3752 </Para>
3753
3754 </Sect2>
3755
3756 <Sect2 id="specialize-instance-pragma">
3757 <Title>SPECIALIZE instance pragma
3758 </Title>
3759
3760 <Para>
3761 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3762 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3763 Same idea, except for instance declarations.  For example:
3764
3765 <ProgramListing>
3766 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
3767
3768 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
3769 </ProgramListing>
3770
3771 Compatible with HBC, by the way.
3772 </Para>
3773
3774 </Sect2>
3775
3776 <Sect2 id="line-pragma">
3777 <Title>LINE pragma
3778 </Title>
3779
3780 <Para>
3781 <IndexTerm><Primary>LINE pragma</Primary></IndexTerm>
3782 <IndexTerm><Primary>pragma, LINE</Primary></IndexTerm>
3783 </Para>
3784
3785 <Para>
3786 This pragma is similar to C's <Literal>&num;line</Literal> pragma, and is mainly for use in
3787 automatically generated Haskell code.  It lets you specify the line
3788 number and filename of the original code; for example
3789 </Para>
3790
3791 <Para>
3792
3793 <ProgramListing>
3794 {-# LINE 42 "Foo.vhs" #-}
3795 </ProgramListing>
3796
3797 </Para>
3798
3799 <Para>
3800 if you'd generated the current file from something called <Filename>Foo.vhs</Filename>
3801 and this line corresponds to line 42 in the original.  GHC will adjust
3802 its error messages to refer to the line/file named in the <Literal>LINE</Literal>
3803 pragma.
3804 </Para>
3805
3806 </Sect2>
3807
3808 <Sect2>
3809 <Title>RULES pragma</Title>
3810
3811 <Para>
3812 The RULES pragma lets you specify rewrite rules.  It is described in
3813 <XRef LinkEnd="rewrite-rules">.
3814 </Para>
3815
3816 </Sect2>
3817
3818 </Sect1>
3819
3820 <Sect1 id="rewrite-rules">
3821 <Title>Rewrite rules
3822
3823 <IndexTerm><Primary>RULES pagma</Primary></IndexTerm>
3824 <IndexTerm><Primary>pragma, RULES</Primary></IndexTerm>
3825 <IndexTerm><Primary>rewrite rules</Primary></IndexTerm></Title>
3826
3827 <Para>
3828 The programmer can specify rewrite rules as part of the source program
3829 (in a pragma).  GHC applies these rewrite rules wherever it can.
3830 </Para>
3831
3832 <Para>
3833 Here is an example:
3834
3835 <ProgramListing>
3836   {-# RULES
3837         "map/map"       forall f g xs. map f (map g xs) = map (f.g) xs
3838   #-}
3839 </ProgramListing>
3840
3841 </Para>
3842
3843 <Sect2>
3844 <Title>Syntax</Title>
3845
3846 <Para>
3847 From a syntactic point of view:
3848
3849 <ItemizedList>
3850 <ListItem>
3851
3852 <Para>
3853  Each rule has a name, enclosed in double quotes.  The name itself has
3854 no significance at all.  It is only used when reporting how many times the rule fired.
3855 </Para>
3856 </ListItem>
3857 <ListItem>
3858
3859 <Para>
3860  There may be zero or more rules in a <Literal>RULES</Literal> pragma.
3861 </Para>
3862 </ListItem>
3863 <ListItem>
3864
3865 <Para>
3866  Layout applies in a <Literal>RULES</Literal> pragma.  Currently no new indentation level
3867 is set, so you must lay out your rules starting in the same column as the
3868 enclosing definitions.
3869 </Para>
3870 </ListItem>
3871 <ListItem>
3872
3873 <Para>
3874  Each variable mentioned in a rule must either be in scope (e.g. <Function>map</Function>),
3875 or bound by the <Literal>forall</Literal> (e.g. <Function>f</Function>, <Function>g</Function>, <Function>xs</Function>).  The variables bound by
3876 the <Literal>forall</Literal> are called the <Emphasis>pattern</Emphasis> variables.  They are separated
3877 by spaces, just like in a type <Literal>forall</Literal>.
3878 </Para>
3879 </ListItem>
3880 <ListItem>
3881
3882 <Para>
3883  A pattern variable may optionally have a type signature.
3884 If the type of the pattern variable is polymorphic, it <Emphasis>must</Emphasis> have a type signature.
3885 For example, here is the <Literal>foldr/build</Literal> rule:
3886
3887 <ProgramListing>
3888 "fold/build"  forall k z (g::forall b. (a->b->b) -> b -> b) .
3889               foldr k z (build g) = g k z
3890 </ProgramListing>
3891
3892 Since <Function>g</Function> has a polymorphic type, it must have a type signature.
3893
3894 </Para>
3895 </ListItem>
3896 <ListItem>
3897
3898 <Para>
3899 The left hand side of a rule must consist of a top-level variable applied
3900 to arbitrary expressions.  For example, this is <Emphasis>not</Emphasis> OK:
3901
3902 <ProgramListing>
3903 "wrong1"   forall e1 e2.  case True of { True -> e1; False -> e2 } = e1
3904 "wrong2"   forall f.      f True = True
3905 </ProgramListing>
3906
3907 In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong2"</Literal>, the LHS has a pattern variable
3908 in the head.
3909 </Para>
3910 </ListItem>
3911 <ListItem>
3912
3913 <Para>
3914  A rule does not need to be in the same module as (any of) the
3915 variables it mentions, though of course they need to be in scope.
3916 </Para>
3917 </ListItem>
3918 <ListItem>
3919
3920 <Para>
3921  Rules are automatically exported from a module, just as instance declarations are.
3922 </Para>
3923 </ListItem>
3924
3925 </ItemizedList>
3926
3927 </Para>
3928
3929 </Sect2>
3930
3931 <Sect2>
3932 <Title>Semantics</Title>
3933
3934 <Para>
3935 From a semantic point of view:
3936
3937 <ItemizedList>
3938 <ListItem>
3939
3940 <Para>
3941 Rules are only applied if you use the <Option>-O</Option> flag.
3942 </Para>
3943 </ListItem>
3944
3945 <ListItem>
3946 <Para>
3947  Rules are regarded as left-to-right rewrite rules.
3948 When GHC finds an expression that is a substitution instance of the LHS
3949 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
3950 By "a substitution instance" we mean that the LHS can be made equal to the
3951 expression by substituting for the pattern variables.
3952
3953 </Para>
3954 </ListItem>
3955 <ListItem>
3956
3957 <Para>
3958  The LHS and RHS of a rule are typechecked, and must have the
3959 same type.
3960
3961 </Para>
3962 </ListItem>
3963 <ListItem>
3964
3965 <Para>
3966  GHC makes absolutely no attempt to verify that the LHS and RHS
3967 of a rule have the same meaning.  That is undecideable in general, and
3968 infeasible in most interesting cases.  The responsibility is entirely the programmer's!
3969
3970 </Para>
3971 </ListItem>
3972 <ListItem>
3973
3974 <Para>
3975  GHC makes no attempt to make sure that the rules are confluent or
3976 terminating.  For example:
3977
3978 <ProgramListing>
3979   "loop"        forall x,y.  f x y = f y x
3980 </ProgramListing>
3981
3982 This rule will cause the compiler to go into an infinite loop.
3983
3984 </Para>
3985 </ListItem>
3986 <ListItem>
3987
3988 <Para>
3989  If more than one rule matches a call, GHC will choose one arbitrarily to apply.
3990
3991 </Para>
3992 </ListItem>
3993 <ListItem>
3994 <Para>
3995  GHC currently uses a very simple, syntactic, matching algorithm
3996 for matching a rule LHS with an expression.  It seeks a substitution
3997 which makes the LHS and expression syntactically equal modulo alpha
3998 conversion.  The pattern (rule), but not the expression, is eta-expanded if
3999 necessary.  (Eta-expanding the epression can lead to laziness bugs.)
4000 But not beta conversion (that's called higher-order matching).
4001 </Para>
4002
4003 <Para>
4004 Matching is carried out on GHC's intermediate language, which includes
4005 type abstractions and applications.  So a rule only matches if the
4006 types match too.  See <XRef LinkEnd="rule-spec"> below.
4007 </Para>
4008 </ListItem>
4009 <ListItem>
4010
4011 <Para>
4012  GHC keeps trying to apply the rules as it optimises the program.
4013 For example, consider:
4014
4015 <ProgramListing>
4016   let s = map f
4017       t = map g
4018   in
4019   s (t xs)
4020 </ProgramListing>
4021
4022 The expression <Literal>s (t xs)</Literal> does not match the rule <Literal>"map/map"</Literal>, but GHC
4023 will substitute for <VarName>s</VarName> and <VarName>t</VarName>, giving an expression which does match.
4024 If <VarName>s</VarName> or <VarName>t</VarName> was (a) used more than once, and (b) large or a redex, then it would
4025 not be substituted, and the rule would not fire.
4026
4027 </Para>
4028 </ListItem>
4029 <ListItem>
4030
4031 <Para>
4032  In the earlier phases of compilation, GHC inlines <Emphasis>nothing
4033 that appears on the LHS of a rule</Emphasis>, because once you have substituted
4034 for something you can't match against it (given the simple minded
4035 matching).  So if you write the rule
4036
4037 <ProgramListing>
4038         "map/map"       forall f,g.  map f . map g = map (f.g)
4039 </ProgramListing>
4040
4041 this <Emphasis>won't</Emphasis> match the expression <Literal>map f (map g xs)</Literal>.
4042 It will only match something written with explicit use of ".".
4043 Well, not quite.  It <Emphasis>will</Emphasis> match the expression
4044
4045 <ProgramListing>
4046 wibble f g xs
4047 </ProgramListing>
4048
4049 where <Function>wibble</Function> is defined:
4050
4051 <ProgramListing>
4052 wibble f g = map f . map g
4053 </ProgramListing>
4054
4055 because <Function>wibble</Function> will be inlined (it's small).
4056
4057 Later on in compilation, GHC starts inlining even things on the
4058 LHS of rules, but still leaves the rules enabled.  This inlining
4059 policy is controlled by the per-simplification-pass flag <Option>-finline-phase</Option><Emphasis>n</Emphasis>.
4060
4061 </Para>
4062 </ListItem>
4063 <ListItem>
4064
4065 <Para>
4066  All rules are implicitly exported from the module, and are therefore
4067 in force in any module that imports the module that defined the rule, directly
4068 or indirectly.  (That is, if A imports B, which imports C, then C's rules are
4069 in force when compiling A.)  The situation is very similar to that for instance
4070 declarations.
4071 </Para>
4072 </ListItem>
4073
4074 </ItemizedList>
4075
4076 </Para>
4077
4078 </Sect2>
4079
4080 <Sect2>
4081 <Title>List fusion</Title>
4082
4083 <Para>
4084 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
4085 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
4086 intermediate list should be eliminated entirely.
4087 </Para>
4088
4089 <Para>
4090 The following are good producers:
4091
4092 <ItemizedList>
4093 <ListItem>
4094
4095 <Para>
4096  List comprehensions
4097 </Para>
4098 </ListItem>
4099 <ListItem>
4100
4101 <Para>
4102  Enumerations of <Literal>Int</Literal> and <Literal>Char</Literal> (e.g. <Literal>['a'..'z']</Literal>).
4103 </Para>
4104 </ListItem>
4105 <ListItem>
4106
4107 <Para>
4108  Explicit lists (e.g. <Literal>[True, False]</Literal>)
4109 </Para>
4110 </ListItem>
4111 <ListItem>
4112
4113 <Para>
4114  The cons constructor (e.g <Literal>3:4:[]</Literal>)
4115 </Para>
4116 </ListItem>
4117 <ListItem>
4118
4119 <Para>
4120  <Function>++</Function>
4121 </Para>
4122 </ListItem>
4123 <ListItem>
4124
4125 <Para>
4126  <Function>map</Function>
4127 </Para>
4128 </ListItem>
4129 <ListItem>
4130
4131 <Para>
4132  <Function>filter</Function>
4133 </Para>
4134 </ListItem>
4135 <ListItem>
4136
4137 <Para>
4138  <Function>iterate</Function>, <Function>repeat</Function>
4139 </Para>
4140 </ListItem>
4141 <ListItem>
4142
4143 <Para>
4144  <Function>zip</Function>, <Function>zipWith</Function>
4145 </Para>
4146 </ListItem>
4147
4148 </ItemizedList>
4149
4150 </Para>
4151
4152 <Para>
4153 The following are good consumers:
4154
4155 <ItemizedList>
4156 <ListItem>
4157
4158 <Para>
4159  List comprehensions
4160 </Para>
4161 </ListItem>
4162 <ListItem>
4163
4164 <Para>
4165  <Function>array</Function> (on its second argument)
4166 </Para>
4167 </ListItem>
4168 <ListItem>
4169
4170 <Para>
4171  <Function>length</Function>
4172 </Para>
4173 </ListItem>
4174 <ListItem>
4175
4176 <Para>
4177  <Function>++</Function> (on its first argument)
4178 </Para>
4179 </ListItem>
4180 <ListItem>
4181
4182 <Para>
4183  <Function>map</Function>
4184 </Para>
4185 </ListItem>
4186 <ListItem>
4187
4188 <Para>
4189  <Function>filter</Function>
4190 </Para>
4191 </ListItem>
4192 <ListItem>
4193
4194 <Para>
4195  <Function>concat</Function>
4196 </Para>
4197 </ListItem>
4198 <ListItem>
4199
4200 <Para>
4201  <Function>unzip</Function>, <Function>unzip2</Function>, <Function>unzip3</Function>, <Function>unzip4</Function>
4202 </Para>
4203 </ListItem>
4204 <ListItem>
4205
4206 <Para>
4207  <Function>zip</Function>, <Function>zipWith</Function> (but on one argument only; if both are good producers, <Function>zip</Function>
4208 will fuse with one but not the other)
4209 </Para>
4210 </ListItem>
4211 <ListItem>
4212
4213 <Para>
4214  <Function>partition</Function>
4215 </Para>
4216 </ListItem>
4217 <ListItem>
4218
4219 <Para>
4220  <Function>head</Function>
4221 </Para>
4222 </ListItem>
4223 <ListItem>
4224
4225 <Para>
4226  <Function>and</Function>, <Function>or</Function>, <Function>any</Function>, <Function>all</Function>
4227 </Para>
4228 </ListItem>
4229 <ListItem>
4230
4231 <Para>
4232  <Function>sequence&lowbar;</Function>
4233 </Para>
4234 </ListItem>
4235 <ListItem>
4236
4237 <Para>
4238  <Function>msum</Function>
4239 </Para>
4240 </ListItem>
4241 <ListItem>
4242
4243 <Para>
4244  <Function>sortBy</Function>
4245 </Para>
4246 </ListItem>
4247
4248 </ItemizedList>
4249
4250 </Para>
4251
4252 <Para>
4253 So, for example, the following should generate no intermediate lists:
4254
4255 <ProgramListing>
4256 array (1,10) [(i,i*i) | i &#60;- map (+ 1) [0..9]]
4257 </ProgramListing>
4258
4259 </Para>
4260
4261 <Para>
4262 This list could readily be extended; if there are Prelude functions that you use
4263 a lot which are not included, please tell us.
4264 </Para>
4265
4266 <Para>
4267 If you want to write your own good consumers or producers, look at the
4268 Prelude definitions of the above functions to see how to do so.
4269 </Para>
4270
4271 </Sect2>
4272
4273 <Sect2 id="rule-spec">
4274 <Title>Specialisation
4275 </Title>
4276
4277 <Para>
4278 Rewrite rules can be used to get the same effect as a feature
4279 present in earlier version of GHC:
4280
4281 <ProgramListing>
4282   {-# SPECIALIZE fromIntegral :: Int8 -> Int16 = int8ToInt16 #-}
4283 </ProgramListing>
4284
4285 This told GHC to use <Function>int8ToInt16</Function> instead of <Function>fromIntegral</Function> whenever
4286 the latter was called with type <Literal>Int8 -&gt; Int16</Literal>.  That is, rather than
4287 specialising the original definition of <Function>fromIntegral</Function> the programmer is
4288 promising that it is safe to use <Function>int8ToInt16</Function> instead.
4289 </Para>
4290
4291 <Para>
4292 This feature is no longer in GHC.  But rewrite rules let you do the
4293 same thing:
4294
4295 <ProgramListing>
4296 {-# RULES
4297   "fromIntegral/Int8/Int16" fromIntegral = int8ToInt16
4298 #-}
4299 </ProgramListing>
4300
4301 This slightly odd-looking rule instructs GHC to replace <Function>fromIntegral</Function>
4302 by <Function>int8ToInt16</Function> <Emphasis>whenever the types match</Emphasis>.  Speaking more operationally,
4303 GHC adds the type and dictionary applications to get the typed rule
4304
4305 <ProgramListing>
4306 forall (d1::Integral Int8) (d2::Num Int16) .
4307         fromIntegral Int8 Int16 d1 d2 = int8ToInt16
4308 </ProgramListing>
4309
4310 What is more,
4311 this rule does not need to be in the same file as fromIntegral,
4312 unlike the <Literal>SPECIALISE</Literal> pragmas which currently do (so that they
4313 have an original definition available to specialise).
4314 </Para>
4315
4316 </Sect2>
4317
4318 <Sect2>
4319 <Title>Controlling what's going on</Title>
4320
4321 <Para>
4322
4323 <ItemizedList>
4324 <ListItem>
4325
4326 <Para>
4327  Use <Option>-ddump-rules</Option> to see what transformation rules GHC is using.
4328 </Para>
4329 </ListItem>
4330 <ListItem>
4331
4332 <Para>
4333  Use <Option>-ddump-simpl-stats</Option> to see what rules are being fired.
4334 If you add <Option>-dppr-debug</Option> you get a more detailed listing.
4335 </Para>
4336 </ListItem>
4337 <ListItem>
4338
4339 <Para>
4340  The defintion of (say) <Function>build</Function> in <FileName>PrelBase.lhs</FileName> looks llike this:
4341
4342 <ProgramListing>
4343         build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
4344         {-# INLINE build #-}
4345         build g = g (:) []
4346 </ProgramListing>
4347
4348 Notice the <Literal>INLINE</Literal>!  That prevents <Literal>(:)</Literal> from being inlined when compiling
4349 <Literal>PrelBase</Literal>, so that an importing module will &ldquo;see&rdquo; the <Literal>(:)</Literal>, and can
4350 match it on the LHS of a rule.  <Literal>INLINE</Literal> prevents any inlining happening
4351 in the RHS of the <Literal>INLINE</Literal> thing.  I regret the delicacy of this.
4352
4353 </Para>
4354 </ListItem>
4355 <ListItem>
4356
4357 <Para>
4358  In <Filename>ghc/lib/std/PrelBase.lhs</Filename> look at the rules for <Function>map</Function> to
4359 see how to write rules that will do fusion and yet give an efficient
4360 program even if fusion doesn't happen.  More rules in <Filename>PrelList.lhs</Filename>.
4361 </Para>
4362 </ListItem>
4363
4364 </ItemizedList>
4365
4366 </Para>
4367
4368 </Sect2>
4369
4370 </Sect1>
4371
4372 <Sect1 id="generic-classes">
4373 <Title>Generic classes</Title>
4374
4375 <Para>
4376 The ideas behind this extension are described in detail in "Derivable type classes",
4377 Ralf Hinze and Simon Peyton Jones, Haskell Workshop, Montreal Sept 2000, pp94-105.
4378 An example will give the idea:
4379 </Para>
4380
4381 <ProgramListing>
4382   import Generics
4383
4384   class Bin a where
4385     toBin   :: a -> [Int]
4386     fromBin :: [Int] -> (a, [Int])
4387   
4388     toBin {| Unit |}    Unit      = []
4389     toBin {| a :+: b |} (Inl x)   = 0 : toBin x
4390     toBin {| a :+: b |} (Inr y)   = 1 : toBin y
4391     toBin {| a :*: b |} (x :*: y) = toBin x ++ toBin y
4392   
4393     fromBin {| Unit |}    bs      = (Unit, bs)
4394     fromBin {| a :+: b |} (0:bs)  = (Inl x, bs')    where (x,bs') = fromBin bs
4395     fromBin {| a :+: b |} (1:bs)  = (Inr y, bs')    where (y,bs') = fromBin bs
4396     fromBin {| a :*: b |} bs      = (x :*: y, bs'') where (x,bs' ) = fromBin bs
4397                                                           (y,bs'') = fromBin bs'
4398 </ProgramListing>
4399 <Para>
4400 This class declaration explains how <Literal>toBin</Literal> and <Literal>fromBin</Literal>
4401 work for arbitrary data types.  They do so by giving cases for unit, product, and sum,
4402 which are defined thus in the library module <Literal>Generics</Literal>:
4403 </Para>
4404 <ProgramListing>
4405   data Unit    = Unit
4406   data a :+: b = Inl a | Inr b
4407   data a :*: b = a :*: b
4408 </ProgramListing>
4409 <Para>
4410 Now you can make a data type into an instance of Bin like this:
4411 <ProgramListing>
4412   instance (Bin a, Bin b) => Bin (a,b)
4413   instance Bin a => Bin [a]
4414 </ProgramListing>
4415 That is, just leave off the "where" clasuse.  Of course, you can put in the
4416 where clause and over-ride whichever methods you please.
4417 </Para>
4418
4419     <Sect2>
4420       <Title> Using generics </Title>
4421       <Para>To use generics you need to</para>
4422       <ItemizedList>
4423         <ListItem>
4424           <Para>Use the <Option>-fgenerics</Option> flag.</Para>
4425         </ListItem>
4426         <ListItem>
4427           <Para>Import the module <Literal>Generics</Literal> from the
4428           <Literal>lang</Literal> package.  This import brings into
4429           scope the data types <Literal>Unit</Literal>,
4430           <Literal>:*:</Literal>, and <Literal>:+:</Literal>.  (You
4431           don't need this import if you don't mention these types
4432           explicitly; for example, if you are simply giving instance
4433           declarations.)</Para>
4434         </ListItem>
4435       </ItemizedList>
4436     </Sect2>
4437
4438 <Sect2> <Title> Changes wrt the paper </Title>
4439 <Para>
4440 Note that the type constructors <Literal>:+:</Literal> and <Literal>:*:</Literal> 
4441 can be written infix (indeed, you can now use
4442 any operator starting in a colon as an infix type constructor).  Also note that
4443 the type constructors are not exactly as in the paper (Unit instead of 1, etc).
4444 Finally, note that the syntax of the type patterns in the class declaration
4445 uses "<Literal>{|</Literal>" and "<Literal>{|</Literal>" brackets; curly braces
4446 alone would ambiguous when they appear on right hand sides (an extension we 
4447 anticipate wanting).
4448 </Para>
4449 </Sect2>
4450
4451 <Sect2> <Title>Terminology and restrictions</Title>
4452 <Para>
4453 Terminology.  A "generic default method" in a class declaration
4454 is one that is defined using type patterns as above.
4455 A "polymorphic default method" is a default method defined as in Haskell 98.
4456 A "generic class declaration" is a class declaration with at least one
4457 generic default method.
4458 </Para>
4459
4460 <Para>
4461 Restrictions:
4462 <ItemizedList>
4463 <ListItem>
4464 <Para>
4465 Alas, we do not yet implement the stuff about constructor names and 
4466 field labels.
4467 </Para>
4468 </ListItem>
4469
4470 <ListItem>
4471 <Para>
4472 A generic class can have only one parameter; you can't have a generic
4473 multi-parameter class.
4474 </Para>
4475 </ListItem>
4476
4477 <ListItem>
4478 <Para>
4479 A default method must be defined entirely using type patterns, or entirely
4480 without.  So this is illegal:
4481 <ProgramListing>
4482   class Foo a where
4483     op :: a -> (a, Bool)
4484     op {| Unit |} Unit = (Unit, True)
4485     op x               = (x,    False)
4486 </ProgramListing>
4487 However it is perfectly OK for some methods of a generic class to have 
4488 generic default methods and others to have polymorphic default methods.
4489 </Para>
4490 </ListItem>
4491
4492 <ListItem>
4493 <Para>
4494 The type variable(s) in the type pattern for a generic method declaration
4495 scope over the right hand side.  So this is legal (note the use of the type variable ``p'' in a type signature on the right hand side:
4496 <ProgramListing>
4497   class Foo a where
4498     op :: a -> Bool
4499     op {| p :*: q |} (x :*: y) = op (x :: p)
4500     ...
4501 </ProgramListing>
4502 </Para>
4503 </ListItem>
4504
4505 <ListItem>
4506 <Para>
4507 The type patterns in a generic default method must take one of the forms:
4508 <ProgramListing>
4509        a :+: b
4510        a :*: b
4511        Unit
4512 </ProgramListing>
4513 where "a" and "b" are type variables.  Furthermore, all the type patterns for
4514 a single type constructor (<Literal>:*:</Literal>, say) must be identical; they
4515 must use the same type variables.  So this is illegal:
4516 <ProgramListing>
4517   class Foo a where
4518     op :: a -> Bool
4519     op {| a :+: b |} (Inl x) = True
4520     op {| p :+: q |} (Inr y) = False
4521 </ProgramListing>
4522 The type patterns must be identical, even in equations for different methods of the class.
4523 So this too is illegal:
4524 <ProgramListing>
4525   class Foo a where
4526     op1 :: a -> Bool
4527     op {| a :*: b |} (Inl x) = True
4528
4529     op2 :: a -> Bool
4530     op {| p :*: q |} (Inr y) = False
4531 </ProgramListing>
4532 (The reason for this restriction is that we gather all the equations for a particular type consructor
4533 into a single generic instance declaration.)
4534 </Para>
4535 </ListItem>
4536
4537 <ListItem>
4538 <Para>
4539 A generic method declaration must give a case for each of the three type constructors.
4540 </Para>
4541 </ListItem>
4542
4543 <ListItem>
4544 <Para>
4545 The type for a generic method can be built only from:
4546   <ItemizedList>
4547   <ListItem> <Para> Function arrows </Para> </ListItem>
4548   <ListItem> <Para> Type variables </Para> </ListItem>
4549   <ListItem> <Para> Tuples </Para> </ListItem>
4550   <ListItem> <Para> Arbitrary types not involving type variables </Para> </ListItem>
4551   </ItemizedList>
4552 Here are some example type signatures for generic methods:
4553 <ProgramListing>
4554     op1 :: a -> Bool
4555     op2 :: Bool -> (a,Bool)
4556     op3 :: [Int] -> a -> a
4557     op4 :: [a] -> Bool
4558 </ProgramListing>
4559 Here, op1, op2, op3 are OK, but op4 is rejected, because it has a type variable
4560 inside a list.  
4561 </Para>
4562 <Para>
4563 This restriction is an implementation restriction: we just havn't got around to
4564 implementing the necessary bidirectional maps over arbitrary type constructors.
4565 It would be relatively easy to add specific type constructors, such as Maybe and list,
4566 to the ones that are allowed.</para>
4567 </ListItem>
4568
4569 <ListItem>
4570 <Para>
4571 In an instance declaration for a generic class, the idea is that the compiler
4572 will fill in the methods for you, based on the generic templates.  However it can only
4573 do so if
4574   <ItemizedList>
4575   <ListItem>
4576   <Para>
4577   The instance type is simple (a type constructor applied to type variables, as in Haskell 98).
4578   </Para>
4579   </ListItem>
4580   <ListItem>
4581   <Para>
4582   No constructor of the instance type has unboxed fields.
4583   </Para>
4584   </ListItem>
4585   </ItemizedList>
4586 (Of course, these things can only arise if you are already using GHC extensions.)
4587 However, you can still give an instance declarations for types which break these rules,
4588 provided you give explicit code to override any generic default methods.
4589 </Para>
4590 </ListItem>
4591
4592 </ItemizedList>
4593 </Para>
4594
4595 <Para>
4596 The option <Option>-ddump-deriv</Option> dumps incomprehensible stuff giving details of 
4597 what the compiler does with generic declarations.
4598 </Para>
4599
4600 </Sect2>
4601
4602 <Sect2> <Title> Another example </Title>
4603 <Para>
4604 Just to finish with, here's another example I rather like:
4605 <ProgramListing>
4606   class Tag a where
4607     nCons :: a -> Int
4608     nCons {| Unit |}    _ = 1
4609     nCons {| a :*: b |} _ = 1
4610     nCons {| a :+: b |} _ = nCons (bot::a) + nCons (bot::b)
4611   
4612     tag :: a -> Int
4613     tag {| Unit |}    _       = 1
4614     tag {| a :*: b |} _       = 1   
4615     tag {| a :+: b |} (Inl x) = tag x
4616     tag {| a :+: b |} (Inr y) = nCons (bot::a) + tag y
4617 </ProgramListing>
4618 </Para>
4619 </Sect2>
4620 </Sect1>
4621
4622 <!-- Emacs stuff:
4623      ;;; Local Variables: ***
4624      ;;; mode: sgml ***
4625      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter" "sect1") ***
4626      ;;; End: ***
4627  -->