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