[project @ 2000-01-05 11:14:06 by rrt]
[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 <Literal>-fglasgow-exts</Literal>
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 ``stuck'' on
14 performance because of the implementation costs of Haskell's
15 ``high-level'' features&mdash;you can always code ``under'' them.  In an
16 extreme case, you can write all your time-critical code in C, and then
17 just glue it together with Haskell!
18 </Para>
19
20 <Para>
21 Executive summary of our extensions:
22 </Para>
23
24 <Para>
25 <VariableList>
26
27 <VarListEntry>
28 <Term>Unboxed types and primitive operations:</Term>
29 <ListItem>
30 <Para>
31 You can get right down to the raw machine types and operations;
32 included in this are ``primitive arrays'' (direct access to Big Wads
33 of Bytes).  Please see <XRef LinkEnd="glasgow-unboxed"> and following.
34 </Para>
35 </ListItem>
36 </VarListEntry>
37
38 <VarListEntry>
39 <Term>Multi-parameter type classes:</Term>
40 <ListItem>
41 <Para>
42 GHC's type system supports extended type classes with multiple
43 parameters.  Please see <XRef LinkEnd="multi-param-type-classes">.
44 </Para>
45 </ListItem>
46 </VarListEntry>
47
48 <VarListEntry>
49 <Term>Local universal quantification:</Term>
50 <ListItem>
51 <Para>
52 GHC's type system supports explicit universal quantification in
53 constructor fields and function arguments.  This is useful for things
54 like defining <Literal>runST</Literal> from the state-thread world.  See <XRef LinkEnd="universal-quantification">.
55 </Para>
56 </ListItem>
57 </VarListEntry>
58
59 <VarListEntry>
60 <Term>Extistentially quantification in data types:</Term>
61 <ListItem>
62 <Para>
63 Some or all of the type variables in a datatype declaration may be
64 <Emphasis>existentially quantified</Emphasis>.  More details in <XRef LinkEnd="existential-quantification">.
65 </Para>
66 </ListItem>
67 </VarListEntry>
68
69 <VarListEntry>
70 <Term>Scoped type variables:</Term>
71 <ListItem>
72 <Para>
73 Scoped type variables enable the programmer to supply type signatures
74 for some nested declarations, where this would not be legal in Haskell
75 98.  Details in <XRef LinkEnd="scoped-type-variables">.
76 </Para>
77 </ListItem>
78 </VarListEntry>
79
80 <VarListEntry>
81 <Term>Calling out to C:</Term>
82 <ListItem>
83 <Para>
84 Just what it sounds like.  We provide <Emphasis>lots</Emphasis> of rope that you
85 can dangle around your neck.  Please see <XRef LinkEnd="glasgow-ccalls">.
86 </Para>
87 </ListItem>
88 </VarListEntry>
89
90 <VarListEntry>
91 <Term>Pragmas</Term>
92 <ListItem>
93 <Para>
94 Pragmas are special instructions to the compiler placed in the source
95 file.  The pragmas GHC supports are described in <XRef LinkEnd="pragmas">.
96 </Para>
97 </ListItem>
98 </VarListEntry>
99
100 <VarListEntry>
101 <Term>Rewrite rules:</Term>
102 <ListItem>
103 <Para>
104 The programmer can specify rewrite rules as part of the source program
105 (in a pragma).  GHC applies these rewrite rules wherever it can.
106 Details in <XRef LinkEnd="rewrite-rules">.
107 </Para>
108 </ListItem>
109 </VarListEntry>
110 </VariableList>
111 </Para>
112
113 <Para>
114 Before you get too carried away working at the lowest level (e.g.,
115 sloshing <Literal>MutableByteArray&num;</Literal>s around your program), you may wish to
116 check if there are system libraries that provide a ``Haskellised
117 veneer'' over the features you want.  See <XRef LinkEnd="ghc-prelude">.
118 </Para>
119
120 <Sect1 id="glasgow-unboxed">
121 <Title>Unboxed types
122 </Title>
123
124 <Para>
125 <IndexTerm><Primary>Unboxed types (Glasgow extension)</Primary></IndexTerm>
126 </Para>
127
128 <Para>
129 These types correspond to the ``raw machine'' types you would use in
130 C: <Literal>Int&num;</Literal> (long int), <Literal>Double&num;</Literal> (double), <Literal>Addr&num;</Literal> (void *), etc.  The
131 <Emphasis>primitive operations</Emphasis> (PrimOps) on these types are what you
132 might expect; e.g., <Literal>(+&num;)</Literal> is addition on <Literal>Int&num;</Literal>s, and is the
133 machine-addition that we all know and love&mdash;usually one instruction.
134 </Para>
135
136 <Para>
137 There are some restrictions on the use of unboxed types, the main one
138 being that you can't pass an unboxed value to a polymorphic function
139 or store one in a polymorphic data type.  This rules out things like
140 <Literal>[Int&num;]</Literal> (ie. lists of unboxed integers).  The reason for this
141 restriction is that polymorphic arguments and constructor fields are
142 assumed to be pointers: if an unboxed integer is stored in one of
143 these, the garbage collector would attempt to follow it, leading to
144 unpredictable space leaks.  Or a <Literal>seq</Literal> operation on the polymorphic
145 component may attempt to dereference the pointer, with disastrous
146 results.  Even worse, the unboxed value might be larger than a pointer
147 (<Literal>Double&num;</Literal> for instance).
148 </Para>
149
150 <Para>
151 Nevertheless, A numerically-intensive program using unboxed types can
152 go a <Emphasis>lot</Emphasis> faster than its ``standard'' counterpart&mdash;we saw a
153 threefold speedup on one example.
154 </Para>
155
156 <Para>
157 Please see <XRef LinkEnd="ghc-libs-ghc"> for the details of unboxed types and the
158 operations on them.
159 </Para>
160
161 </Sect1>
162
163 <Sect1 id="glasgow-ST-monad">
164 <Title>Primitive state-transformer monad
165 </Title>
166
167 <Para>
168 <IndexTerm><Primary>state transformers (Glasgow extensions)</Primary></IndexTerm>
169 <IndexTerm><Primary>ST monad (Glasgow extension)</Primary></IndexTerm>
170 </Para>
171
172 <Para>
173 This monad underlies our implementation of arrays, mutable and
174 immutable, and our implementation of I/O, including ``C calls''.
175 </Para>
176
177 <Para>
178 The <Literal>ST</Literal> library, which provides access to the <Literal>ST</Literal> monad, is a
179 GHC/Hugs extension library and is described in the separate <ULink
180 URL="libs.html"
181 >GHC/Hugs Extension Libraries</ULink
182 > document.
183 </Para>
184
185 </Sect1>
186
187 <Sect1 id="glasgow-prim-arrays">
188 <Title>Primitive arrays, mutable and otherwise
189 </Title>
190
191 <Para>
192 <IndexTerm><Primary>primitive arrays (Glasgow extension)</Primary></IndexTerm>
193 <IndexTerm><Primary>arrays, primitive (Glasgow extension)</Primary></IndexTerm>
194 </Para>
195
196 <Para>
197 GHC knows about quite a few flavours of Large Swathes of Bytes.
198 </Para>
199
200 <Para>
201 First, GHC distinguishes between primitive arrays of (boxed) Haskell
202 objects (type <Literal>Array&num; obj</Literal>) and primitive arrays of bytes (type
203 <Literal>ByteArray&num;</Literal>).
204 </Para>
205
206 <Para>
207 Second, it distinguishes between&hellip;
208 <VariableList>
209
210 <VarListEntry>
211 <Term>Immutable:</Term>
212 <ListItem>
213 <Para>
214 Arrays that do not change (as with ``standard'' Haskell arrays); you
215 can only read from them.  Obviously, they do not need the care and
216 attention of the state-transformer monad.
217 </Para>
218 </ListItem>
219 </VarListEntry>
220 <VarListEntry>
221 <Term>Mutable:</Term>
222 <ListItem>
223 <Para>
224 Arrays that may be changed or ``mutated.''  All the operations on them
225 live within the state-transformer monad and the updates happen
226 <Emphasis>in-place</Emphasis>.
227 </Para>
228 </ListItem>
229 </VarListEntry>
230 <VarListEntry>
231 <Term>``Static'' (in C land):</Term>
232 <ListItem>
233 <Para>
234 A C routine may pass an <Literal>Addr&num;</Literal> pointer back into Haskell land.  There
235 are then primitive operations with which you may merrily grab values
236 over in C land, by indexing off the ``static'' pointer.
237 </Para>
238 </ListItem>
239 </VarListEntry>
240 <VarListEntry>
241 <Term>``Stable'' pointers:</Term>
242 <ListItem>
243 <Para>
244 If, for some reason, you wish to hand a Haskell pointer (i.e.,
245 <Emphasis>not</Emphasis> an unboxed value) to a C routine, you first make the
246 pointer ``stable,'' so that the garbage collector won't forget that it
247 exists.  That is, GHC provides a safe way to pass Haskell pointers to
248 C.
249 </Para>
250
251 <Para>
252 Please see <XRef LinkEnd="glasgow-stablePtrs"> for more details.
253 </Para>
254 </ListItem>
255 </VarListEntry>
256 <VarListEntry>
257 <Term>``Foreign objects'':</Term>
258 <ListItem>
259 <Para>
260 A ``foreign object'' is a safe way to pass an external object (a
261 C-allocated pointer, say) to Haskell and have Haskell do the Right
262 Thing when it no longer references the object.  So, for example, C
263 could pass a large bitmap over to Haskell and say ``please free this
264 memory when you're done with it.''
265 </Para>
266
267 <Para>
268 Please see <XRef LinkEnd="glasgow-foreignObjs"> for more details.
269 </Para>
270 </ListItem>
271 </VarListEntry>
272 </VariableList>
273 </Para>
274
275 <Para>
276 The libraries section gives more details on all these ``primitive
277 array'' types and the operations on them, <XRef LinkEnd="ghc-prelude">.  Some of these extensions
278 are also supported by Hugs, and the supporting libraries are described
279 in the <ULink
280 URL="libs.html"
281 >GHC/Hugs Extension Libraries</ULink
282 >
283 document.
284 </Para>
285
286 </Sect1>
287
288 <Sect1 id="glasgow-ccalls">
289 <Title>Calling&nbsp;C directly from Haskell
290 </Title>
291
292 <Para>
293 <IndexTerm><Primary>C calls (Glasgow extension)</Primary></IndexTerm>
294 <IndexTerm><Primary>&lowbar;ccall&lowbar; (Glasgow extension)</Primary></IndexTerm>
295 <IndexTerm><Primary>&lowbar;casm&lowbar; (Glasgow extension)</Primary></IndexTerm>
296 </Para>
297
298 <Para>
299 GOOD ADVICE: Because this stuff is not Entirely Stable as far as names
300 and things go, you would be well-advised to keep your C-callery
301 corraled in a few modules, rather than sprinkled all over your code.
302 It will then be quite easy to update later on.
303 </Para>
304
305 <Sect2 id="ccall-intro">
306 <Title><Literal>&lowbar;ccall&lowbar;</Literal> and <Literal>&lowbar;casm&lowbar;</Literal>: an introduction
307 </Title>
308
309 <Para>
310 The simplest way to use a simple C function
311 </Para>
312
313 <Para>
314
315 <ProgramListing>
316 double fooC( FILE *in, char c, int i, double d, unsigned int u )
317 </ProgramListing>
318
319 </Para>
320
321 <Para>
322 is to provide a Haskell wrapper:
323 </Para>
324
325 <Para>
326
327 <ProgramListing>
328 fooH :: Char -&#62; Int -&#62; Double -&#62; Word -&#62; IO Double
329 fooH c i d w = _ccall_ fooC (``stdin''::Addr) c i d w
330 </ProgramListing>
331
332 </Para>
333
334 <Para>
335 The function <Literal>fooH</Literal> will unbox all of its arguments, call the C
336 function <Literal>fooC</Literal> and box the corresponding arguments.
337 </Para>
338
339 <Para>
340 One of the annoyances about <Literal>&lowbar;ccall&lowbar;</Literal>s is when the C types don't quite
341 match the Haskell compiler's ideas.  For this, the <Literal>&lowbar;casm&lowbar;</Literal> variant
342 may be just the ticket (NB: <Emphasis>no chance</Emphasis> of such code going
343 through a native-code generator):
344 </Para>
345
346 <Para>
347
348 <ProgramListing>
349 import Addr
350 import CString
351
352 oldGetEnv name
353   = _casm_ ``%r = getenv((char *) %0);'' name &#62;&#62;= \ litstring -&#62;
354     return (
355         if (litstring == nullAddr) then
356             Left ("Fail:oldGetEnv:"++name)
357         else
358             Right (unpackCString litstring)
359     )
360 </ProgramListing>
361
362 </Para>
363
364 <Para>
365 The first literal-literal argument to a <Literal>&lowbar;casm&lowbar;</Literal> is like a <Literal>printf</Literal>
366 format: <Literal>&percnt;r</Literal> is replaced with the ``result,'' <Literal>&percnt;0</Literal>--<Literal>&percnt;n-1</Literal> are
367 replaced with the 1st--nth arguments.  As you can see above, it is an
368 easy way to do simple C&nbsp;casting.  Everything said about <Literal>&lowbar;ccall&lowbar;</Literal> goes
369 for <Literal>&lowbar;casm&lowbar;</Literal> as well.
370 </Para>
371
372 <Para>
373 The use of <Literal>&lowbar;casm&lowbar;</Literal> in your code does pose a problem to the compiler
374 when it comes to generating an interface file for a freshly compiled
375 module. Included in an interface file is the unfolding (if any) of a
376 declaration. However, if a declaration's unfolding happens to contain
377 a <Literal>&lowbar;casm&lowbar;</Literal>, its unfolding will <Emphasis>not</Emphasis> be emitted into the interface
378 file even if it qualifies by all the other criteria. The reason why
379 the compiler prevents this from happening is that unfolding <Literal>&lowbar;casm&lowbar;</Literal>s
380 into an interface file unduly constrains how code that import your
381 module have to be compiled. If an imported declaration is unfolded and
382 it contains a <Literal>&lowbar;casm&lowbar;</Literal>, you now have to be using a compiler backend
383 capable of dealing with it (i.e., the C compiler backend). If you are
384 using the C compiler backend, the unfolded <Literal>&lowbar;casm&lowbar;</Literal> may still cause you
385 problems since the C code snippet it contains may mention CPP symbols
386 that were in scope when compiling the original module are not when
387 compiling the importing module.
388 </Para>
389
390 <Para>
391 If you're willing to put up with the drawbacks of doing cross-module
392 inlining of C code (GHC - A Better C Compiler :-), the option
393 <Literal>-funfold-casms-in-hi-file</Literal> will turn off the default behaviour.
394 <IndexTerm><Primary>-funfold-casms-in-hi-file option</Primary></IndexTerm>
395 </Para>
396
397 </Sect2>
398
399 <Sect2 id="glasgow-literal-literals">
400 <Title>Literal-literals
401 </Title>
402
403 <Para>
404 <IndexTerm><Primary>Literal-literals</Primary></IndexTerm>
405 </Para>
406
407 <Para>
408 The literal-literal argument to <Literal>&lowbar;casm&lowbar;</Literal> can be made use of separately
409 from the <Literal>&lowbar;casm&lowbar;</Literal> construct itself. Indeed, we've already used it:
410 </Para>
411
412 <Para>
413
414 <ProgramListing>
415 fooH :: Char -&#62; Int -&#62; Double -&#62; Word -&#62; IO Double
416 fooH c i d w = _ccall_ fooC (``stdin''::Addr) c i d w
417 </ProgramListing>
418
419 </Para>
420
421 <Para>
422 The first argument that's passed to <Literal>fooC</Literal> is given as a literal-literal,
423 that is, a literal chunk of C code that will be inserted into the generated
424 <Literal>.hc</Literal> code at the right place.
425 </Para>
426
427 <Para>
428 A literal-literal is restricted to having a type that's an instance of
429 the <Literal>CCallable</Literal> class, see <XRef LinkEnd="ccall-gotchas">
430 for more information.
431 </Para>
432
433 <Para>
434 Notice that literal-literals are by their very nature unfriendly to
435 native code generators, so exercise judgement about whether or not to
436 make use of them in your code.
437 </Para>
438
439 </Sect2>
440
441 <Sect2 id="glasgow-foreign-headers">
442 <Title>Using function headers
443 </Title>
444
445 <Para>
446 <IndexTerm><Primary>C calls, function headers</Primary></IndexTerm>
447 </Para>
448
449 <Para>
450 When generating C (using the <Literal>-fvia-C</Literal> directive), one can assist the
451 C compiler in detecting type errors by using the <Literal>-&num;include</Literal> directive
452 to provide <Literal>.h</Literal> files containing function headers.
453 </Para>
454
455 <Para>
456 For example,
457 </Para>
458
459 <Para>
460
461 <ProgramListing>
462 typedef unsigned long *StgForeignObj;
463 typedef long StgInt;
464
465 void          initialiseEFS (StgInt size);
466 StgInt        terminateEFS (void);
467 StgForeignObj emptyEFS(void);
468 StgForeignObj updateEFS (StgForeignObj a, StgInt i, StgInt x);
469 StgInt        lookupEFS (StgForeignObj a, StgInt i);
470 </ProgramListing>
471
472 </Para>
473
474 <Para>
475 You can find appropriate definitions for <Literal>StgInt</Literal>, <Literal>StgForeignObj</Literal>,
476 etc using <Literal>gcc</Literal> on your architecture by consulting
477 <Literal>ghc/includes/StgTypes.h</Literal>.  The following table summarises the
478 relationship between Haskell types and C types.
479 </Para>
480
481 <Para>
482
483 <InformalTable>
484 <TGroup Cols="2">
485 <ColSpec Align="Left" Colsep="0">
486 <ColSpec Align="Left" Colsep="0">
487 <TBody>
488 <Row>
489 <Entry><Emphasis>C type name</Emphasis> </Entry>
490 <Entry> <Emphasis>Haskell Type</Emphasis> </Entry>
491 </Row>
492
493 <Row>
494 <Entry>
495 <Literal>StgChar</Literal> </Entry>
496 <Entry> <Literal>Char&num;</Literal> </Entry>
497 </Row>
498 <Row>
499 <Entry>
500 <Literal>StgInt</Literal> </Entry>
501 <Entry> <Literal>Int&num;</Literal> </Entry>
502 </Row>
503 <Row>
504 <Entry>
505 <Literal>StgWord</Literal> </Entry>
506 <Entry> <Literal>Word&num;</Literal> </Entry>
507 </Row>
508 <Row>
509 <Entry>
510 <Literal>StgAddr</Literal> </Entry>
511 <Entry> <Literal>Addr&num;</Literal> </Entry>
512 </Row>
513 <Row>
514 <Entry>
515 <Literal>StgFloat</Literal> </Entry>
516 <Entry> <Literal>Float&num;</Literal> </Entry>
517 </Row>
518 <Row>
519 <Entry>
520 <Literal>StgDouble</Literal> </Entry>
521 <Entry> <Literal>Double&num;</Literal> </Entry>
522 </Row>
523 <Row>
524 <Entry>
525 <Literal>StgArray</Literal> </Entry>
526 <Entry> <Literal>Array&num;</Literal> </Entry>
527 </Row>
528 <Row>
529 <Entry>
530 <Literal>StgByteArray</Literal> </Entry>
531 <Entry> <Literal>ByteArray&num;</Literal> </Entry>
532 </Row>
533 <Row>
534 <Entry>
535 <Literal>StgArray</Literal> </Entry>
536 <Entry> <Literal>MutableArray&num;</Literal> </Entry>
537 </Row>
538 <Row>
539 <Entry>
540 <Literal>StgByteArray</Literal> </Entry>
541 <Entry> <Literal>MutableByteArray&num;</Literal> </Entry>
542 </Row>
543 <Row>
544 <Entry>
545 <Literal>StgStablePtr</Literal> </Entry>
546 <Entry> <Literal>StablePtr&num;</Literal> </Entry>
547 </Row>
548 <Row>
549 <Entry>
550 <Literal>StgForeignObj</Literal> </Entry>
551 <Entry> <Literal>ForeignObj&num;</Literal></Entry>
552 </Row>
553 </TBody>
554
555 </TGroup>
556 </InformalTable>
557 </Para>
558
559 <Para>
560 Note that this approach is only <Emphasis>essential</Emphasis> for returning
561 <Literal>float</Literal>s (or if <Literal>sizeof(int) != sizeof(int *)</Literal> on your
562 architecture) but is a Good Thing for anyone who cares about writing
563 solid code.  You're crazy not to do it.
564 </Para>
565
566 </Sect2>
567
568 <Sect2 id="glasgow-stablePtrs">
569 <Title>Subverting automatic unboxing with ``stable pointers''
570 </Title>
571
572 <Para>
573 <IndexTerm><Primary>stable pointers (Glasgow extension)</Primary></IndexTerm>
574 </Para>
575
576 <Para>
577 The arguments of a <Literal>&lowbar;ccall&lowbar;</Literal> are automatically unboxed before the
578 call.  There are two reasons why this is usually the Right Thing to
579 do:
580 </Para>
581
582 <Para>
583
584 <ItemizedList>
585 <ListItem>
586
587 <Para>
588 C is a strict language: it would be excessively tedious to pass
589 unevaluated arguments and require the C programmer to force their
590 evaluation before using them.
591
592 </Para>
593 </ListItem>
594 <ListItem>
595
596 <Para>
597  Boxed values are stored on the Haskell heap and may be moved
598 within the heap if a garbage collection occurs&mdash;that is, pointers
599 to boxed objects are not <Emphasis>stable</Emphasis>.
600 </Para>
601 </ListItem>
602
603 </ItemizedList>
604
605 </Para>
606
607 <Para>
608 It is possible to subvert the unboxing process by creating a ``stable
609 pointer'' to a value and passing the stable pointer instead.  For
610 example, to pass/return an integer lazily to C functions <Literal>storeC</Literal> and
611 <Literal>fetchC</Literal>, one might write:
612 </Para>
613
614 <Para>
615
616 <ProgramListing>
617 storeH :: Int -&#62; IO ()
618 storeH x = makeStablePtr x              &#62;&#62;= \ stable_x -&#62;
619            _ccall_ storeC stable_x
620
621 fetchH :: IO Int
622 fetchH x = _ccall_ fetchC               &#62;&#62;= \ stable_x -&#62;
623            deRefStablePtr stable_x      &#62;&#62;= \ x -&#62;
624            freeStablePtr stable_x       &#62;&#62;
625            return x
626 </ProgramListing>
627
628 </Para>
629
630 <Para>
631 The garbage collector will refrain from throwing a stable pointer away
632 until you explicitly call one of the following from C or Haskell.
633 </Para>
634
635 <Para>
636
637 <ProgramListing>
638 void freeStablePointer( StgStablePtr stablePtrToToss )
639 freeStablePtr :: StablePtr a -&#62; IO ()
640 </ProgramListing>
641
642 </Para>
643
644 <Para>
645 As with the use of <Literal>free</Literal> in C programs, GREAT CARE SHOULD BE
646 EXERCISED to ensure these functions are called at the right time: too
647 early and you get dangling references (and, if you're lucky, an error
648 message from the runtime system); too late and you get space leaks.
649 </Para>
650
651 <Para>
652 And to force evaluation of the argument within <Literal>fooC</Literal>, one would
653 call one of the following C functions (according to type of argument).
654 </Para>
655
656 <Para>
657
658 <ProgramListing>
659 void     performIO  ( StgStablePtr stableIndex /* StablePtr s (IO ()) */ );
660 StgInt   enterInt   ( StgStablePtr stableIndex /* StablePtr s Int */ );
661 StgFloat enterFloat ( StgStablePtr stableIndex /* StablePtr s Float */ );
662 </ProgramListing>
663
664 </Para>
665
666 <Para>
667 <IndexTerm><Primary>performIO</Primary></IndexTerm>
668 <IndexTerm><Primary>enterInt</Primary></IndexTerm>
669 <IndexTerm><Primary>enterFloat</Primary></IndexTerm>
670 </Para>
671
672 <Para>
673 Nota Bene: <Literal>&lowbar;ccall&lowbar;GC&lowbar;</Literal><IndexTerm><Primary>&lowbar;ccall&lowbar;GC&lowbar;</Primary></IndexTerm> must be used if any of
674 these functions are used.
675 </Para>
676
677 </Sect2>
678
679 <Sect2 id="glasgow-foreignObjs">
680 <Title>Foreign objects: pointing outside the Haskell heap
681 </Title>
682
683 <Para>
684 <IndexTerm><Primary>foreign objects (Glasgow extension)</Primary></IndexTerm>
685 </Para>
686
687 <Para>
688 There are two types that <Literal>ghc</Literal> programs can use to reference
689 (heap-allocated) objects outside the Haskell world: <Literal>Addr</Literal> and
690 <Literal>ForeignObj</Literal>.
691 </Para>
692
693 <Para>
694 If you use <Literal>Addr</Literal>, it is up to you to the programmer to arrange
695 allocation and deallocation of the objects.
696 </Para>
697
698 <Para>
699 If you use <Literal>ForeignObj</Literal>, <Literal>ghc</Literal>'s garbage collector will call upon the
700 user-supplied <Emphasis>finaliser</Emphasis> function to free the object when the
701 Haskell world no longer can access the object.  (An object is
702 associated with a finaliser function when the abstract
703 Haskell type <Literal>ForeignObj</Literal> is created). The finaliser function is
704 expressed in C, and is passed as argument the object:
705 </Para>
706
707 <Para>
708
709 <ProgramListing>
710 void foreignFinaliser ( StgForeignObj fo )
711 </ProgramListing>
712
713 </Para>
714
715 <Para>
716 when the Haskell world can no longer access the object.  Since
717 <Literal>ForeignObj</Literal>s only get released when a garbage collection occurs, we
718 provide ways of triggering a garbage collection from within C and from
719 within Haskell.
720 </Para>
721
722 <Para>
723
724 <ProgramListing>
725 void GarbageCollect()
726 performGC :: IO ()
727 </ProgramListing>
728
729 </Para>
730
731 <Para>
732 More information on the programmers' interface to <Literal>ForeignObj</Literal> can be
733 found in the library documentation.
734 </Para>
735
736 </Sect2>
737
738 <Sect2 id="glasgow-avoiding-monads">
739 <Title>Avoiding monads
740 </Title>
741
742 <Para>
743 <IndexTerm><Primary>C calls to `pure C'</Primary></IndexTerm>
744 <IndexTerm><Primary>unsafePerformIO</Primary></IndexTerm>
745 </Para>
746
747 <Para>
748 The <Literal>&lowbar;ccall&lowbar;</Literal> construct is part of the <Literal>IO</Literal> monad because 9 out of 10
749 uses will be to call imperative functions with side effects such as
750 <Literal>printf</Literal>.  Use of the monad ensures that these operations happen in a
751 predictable order in spite of laziness and compiler optimisations.
752 </Para>
753
754 <Para>
755 To avoid having to be in the monad to call a C function, it is
756 possible to use <Literal>unsafePerformIO</Literal>, which is available from the
757 <Literal>IOExts</Literal> module.  There are three situations where one might like to
758 call a C function from outside the IO world:
759 </Para>
760
761 <Para>
762
763 <ItemizedList>
764 <ListItem>
765
766 <Para>
767 Calling a function with no side-effects:
768
769 <ProgramListing>
770 atan2d :: Double -&#62; Double -&#62; Double
771 atan2d y x = unsafePerformIO (_ccall_ atan2d y x)
772
773 sincosd :: Double -&#62; (Double, Double)
774 sincosd x = unsafePerformIO $ do
775         da &#60;- newDoubleArray (0, 1)
776         _casm_ ``sincosd( %0, &amp;((double *)%1[0]), &amp;((double *)%1[1]) );'' x da
777         s &#60;- readDoubleArray da 0
778         c &#60;- readDoubleArray da 1
779         return (s, c)
780 </ProgramListing>
781
782
783 </Para>
784 </ListItem>
785 <ListItem>
786
787 <Para>
788  Calling a set of functions which have side-effects but which can
789 be used in a purely functional manner.
790
791 For example, an imperative implementation of a purely functional
792 lookup-table might be accessed using the following functions.
793
794
795 <ProgramListing>
796 empty  :: EFS x
797 update :: EFS x -&#62; Int -&#62; x -&#62; EFS x
798 lookup :: EFS a -&#62; Int -&#62; a
799
800 empty = unsafePerformIO (_ccall_ emptyEFS)
801
802 update a i x = unsafePerformIO $
803         makeStablePtr x         &#62;&#62;= \ stable_x -&#62;
804         _ccall_ updateEFS a i stable_x
805
806 lookup a i = unsafePerformIO $
807         _ccall_ lookupEFS a i   &#62;&#62;= \ stable_x -&#62;
808         deRefStablePtr stable_x
809 </ProgramListing>
810
811
812 You will almost always want to use <Literal>ForeignObj</Literal>s with this.
813
814 </Para>
815 </ListItem>
816 <ListItem>
817
818 <Para>
819  Calling a side-effecting function even though the results will
820 be unpredictable.  For example the <Literal>trace</Literal> function is defined by:
821
822
823 <ProgramListing>
824 trace :: String -&#62; a -&#62; a
825 trace string expr
826   = unsafePerformIO (
827         ((_ccall_ PreTraceHook sTDERR{-msg-}):: IO ())  &#62;&#62;
828         fputs sTDERR string                             &#62;&#62;
829         ((_ccall_ PostTraceHook sTDERR{-msg-}):: IO ()) &#62;&#62;
830         return expr )
831   where
832     sTDERR = (``stderr'' :: Addr)
833 </ProgramListing>
834
835
836 (This kind of use is not highly recommended&mdash;it is only really
837 useful in debugging code.)
838 </Para>
839 </ListItem>
840
841 </ItemizedList>
842
843 </Para>
844
845 </Sect2>
846
847 <Sect2 id="ccall-gotchas">
848 <Title>C-calling ``gotchas'' checklist
849 </Title>
850
851 <Para>
852 <IndexTerm><Primary>C call dangers</Primary></IndexTerm>
853 <IndexTerm><Primary>CCallable</Primary></IndexTerm>
854 <IndexTerm><Primary>CReturnable</Primary></IndexTerm>
855 </Para>
856
857 <Para>
858 And some advice, too.
859 </Para>
860
861 <Para>
862
863 <ItemizedList>
864 <ListItem>
865
866 <Para>
867  For modules that use <Literal>&lowbar;ccall&lowbar;</Literal>s, etc., compile with
868 <Literal>-fvia-C</Literal>.<IndexTerm><Primary>-fvia-C option</Primary></IndexTerm> You don't have to, but you should.
869
870 Also, use the <Literal>-&num;include "prototypes.h"</Literal> flag (hack) to inform the C
871 compiler of the fully-prototyped types of all the C functions you
872 call.  (<XRef LinkEnd="glasgow-foreign-headers"> says more about this&hellip;)
873
874 This scheme is the <Emphasis>only</Emphasis> way that you will get <Emphasis>any</Emphasis>
875 typechecking of your <Literal>&lowbar;ccall&lowbar;</Literal>s.  (It shouldn't be that way, but&hellip;).
876 GHC will pass the flag <Literal>-Wimplicit</Literal> to gcc so that you'll get warnings
877 if any <Literal>&lowbar;ccall&lowbar;</Literal>ed functions have no prototypes.
878
879 </Para>
880 </ListItem>
881 <ListItem>
882
883 <Para>
884 Try to avoid <Literal>&lowbar;ccall&lowbar;</Literal>s to C&nbsp;functions that take <Literal>float</Literal>
885 arguments or return <Literal>float</Literal> results.  Reason: if you do, you will
886 become entangled in (ANSI?) C's rules for when arguments/results are
887 promoted to <Literal>doubles</Literal>.  It's a nightmare and just not worth it.
888 Use <Literal>doubles</Literal> if possible.
889
890 If you do use <Literal>floats</Literal>, check and re-check that the right thing is
891 happening.  Perhaps compile with <Literal>-keep-hc-file-too</Literal> and look at
892 the intermediate C (<Literal>.hc</Literal> file).
893
894 </Para>
895 </ListItem>
896 <ListItem>
897
898 <Para>
899  The compiler uses two non-standard type-classes when
900 type-checking the arguments and results of <Literal>&lowbar;ccall&lowbar;</Literal>: the arguments
901 (respectively result) of <Literal>&lowbar;ccall&lowbar;</Literal> must be instances of the class
902 <Literal>CCallable</Literal> (respectively <Literal>CReturnable</Literal>).  Both classes may be
903 imported from the module <Literal>CCall</Literal>, but this should only be
904 necessary if you want to define a new instance.  (Neither class
905 defines any methods&mdash;their only function is to keep the
906 type-checker happy.)
907
908 The type checker must be able to figure out just which of the
909 C-callable/returnable types is being used.  If it can't, you have to
910 add type signatures. For example,
911
912
913 <ProgramListing>
914 f x = _ccall_ foo x
915 </ProgramListing>
916
917
918 is not good enough, because the compiler can't work out what type <Literal>x</Literal>
919 is, nor what type the <Literal>&lowbar;ccall&lowbar;</Literal> returns.  You have to write, say:
920
921
922 <ProgramListing>
923 f :: Int -&#62; IO Double
924 f x = _ccall_ foo x
925 </ProgramListing>
926
927
928 This table summarises the standard instances of these classes.
929
930 <InformalTable>
931 <TGroup Cols="4">
932 <ColSpec Align="Left" Colsep="0">
933 <ColSpec Align="Left" Colsep="0">
934 <ColSpec Align="Left" Colsep="0">
935 <ColSpec Align="Left" Colsep="0">
936 <TBody>
937 <Row>
938 <Entry><Emphasis>Type</Emphasis> </Entry>
939 <Entry><Emphasis>CCallable</Emphasis></Entry>
940 <Entry><Emphasis>CReturnable</Emphasis> </Entry>
941 <Entry><Emphasis>Which is probably&hellip;</Emphasis> </Entry>
942 </Row>
943 <Row>
944 <Entry>
945 <Literal>Char</Literal> </Entry>
946 <Entry> Yes </Entry>
947 <Entry> Yes </Entry>
948 <Entry> <Literal>unsigned char</Literal> </Entry>
949 </Row>
950 <Row>
951 <Entry>
952 <Literal>Int</Literal> </Entry>
953 <Entry> Yes </Entry>
954 <Entry> Yes </Entry>
955 <Entry> <Literal>long int</Literal> </Entry>
956 </Row>
957 <Row>
958 <Entry>
959 <Literal>Word</Literal> </Entry>
960 <Entry> Yes </Entry>
961 <Entry> Yes </Entry>
962 <Entry> <Literal>unsigned long int</Literal> </Entry>
963 </Row>
964 <Row>
965 <Entry>
966 <Literal>Addr</Literal> </Entry>
967 <Entry> Yes </Entry>
968 <Entry> Yes </Entry>
969 <Entry> <Literal>void *</Literal> </Entry>
970 </Row>
971 <Row>
972 <Entry>
973 <Literal>Float</Literal> </Entry>
974 <Entry> Yes </Entry>
975 <Entry> Yes </Entry>
976 <Entry> <Literal>float</Literal> </Entry>
977 </Row>
978 <Row>
979 <Entry>
980 <Literal>Double</Literal> </Entry>
981 <Entry> Yes </Entry>
982 <Entry> Yes </Entry>
983 <Entry> <Literal>double</Literal> </Entry>
984 </Row>
985 <Row>
986 <Entry>
987 <Literal>()</Literal> </Entry>
988 <Entry> No </Entry>
989 <Entry> Yes </Entry>
990 <Entry> <Literal>void</Literal> </Entry>
991 </Row>
992 <Row>
993 <Entry>
994 <Literal>[Char]</Literal> </Entry>
995 <Entry> Yes </Entry>
996 <Entry> No </Entry>
997 <Entry> <Literal>char *</Literal> (null-terminated) </Entry>
998 </Row>
999 <Row>
1000 <Entry>
1001 <Literal>Array</Literal> </Entry>
1002 <Entry> Yes </Entry>
1003 <Entry> No </Entry>
1004 <Entry> <Literal>unsigned long *</Literal> </Entry>
1005 </Row>
1006 <Row>
1007 <Entry>
1008 <Literal>ByteArray</Literal> </Entry>
1009 <Entry> Yes </Entry>
1010 <Entry> No </Entry>
1011 <Entry> <Literal>unsigned long *</Literal> </Entry>
1012 </Row>
1013 <Row>
1014 <Entry>
1015 <Literal>MutableArray</Literal> </Entry>
1016 <Entry> Yes </Entry>
1017 <Entry> No </Entry>
1018 <Entry> <Literal>unsigned long *</Literal> </Entry>
1019 </Row>
1020 <Row>
1021 <Entry>
1022 <Literal>MutableByteArray</Literal> </Entry>
1023 <Entry> Yes </Entry>
1024 <Entry> No </Entry>
1025 <Entry> <Literal>unsigned long *</Literal> </Entry>
1026 </Row>
1027 <Row>
1028 <Entry>
1029 <Literal>State</Literal> </Entry>
1030 <Entry> Yes </Entry>
1031 <Entry> Yes </Entry>
1032 <Entry> nothing!</Entry>
1033 </Row>
1034 <Row>
1035 <Entry>
1036 <Literal>StablePtr</Literal> </Entry>
1037 <Entry> Yes </Entry>
1038 <Entry> Yes </Entry>
1039 <Entry> <Literal>unsigned long *</Literal> </Entry>
1040 </Row>
1041 <Row>
1042 <Entry>
1043 <Literal>ForeignObjs</Literal> </Entry>
1044 <Entry> Yes </Entry>
1045 <Entry> Yes </Entry>
1046 <Entry> see later </Entry>
1047 </Row>
1048
1049 </TBody>
1050
1051 </TGroup>
1052 </InformalTable>
1053
1054 Actually, the <Literal>Word</Literal> type is defined as being the same size as a
1055 pointer on the target architecture, which is <Emphasis>probably</Emphasis>
1056 <Literal>unsigned long int</Literal>.
1057
1058 The brave and careful programmer can add their own instances of these
1059 classes for the following types:
1060
1061
1062 <ItemizedList>
1063 <ListItem>
1064
1065 <Para>
1066 A <Emphasis>boxed-primitive</Emphasis> type may be made an instance of both
1067 <Literal>CCallable</Literal> and <Literal>CReturnable</Literal>.
1068
1069 A boxed primitive type is any data type with a
1070 single unary constructor with a single primitive argument.  For
1071 example, the following are all boxed primitive types:
1072
1073
1074 <ProgramListing>
1075 Int
1076 Double
1077 data XDisplay = XDisplay Addr#
1078 data EFS a = EFS# ForeignObj#
1079 </ProgramListing>
1080
1081
1082
1083 <ProgramListing>
1084 instance CCallable   (EFS a)
1085 instance CReturnable (EFS a)
1086 </ProgramListing>
1087
1088
1089 </Para>
1090 </ListItem>
1091 <ListItem>
1092
1093 <Para>
1094  Any datatype with a single nullary constructor may be made an
1095 instance of <Literal>CReturnable</Literal>.  For example:
1096
1097
1098 <ProgramListing>
1099 data MyVoid = MyVoid
1100 instance CReturnable MyVoid
1101 </ProgramListing>
1102
1103
1104 </Para>
1105 </ListItem>
1106 <ListItem>
1107
1108 <Para>
1109  As at version 2.09, <Literal>String</Literal> (i.e., <Literal>[Char]</Literal>) is still
1110 not a <Literal>CReturnable</Literal> type.
1111
1112 Also, the now-builtin type <Literal>PackedString</Literal> is neither
1113 <Literal>CCallable</Literal> nor <Literal>CReturnable</Literal>.  (But there are functions in
1114 the PackedString interface to let you get at the necessary bits&hellip;)
1115 </Para>
1116 </ListItem>
1117
1118 </ItemizedList>
1119
1120
1121 </Para>
1122 </ListItem>
1123 <ListItem>
1124
1125 <Para>
1126  The code-generator will complain if you attempt to use <Literal>&percnt;r</Literal> in
1127 a <Literal>&lowbar;casm&lowbar;</Literal> whose result type is <Literal>IO ()</Literal>; or if you don't use <Literal>&percnt;r</Literal>
1128 <Emphasis>precisely</Emphasis> once for any other result type.  These messages are
1129 supposed to be helpful and catch bugs&mdash;please tell us if they wreck
1130 your life.
1131
1132 </Para>
1133 </ListItem>
1134 <ListItem>
1135
1136 <Para>
1137  If you call out to C code which may trigger the Haskell garbage
1138 collector or create new threads (examples of this later&hellip;), then you
1139 must use the <Literal>&lowbar;ccall&lowbar;GC&lowbar;</Literal><IndexTerm><Primary>&lowbar;ccall&lowbar;GC&lowbar; primitive</Primary></IndexTerm> or
1140 <Literal>&lowbar;casm&lowbar;GC&lowbar;</Literal><IndexTerm><Primary>&lowbar;casm&lowbar;GC&lowbar; primitive</Primary></IndexTerm> variant of C-calls.  (This
1141 does not work with the native code generator - use <Literal>\fvia-C</Literal>.) This
1142 stuff is hairy with a capital H!
1143 </Para>
1144 </ListItem>
1145
1146 </ItemizedList>
1147
1148 </Para>
1149
1150 </Sect2>
1151
1152 </Sect1>
1153
1154 <Sect1 id="multi-param-type-classes">
1155 <Title>Multi-parameter type classes
1156 </Title>
1157
1158 <Para>
1159 This section documents GHC's implementation of multi-paramter type
1160 classes.  There's lots of background in the paper <ULink
1161 URL="http://www.dcs.gla.ac.uk/~simonpj/multi.ps.gz"
1162 >Type classes: exploring the design space</ULink
1163 > (Simon Peyton
1164 Jones, Mark Jones, Erik Meijer).
1165 </Para>
1166
1167 <Para>
1168 I'd like to thank people who reported shorcomings in the GHC 3.02
1169 implementation.  Our default decisions were all conservative ones, and
1170 the experience of these heroic pioneers has given useful concrete
1171 examples to support several generalisations.  (These appear below as
1172 design choices not implemented in 3.02.)
1173 </Para>
1174
1175 <Para>
1176 I've discussed these notes with Mark Jones, and I believe that Hugs
1177 will migrate towards the same design choices as I outline here.
1178 Thanks to him, and to many others who have offered very useful
1179 feedback.
1180 </Para>
1181
1182 <Sect2>
1183 <Title>Types</Title>
1184
1185 <Para>
1186 There are the following restrictions on the form of a qualified
1187 type:
1188 </Para>
1189
1190 <Para>
1191
1192 <ProgramListing>
1193   forall tv1..tvn (c1, ...,cn) =&#62; type
1194 </ProgramListing>
1195
1196 </Para>
1197
1198 <Para>
1199 (Here, I write the "foralls" explicitly, although the Haskell source
1200 language omits them; in Haskell 1.4, all the free type variables of an
1201 explicit source-language type signature are universally quantified,
1202 except for the class type variables in a class declaration.  However,
1203 in GHC, you can give the foralls if you want.  See <XRef LinkEnd="universal-quantification">).
1204 </Para>
1205
1206 <Para>
1207
1208 <OrderedList>
1209 <ListItem>
1210
1211 <Para>
1212  <Emphasis>Each universally quantified type variable
1213 <Literal>tvi</Literal> must be mentioned (i.e. appear free) in <Literal>type</Literal></Emphasis>.
1214
1215 The reason for this is that a value with a type that does not obey
1216 this restriction could not be used without introducing
1217 ambiguity. Here, for example, is an illegal type:
1218
1219
1220 <ProgramListing>
1221   forall a. Eq a =&#62; Int
1222 </ProgramListing>
1223
1224
1225 When a value with this type was used, the constraint <Literal>Eq tv</Literal>
1226 would be introduced where <Literal>tv</Literal> is a fresh type variable, and
1227 (in the dictionary-translation implementation) the value would be
1228 applied to a dictionary for <Literal>Eq tv</Literal>.  The difficulty is that we
1229 can never know which instance of <Literal>Eq</Literal> to use because we never
1230 get any more information about <Literal>tv</Literal>.
1231
1232 </Para>
1233 </ListItem>
1234 <ListItem>
1235
1236 <Para>
1237  <Emphasis>Every constraint <Literal>ci</Literal> must mention at least one of the
1238 universally quantified type variables <Literal>tvi</Literal></Emphasis>.
1239
1240 For example, this type is OK because <Literal>C a b</Literal> mentions the
1241 universally quantified type variable <Literal>b</Literal>:
1242
1243
1244 <ProgramListing>
1245   forall a. C a b =&#62; burble
1246 </ProgramListing>
1247
1248
1249 The next type is illegal because the constraint <Literal>Eq b</Literal> does not
1250 mention <Literal>a</Literal>:
1251
1252
1253 <ProgramListing>
1254   forall a. Eq b =&#62; burble
1255 </ProgramListing>
1256
1257
1258 The reason for this restriction is milder than the other one.  The
1259 excluded types are never useful or necessary (because the offending
1260 context doesn't need to be witnessed at this point; it can be floated
1261 out).  Furthermore, floating them out increases sharing. Lastly,
1262 excluding them is a conservative choice; it leaves a patch of
1263 territory free in case we need it later.
1264
1265 </Para>
1266 </ListItem>
1267
1268 </OrderedList>
1269
1270 </Para>
1271
1272 <Para>
1273 These restrictions apply to all types, whether declared in a type signature
1274 or inferred.
1275 </Para>
1276
1277 <Para>
1278 Unlike Haskell 1.4, constraints in types do <Emphasis>not</Emphasis> have to be of
1279 the form <Emphasis>(class type-variables)</Emphasis>.  Thus, these type signatures
1280 are perfectly OK
1281 </Para>
1282
1283 <Para>
1284
1285 <ProgramListing>
1286   f :: Eq (m a) =&#62; [m a] -&#62; [m a]
1287   g :: Eq [a] =&#62; ...
1288 </ProgramListing>
1289
1290 </Para>
1291
1292 <Para>
1293 This choice recovers principal types, a property that Haskell 1.4 does not have.
1294 </Para>
1295
1296 </Sect2>
1297
1298 <Sect2>
1299 <Title>Class declarations</Title>
1300
1301 <Para>
1302
1303 <OrderedList>
1304 <ListItem>
1305
1306 <Para>
1307  <Emphasis>Multi-parameter type classes are permitted</Emphasis>. For example:
1308
1309
1310 <ProgramListing>
1311   class Collection c a where
1312     union :: c a -&#62; c a -&#62; c a
1313     ...etc.
1314 </ProgramListing>
1315
1316
1317
1318 </Para>
1319 </ListItem>
1320 <ListItem>
1321
1322 <Para>
1323  <Emphasis>The class hierarchy must be acyclic</Emphasis>.  However, the definition
1324 of "acyclic" involves only the superclass relationships.  For example,
1325 this is OK:
1326
1327
1328 <ProgramListing>
1329   class C a where {
1330     op :: D b =&#62; a -&#62; b -&#62; b
1331   }
1332
1333   class C a =&#62; D a where { ... }
1334 </ProgramListing>
1335
1336
1337 Here, <Literal>C</Literal> is a superclass of <Literal>D</Literal>, but it's OK for a
1338 class operation <Literal>op</Literal> of <Literal>C</Literal> to mention <Literal>D</Literal>.  (It
1339 would not be OK for <Literal>D</Literal> to be a superclass of <Literal>C</Literal>.)
1340
1341 </Para>
1342 </ListItem>
1343 <ListItem>
1344
1345 <Para>
1346  <Emphasis>There are no restrictions on the context in a class declaration
1347 (which introduces superclasses), except that the class hierarchy must
1348 be acyclic</Emphasis>.  So these class declarations are OK:
1349
1350
1351 <ProgramListing>
1352   class Functor (m k) =&#62; FiniteMap m k where
1353     ...
1354
1355   class (Monad m, Monad (t m)) =&#62; Transform t m where
1356     lift :: m a -&#62; (t m) a
1357 </ProgramListing>
1358
1359
1360 </Para>
1361 </ListItem>
1362 <ListItem>
1363
1364 <Para>
1365  <Emphasis>In the signature of a class operation, every constraint
1366 must mention at least one type variable that is not a class type
1367 variable</Emphasis>.
1368
1369 Thus:
1370
1371
1372 <ProgramListing>
1373   class Collection c a where
1374     mapC :: Collection c b =&#62; (a-&#62;b) -&#62; c a -&#62; c b
1375 </ProgramListing>
1376
1377
1378 is OK because the constraint <Literal>(Collection a b)</Literal> mentions
1379 <Literal>b</Literal>, even though it also mentions the class variable
1380 <Literal>a</Literal>.  On the other hand:
1381
1382
1383 <ProgramListing>
1384   class C a where
1385     op :: Eq a =&#62; (a,b) -&#62; (a,b)
1386 </ProgramListing>
1387
1388
1389 is not OK because the constraint <Literal>(Eq a)</Literal> mentions on the class
1390 type variable <Literal>a</Literal>, but not <Literal>b</Literal>.  However, any such
1391 example is easily fixed by moving the offending context up to the
1392 superclass context:
1393
1394
1395 <ProgramListing>
1396   class Eq a =&#62; C a where
1397     op ::(a,b) -&#62; (a,b)
1398 </ProgramListing>
1399
1400
1401 A yet more relaxed rule would allow the context of a class-op signature
1402 to mention only class type variables.  However, that conflicts with
1403 Rule 1(b) for types above.
1404
1405 </Para>
1406 </ListItem>
1407 <ListItem>
1408
1409 <Para>
1410  <Emphasis>The type of each class operation must mention <Emphasis>all</Emphasis> of
1411 the class type variables</Emphasis>.  For example:
1412
1413
1414 <ProgramListing>
1415   class Coll s a where
1416     empty  :: s
1417     insert :: s -&#62; a -&#62; s
1418 </ProgramListing>
1419
1420
1421 is not OK, because the type of <Literal>empty</Literal> doesn't mention
1422 <Literal>a</Literal>.  This rule is a consequence of Rule 1(a), above, for
1423 types, and has the same motivation.
1424
1425 Sometimes, offending class declarations exhibit misunderstandings.  For
1426 example, <Literal>Coll</Literal> might be rewritten
1427
1428
1429 <ProgramListing>
1430   class Coll s a where
1431     empty  :: s a
1432     insert :: s a -&#62; a -&#62; s a
1433 </ProgramListing>
1434
1435
1436 which makes the connection between the type of a collection of
1437 <Literal>a</Literal>'s (namely <Literal>(s a)</Literal>) and the element type <Literal>a</Literal>.
1438 Occasionally this really doesn't work, in which case you can split the
1439 class like this:
1440
1441
1442 <ProgramListing>
1443   class CollE s where
1444     empty  :: s
1445
1446   class CollE s =&#62; Coll s a where
1447     insert :: s -&#62; a -&#62; s
1448 </ProgramListing>
1449
1450
1451 </Para>
1452 </ListItem>
1453
1454 </OrderedList>
1455
1456 </Para>
1457
1458 </Sect2>
1459
1460 <Sect2>
1461 <Title>Instance declarations</Title>
1462
1463 <Para>
1464
1465 <OrderedList>
1466 <ListItem>
1467
1468 <Para>
1469  <Emphasis>Instance declarations may not overlap</Emphasis>.  The two instance
1470 declarations
1471
1472
1473 <ProgramListing>
1474   instance context1 =&#62; C type1 where ...
1475   instance context2 =&#62; C type2 where ...
1476 </ProgramListing>
1477
1478
1479 "overlap" if <Literal>type1</Literal> and <Literal>type2</Literal> unify
1480
1481 However, if you give the command line option
1482 <Literal>-fallow-overlapping-instances</Literal><IndexTerm><Primary>-fallow-overlapping-instances
1483 option</Primary></IndexTerm> then two overlapping instance declarations are permitted
1484 iff
1485
1486
1487 <ItemizedList>
1488 <ListItem>
1489
1490 <Para>
1491  EITHER <Literal>type1</Literal> and <Literal>type2</Literal> do not unify
1492 </Para>
1493 </ListItem>
1494 <ListItem>
1495
1496 <Para>
1497  OR <Literal>type2</Literal> is a substitution instance of <Literal>type1</Literal>
1498 (but not identical to <Literal>type1</Literal>)
1499 </Para>
1500 </ListItem>
1501 <ListItem>
1502
1503 <Para>
1504  OR vice versa
1505 </Para>
1506 </ListItem>
1507
1508 </ItemizedList>
1509
1510
1511 Notice that these rules
1512
1513
1514 <ItemizedList>
1515 <ListItem>
1516
1517 <Para>
1518  make it clear which instance decl to use
1519 (pick the most specific one that matches)
1520
1521 </Para>
1522 </ListItem>
1523 <ListItem>
1524
1525 <Para>
1526  do not mention the contexts <Literal>context1</Literal>, <Literal>context2</Literal>
1527 Reason: you can pick which instance decl
1528 "matches" based on the type.
1529 </Para>
1530 </ListItem>
1531
1532 </ItemizedList>
1533
1534
1535 Regrettably, GHC doesn't guarantee to detect overlapping instance
1536 declarations if they appear in different modules.  GHC can "see" the
1537 instance declarations in the transitive closure of all the modules
1538 imported by the one being compiled, so it can "see" all instance decls
1539 when it is compiling <Literal>Main</Literal>.  However, it currently chooses not
1540 to look at ones that can't possibly be of use in the module currently
1541 being compiled, in the interests of efficiency.  (Perhaps we should
1542 change that decision, at least for <Literal>Main</Literal>.)
1543
1544 </Para>
1545 </ListItem>
1546 <ListItem>
1547
1548 <Para>
1549  <Emphasis>There are no restrictions on the type in an instance
1550 <Emphasis>head</Emphasis>, except that at least one must not be a type variable</Emphasis>.
1551 The instance "head" is the bit after the "=&#62;" in an instance decl. For
1552 example, these are OK:
1553
1554
1555 <ProgramListing>
1556   instance C Int a where ...
1557
1558   instance D (Int, Int) where ...
1559
1560   instance E [[a]] where ...
1561 </ProgramListing>
1562
1563
1564 Note that instance heads <Emphasis>may</Emphasis> contain repeated type variables.
1565 For example, this is OK:
1566
1567
1568 <ProgramListing>
1569   instance Stateful (ST s) (MutVar s) where ...
1570 </ProgramListing>
1571
1572
1573 The "at least one not a type variable" restriction is to ensure that
1574 context reduction terminates: each reduction step removes one type
1575 constructor.  For example, the following would make the type checker
1576 loop if it wasn't excluded:
1577
1578
1579 <ProgramListing>
1580   instance C a =&#62; C a where ...
1581 </ProgramListing>
1582
1583
1584 There are two situations in which the rule is a bit of a pain. First,
1585 if one allows overlapping instance declarations then it's quite
1586 convenient to have a "default instance" declaration that applies if
1587 something more specific does not:
1588
1589
1590 <ProgramListing>
1591   instance C a where
1592     op = ... -- Default
1593 </ProgramListing>
1594
1595
1596 Second, sometimes you might want to use the following to get the
1597 effect of a "class synonym":
1598
1599
1600 <ProgramListing>
1601   class (C1 a, C2 a, C3 a) =&#62; C a where { }
1602
1603   instance (C1 a, C2 a, C3 a) =&#62; C a where { }
1604 </ProgramListing>
1605
1606
1607 This allows you to write shorter signatures:
1608
1609
1610 <ProgramListing>
1611   f :: C a =&#62; ...
1612 </ProgramListing>
1613
1614
1615 instead of
1616
1617
1618 <ProgramListing>
1619   f :: (C1 a, C2 a, C3 a) =&#62; ...
1620 </ProgramListing>
1621
1622
1623 I'm on the lookout for a simple rule that preserves decidability while
1624 allowing these idioms.  The experimental flag
1625 <Literal>-fallow-undecidable-instances</Literal><IndexTerm><Primary>-fallow-undecidable-instances
1626 option</Primary></IndexTerm> lifts this restriction, allowing all the types in an
1627 instance head to be type variables.
1628
1629 </Para>
1630 </ListItem>
1631 <ListItem>
1632
1633 <Para>
1634  <Emphasis>Unlike Haskell 1.4, instance heads may use type
1635 synonyms</Emphasis>.  As always, using a type synonym is just shorthand for
1636 writing the RHS of the type synonym definition.  For example:
1637
1638
1639 <ProgramListing>
1640   type Point = (Int,Int)
1641   instance C Point   where ...
1642   instance C [Point] where ...
1643 </ProgramListing>
1644
1645
1646 is legal.  However, if you added
1647
1648
1649 <ProgramListing>
1650   instance C (Int,Int) where ...
1651 </ProgramListing>
1652
1653
1654 as well, then the compiler will complain about the overlapping
1655 (actually, identical) instance declarations.  As always, type synonyms
1656 must be fully applied.  You cannot, for example, write:
1657
1658
1659 <ProgramListing>
1660   type P a = [[a]]
1661   instance Monad P where ...
1662 </ProgramListing>
1663
1664
1665 This design decision is independent of all the others, and easily
1666 reversed, but it makes sense to me.
1667
1668 </Para>
1669 </ListItem>
1670 <ListItem>
1671
1672 <Para>
1673 <Emphasis>The types in an instance-declaration <Emphasis>context</Emphasis> must all
1674 be type variables</Emphasis>. Thus
1675
1676
1677 <ProgramListing>
1678 instance C a b =&#62; Eq (a,b) where ...
1679 </ProgramListing>
1680
1681
1682 is OK, but
1683
1684
1685 <ProgramListing>
1686 instance C Int b =&#62; Foo b where ...
1687 </ProgramListing>
1688
1689
1690 is not OK.  Again, the intent here is to make sure that context
1691 reduction terminates.
1692
1693 Voluminous correspondence on the Haskell mailing list has convinced me
1694 that it's worth experimenting with a more liberal rule.  If you use
1695 the flag <Literal>-fallow-undecidable-instances</Literal> you can use arbitrary
1696 types in an instance context.  Termination is ensured by having a
1697 fixed-depth recursion stack.  If you exceed the stack depth you get a
1698 sort of backtrace, and the opportunity to increase the stack depth
1699 with <Literal>-fcontext-stack</Literal><Emphasis>N</Emphasis>.
1700
1701 </Para>
1702 </ListItem>
1703
1704 </OrderedList>
1705
1706 </Para>
1707
1708 </Sect2>
1709
1710 </Sect1>
1711
1712 <Sect1 id="universal-quantification">
1713 <Title>Explicit universal quantification
1714 </Title>
1715
1716 <Para>
1717 GHC now allows you to write explicitly quantified types.  GHC's
1718 syntax for this now agrees with Hugs's, namely:
1719 </Para>
1720
1721 <Para>
1722
1723 <ProgramListing>
1724         forall a b. (Ord a, Eq  b) =&#62; a -&#62; b -&#62; a
1725 </ProgramListing>
1726
1727 </Para>
1728
1729 <Para>
1730 The context is, of course, optional.  You can't use <Literal>forall</Literal> as
1731 a type variable any more!
1732 </Para>
1733
1734 <Para>
1735 Haskell type signatures are implicitly quantified.  The <Literal>forall</Literal>
1736 allows us to say exactly what this means.  For example:
1737 </Para>
1738
1739 <Para>
1740
1741 <ProgramListing>
1742         g :: b -&#62; b
1743 </ProgramListing>
1744
1745 </Para>
1746
1747 <Para>
1748 means this:
1749 </Para>
1750
1751 <Para>
1752
1753 <ProgramListing>
1754         g :: forall b. (b -&#62; b)
1755 </ProgramListing>
1756
1757 </Para>
1758
1759 <Para>
1760 The two are treated identically.
1761 </Para>
1762
1763 <Sect2 id="univ">
1764 <Title>Universally-quantified data type fields
1765 </Title>
1766
1767 <Para>
1768 In a <Literal>data</Literal> or <Literal>newtype</Literal> declaration one can quantify
1769 the types of the constructor arguments.  Here are several examples:
1770 </Para>
1771
1772 <Para>
1773
1774 <ProgramListing>
1775 data T a = T1 (forall b. b -&#62; b -&#62; b) a
1776
1777 data MonadT m = MkMonad { return :: forall a. a -&#62; m a,
1778                           bind   :: forall a b. m a -&#62; (a -&#62; m b) -&#62; m b
1779                         }
1780
1781 newtype Swizzle = MkSwizzle (Ord a =&#62; [a] -&#62; [a])
1782 </ProgramListing>
1783
1784 </Para>
1785
1786 <Para>
1787 The constructors now have so-called <Emphasis>rank 2</Emphasis> polymorphic
1788 types, in which there is a for-all in the argument types.:
1789 </Para>
1790
1791 <Para>
1792
1793 <ProgramListing>
1794 T1 :: forall a. (forall b. b -&#62; b -&#62; b) -&#62; a -&#62; T1 a
1795 MkMonad :: forall m. (forall a. a -&#62; m a)
1796                   -&#62; (forall a b. m a -&#62; (a -&#62; m b) -&#62; m b)
1797                   -&#62; MonadT m
1798 MkSwizzle :: (Ord a =&#62; [a] -&#62; [a]) -&#62; Swizzle
1799 </ProgramListing>
1800
1801 </Para>
1802
1803 <Para>
1804 Notice that you don't need to use a <Literal>forall</Literal> if there's an
1805 explicit context.  For example in the first argument of the
1806 constructor <Literal>MkSwizzle</Literal>, an implicit "<Literal>forall a.</Literal>" is
1807 prefixed to the argument type.  The implicit <Literal>forall</Literal>
1808 quantifies all type variables that are not already in scope, and are
1809 mentioned in the type quantified over.
1810 </Para>
1811
1812 <Para>
1813 As for type signatures, implicit quantification happens for non-overloaded
1814 types too.  So if you write this:
1815
1816 <ProgramListing>
1817   data T a = MkT (Either a b) (b -&#62; b)
1818 </ProgramListing>
1819
1820 it's just as if you had written this:
1821
1822 <ProgramListing>
1823   data T a = MkT (forall b. Either a b) (forall b. b -&#62; b)
1824 </ProgramListing>
1825
1826 That is, since the type variable <Literal>b</Literal> isn't in scope, it's
1827 implicitly universally quantified.  (Arguably, it would be better
1828 to <Emphasis>require</Emphasis> explicit quantification on constructor arguments
1829 where that is what is wanted.  Feedback welcomed.)
1830 </Para>
1831
1832 </Sect2>
1833
1834 <Sect2>
1835 <Title>Construction </Title>
1836
1837 <Para>
1838 You construct values of types <Literal>T1, MonadT, Swizzle</Literal> by applying
1839 the constructor to suitable values, just as usual.  For example,
1840 </Para>
1841
1842 <Para>
1843
1844 <ProgramListing>
1845 (T1 (\xy-&#62;x) 3) :: T Int
1846
1847 (MkSwizzle sort)    :: Swizzle
1848 (MkSwizzle reverse) :: Swizzle
1849
1850 (let r x = Just x
1851      b m k = case m of
1852                 Just y -&#62; k y
1853                 Nothing -&#62; Nothing
1854   in
1855   MkMonad r b) :: MonadT Maybe
1856 </ProgramListing>
1857
1858 </Para>
1859
1860 <Para>
1861 The type of the argument can, as usual, be more general than the type
1862 required, as <Literal>(MkSwizzle reverse)</Literal> shows.  (<Literal>reverse</Literal>
1863 does not need the <Literal>Ord</Literal> constraint.)
1864 </Para>
1865
1866 </Sect2>
1867
1868 <Sect2>
1869 <Title>Pattern matching</Title>
1870
1871 <Para>
1872 When you use pattern matching, the bound variables may now have
1873 polymorphic types.  For example:
1874 </Para>
1875
1876 <Para>
1877
1878 <ProgramListing>
1879         f :: T a -&#62; a -&#62; (a, Char)
1880         f (T1 f k) x = (f k x, f 'c' 'd')
1881
1882         g :: (Ord a, Ord b) =&#62; Swizzle -&#62; [a] -&#62; (a -&#62; b) -&#62; [b]
1883         g (MkSwizzle s) xs f = s (map f (s xs))
1884
1885         h :: MonadT m -&#62; [m a] -&#62; m [a]
1886         h m [] = return m []
1887         h m (x:xs) = bind m x           $ \y -&#62;
1888                       bind m (h m xs)   $ \ys -&#62;
1889                       return m (y:ys)
1890 </ProgramListing>
1891
1892 </Para>
1893
1894 <Para>
1895 In the function <Literal>h</Literal> we use the record selectors <Literal>return</Literal>
1896 and <Literal>bind</Literal> to extract the polymorphic bind and return functions
1897 from the <Literal>MonadT</Literal> data structure, rather than using pattern
1898 matching.
1899 </Para>
1900
1901 <Para>
1902 You cannot pattern-match against an argument that is polymorphic.
1903 For example:
1904
1905 <ProgramListing>
1906         newtype TIM s a = TIM (ST s (Maybe a))
1907
1908         runTIM :: (forall s. TIM s a) -&#62; Maybe a
1909         runTIM (TIM m) = runST m
1910 </ProgramListing>
1911
1912 </Para>
1913
1914 <Para>
1915 Here the pattern-match fails, because you can't pattern-match against
1916 an argument of type <Literal>(forall s. TIM s a)</Literal>.  Instead you
1917 must bind the variable and pattern match in the right hand side:
1918
1919 <ProgramListing>
1920         runTIM :: (forall s. TIM s a) -&#62; Maybe a
1921         runTIM tm = case tm of { TIM m -&#62; runST m }
1922 </ProgramListing>
1923
1924 The <Literal>tm</Literal> on the right hand side is (invisibly) instantiated, like
1925 any polymorphic value at its occurrence site, and now you can pattern-match
1926 against it.
1927 </Para>
1928
1929 </Sect2>
1930
1931 <Sect2>
1932 <Title>The partial-application restriction</Title>
1933
1934 <Para>
1935 There is really only one way in which data structures with polymorphic
1936 components might surprise you: you must not partially apply them.
1937 For example, this is illegal:
1938 </Para>
1939
1940 <Para>
1941
1942 <ProgramListing>
1943         map MkSwizzle [sort, reverse]
1944 </ProgramListing>
1945
1946 </Para>
1947
1948 <Para>
1949 The restriction is this: <Emphasis>every subexpression of the program must
1950 have a type that has no for-alls, except that in a function
1951 application (f e1&hellip;en) the partial applications are not subject to
1952 this rule</Emphasis>.  The restriction makes type inference feasible.
1953 </Para>
1954
1955 <Para>
1956 In the illegal example, the sub-expression <Literal>MkSwizzle</Literal> has the
1957 polymorphic type <Literal>(Ord b =&#62; [b] -&#62; [b]) -&#62; Swizzle</Literal> and is not
1958 a sub-expression of an enclosing application.  On the other hand, this
1959 expression is OK:
1960 </Para>
1961
1962 <Para>
1963
1964 <ProgramListing>
1965         map (T1 (\a b -&#62; a)) [1,2,3]
1966 </ProgramListing>
1967
1968 </Para>
1969
1970 <Para>
1971 even though it involves a partial application of <Literal>T1</Literal>, because
1972 the sub-expression <Literal>T1 (\a b -&#62; a)</Literal> has type <Literal>Int -&#62; T
1973 Int</Literal>.
1974 </Para>
1975
1976 </Sect2>
1977
1978 <Sect2 id="sigs">
1979 <Title>Type signatures
1980 </Title>
1981
1982 <Para>
1983 Once you have data constructors with universally-quantified fields, or
1984 constants such as <Literal>runST</Literal> that have rank-2 types, it isn't long
1985 before you discover that you need more!  Consider:
1986 </Para>
1987
1988 <Para>
1989
1990 <ProgramListing>
1991   mkTs f x y = [T1 f x, T1 f y]
1992 </ProgramListing>
1993
1994 </Para>
1995
1996 <Para>
1997 <Literal>mkTs</Literal> is a fuction that constructs some values of type
1998 <Literal>T</Literal>, using some pieces passed to it.  The trouble is that since
1999 <Literal>f</Literal> is a function argument, Haskell assumes that it is
2000 monomorphic, so we'll get a type error when applying <Literal>T1</Literal> to
2001 it.  This is a rather silly example, but the problem really bites in
2002 practice.  Lots of people trip over the fact that you can't make
2003 "wrappers functions" for <Literal>runST</Literal> for exactly the same reason.
2004 In short, it is impossible to build abstractions around functions with
2005 rank-2 types.
2006 </Para>
2007
2008 <Para>
2009 The solution is fairly clear.  We provide the ability to give a rank-2
2010 type signature for <Emphasis>ordinary</Emphasis> functions (not only data
2011 constructors), thus:
2012 </Para>
2013
2014 <Para>
2015
2016 <ProgramListing>
2017   mkTs :: (forall b. b -&#62; b -&#62; b) -&#62; a -&#62; [T a]
2018   mkTs f x y = [T1 f x, T1 f y]
2019 </ProgramListing>
2020
2021 </Para>
2022
2023 <Para>
2024 This type signature tells the compiler to attribute <Literal>f</Literal> with
2025 the polymorphic type <Literal>(forall b. b -&#62; b -&#62; b)</Literal> when type
2026 checking the body of <Literal>mkTs</Literal>, so now the application of
2027 <Literal>T1</Literal> is fine.
2028 </Para>
2029
2030 <Para>
2031 There are two restrictions:
2032 </Para>
2033
2034 <Para>
2035
2036 <ItemizedList>
2037 <ListItem>
2038
2039 <Para>
2040  You can only define a rank 2 type, specified by the following
2041 grammar:
2042
2043
2044 <ProgramListing>
2045    rank2type ::= [forall tyvars .] [context =&#62;] funty
2046    funty     ::= ([forall tyvars .] [context =&#62;] ty) -&#62; funty
2047                | ty
2048    ty        ::= ...current Haskell monotype syntax...
2049 </ProgramListing>
2050
2051
2052 Informally, the universal quantification must all be right at the beginning,
2053 or at the top level of a function argument.
2054
2055 </Para>
2056 </ListItem>
2057 <ListItem>
2058
2059 <Para>
2060  There is a restriction on the definition of a function whose
2061 type signature is a rank-2 type: the polymorphic arguments must be
2062 matched on the left hand side of the "<Literal>=</Literal>" sign.  You can't
2063 define <Literal>mkTs</Literal> like this:
2064
2065
2066 <ProgramListing>
2067   mkTs :: (forall b. b -&#62; b -&#62; b) -&#62; a -&#62; [T a]
2068   mkTs = \ f x y -&#62; [T1 f x, T1 f y]
2069 </ProgramListing>
2070
2071
2072
2073 The same partial-application rule applies to ordinary functions with
2074 rank-2 types as applied to data constructors.
2075
2076 </Para>
2077 </ListItem>
2078
2079 </ItemizedList>
2080
2081 </Para>
2082
2083 </Sect2>
2084
2085 </Sect1>
2086
2087 <Sect1 id="existential-quantification">
2088 <Title>Existentially quantified data constructors
2089 </Title>
2090
2091 <Para>
2092 The idea of using existential quantification in data type declarations
2093 was suggested by Laufer (I believe, thought doubtless someone will
2094 correct me), and implemented in Hope+. It's been in Lennart
2095 Augustsson's <Literal>hbc</Literal> Haskell compiler for several years, and
2096 proved very useful.  Here's the idea.  Consider the declaration:
2097 </Para>
2098
2099 <Para>
2100
2101 <ProgramListing>
2102   data Foo = forall a. MkFoo a (a -&#62; Bool)
2103            | Nil
2104 </ProgramListing>
2105
2106 </Para>
2107
2108 <Para>
2109 The data type <Literal>Foo</Literal> has two constructors with types:
2110 </Para>
2111
2112 <Para>
2113
2114 <ProgramListing>
2115   MkFoo :: forall a. a -&#62; (a -&#62; Bool) -&#62; Foo
2116   Nil   :: Foo
2117 </ProgramListing>
2118
2119 </Para>
2120
2121 <Para>
2122 Notice that the type variable <Literal>a</Literal> in the type of <Literal>MkFoo</Literal>
2123 does not appear in the data type itself, which is plain <Literal>Foo</Literal>.
2124 For example, the following expression is fine:
2125 </Para>
2126
2127 <Para>
2128
2129 <ProgramListing>
2130   [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
2131 </ProgramListing>
2132
2133 </Para>
2134
2135 <Para>
2136 Here, <Literal>(MkFoo 3 even)</Literal> packages an integer with a function
2137 <Literal>even</Literal> that maps an integer to <Literal>Bool</Literal>; and <Literal>MkFoo 'c'
2138 isUpper</Literal> packages a character with a compatible function.  These
2139 two things are each of type <Literal>Foo</Literal> and can be put in a list.
2140 </Para>
2141
2142 <Para>
2143 What can we do with a value of type <Literal>Foo</Literal>?.  In particular,
2144 what happens when we pattern-match on <Literal>MkFoo</Literal>?
2145 </Para>
2146
2147 <Para>
2148
2149 <ProgramListing>
2150   f (MkFoo val fn) = ???
2151 </ProgramListing>
2152
2153 </Para>
2154
2155 <Para>
2156 Since all we know about <Literal>val</Literal> and <Literal>fn</Literal> is that they
2157 are compatible, the only (useful) thing we can do with them is to
2158 apply <Literal>fn</Literal> to <Literal>val</Literal> to get a boolean.  For example:
2159 </Para>
2160
2161 <Para>
2162
2163 <ProgramListing>
2164   f :: Foo -&#62; Bool
2165   f (MkFoo val fn) = fn val
2166 </ProgramListing>
2167
2168 </Para>
2169
2170 <Para>
2171 What this allows us to do is to package heterogenous values
2172 together with a bunch of functions that manipulate them, and then treat
2173 that collection of packages in a uniform manner.  You can express
2174 quite a bit of object-oriented-like programming this way.
2175 </Para>
2176
2177 <Sect2 id="existential">
2178 <Title>Why existential?
2179 </Title>
2180
2181 <Para>
2182 What has this to do with <Emphasis>existential</Emphasis> quantification?
2183 Simply that <Literal>MkFoo</Literal> has the (nearly) isomorphic type
2184 </Para>
2185
2186 <Para>
2187
2188 <ProgramListing>
2189   MkFoo :: (exists a . (a, a -&#62; Bool)) -&#62; Foo
2190 </ProgramListing>
2191
2192 </Para>
2193
2194 <Para>
2195 But Haskell programmers can safely think of the ordinary
2196 <Emphasis>universally</Emphasis> quantified type given above, thereby avoiding
2197 adding a new existential quantification construct.
2198 </Para>
2199
2200 </Sect2>
2201
2202 <Sect2>
2203 <Title>Type classes</Title>
2204
2205 <Para>
2206 An easy extension (implemented in <Literal>hbc</Literal>) is to allow
2207 arbitrary contexts before the constructor.  For example:
2208 </Para>
2209
2210 <Para>
2211
2212 <ProgramListing>
2213   data Baz = forall a. Eq a =&#62; Baz1 a a
2214            | forall b. Show b =&#62; Baz2 b (b -&#62; b)
2215 </ProgramListing>
2216
2217 </Para>
2218
2219 <Para>
2220 The two constructors have the types you'd expect:
2221 </Para>
2222
2223 <Para>
2224
2225 <ProgramListing>
2226   Baz1 :: forall a. Eq a =&#62; a -&#62; a -&#62; Baz
2227   Baz2 :: forall b. Show b =&#62; b -&#62; (b -&#62; b) -&#62; Baz
2228 </ProgramListing>
2229
2230 </Para>
2231
2232 <Para>
2233 But when pattern matching on <Literal>Baz1</Literal> the matched values can be compared
2234 for equality, and when pattern matching on <Literal>Baz2</Literal> the first matched
2235 value can be converted to a string (as well as applying the function to it).
2236 So this program is legal:
2237 </Para>
2238
2239 <Para>
2240
2241 <ProgramListing>
2242   f :: Baz -&#62; String
2243   f (Baz1 p q) | p == q    = "Yes"
2244                | otherwise = "No"
2245   f (Baz1 v fn)            = show (fn v)
2246 </ProgramListing>
2247
2248 </Para>
2249
2250 <Para>
2251 Operationally, in a dictionary-passing implementation, the
2252 constructors <Literal>Baz1</Literal> and <Literal>Baz2</Literal> must store the
2253 dictionaries for <Literal>Eq</Literal> and <Literal>Show</Literal> respectively, and
2254 extract it on pattern matching.
2255 </Para>
2256
2257 <Para>
2258 Notice the way that the syntax fits smoothly with that used for
2259 universal quantification earlier.
2260 </Para>
2261
2262 </Sect2>
2263
2264 <Sect2>
2265 <Title>Restrictions</Title>
2266
2267 <Para>
2268 There are several restrictions on the ways in which existentially-quantified
2269 constructors can be use.
2270 </Para>
2271
2272 <Para>
2273
2274 <ItemizedList>
2275 <ListItem>
2276
2277 <Para>
2278  When pattern matching, each pattern match introduces a new,
2279 distinct, type for each existential type variable.  These types cannot
2280 be unified with any other type, nor can they escape from the scope of
2281 the pattern match.  For example, these fragments are incorrect:
2282
2283
2284 <ProgramListing>
2285   f1 (MkFoo a f) = a
2286 </ProgramListing>
2287
2288
2289 Here, the type bound by <Literal>MkFoo</Literal> "escapes", because <Literal>a</Literal>
2290 is the result of <Literal>f1</Literal>.  One way to see why this is wrong is to
2291 ask what type <Literal>f1</Literal> has:
2292
2293
2294 <ProgramListing>
2295   f1 :: Foo -&#62; a             -- Weird!
2296 </ProgramListing>
2297
2298
2299 What is this "<Literal>a</Literal>" in the result type? Clearly we don't mean
2300 this:
2301
2302
2303 <ProgramListing>
2304   f1 :: forall a. Foo -&#62; a   -- Wrong!
2305 </ProgramListing>
2306
2307
2308 The original program is just plain wrong.  Here's another sort of error
2309
2310
2311 <ProgramListing>
2312   f2 (Baz1 a b) (Baz1 p q) = a==q
2313 </ProgramListing>
2314
2315
2316 It's ok to say <Literal>a==b</Literal> or <Literal>p==q</Literal>, but
2317 <Literal>a==q</Literal> is wrong because it equates the two distinct types arising
2318 from the two <Literal>Baz1</Literal> constructors.
2319
2320
2321 </Para>
2322 </ListItem>
2323 <ListItem>
2324
2325 <Para>
2326 You can't pattern-match on an existentially quantified
2327 constructor in a <Literal>let</Literal> or <Literal>where</Literal> group of
2328 bindings. So this is illegal:
2329
2330
2331 <ProgramListing>
2332   f3 x = a==b where { Baz1 a b = x }
2333 </ProgramListing>
2334
2335
2336 You can only pattern-match
2337 on an existentially-quantified constructor in a <Literal>case</Literal> expression or
2338 in the patterns of a function definition.
2339
2340 The reason for this restriction is really an implementation one.
2341 Type-checking binding groups is already a nightmare without
2342 existentials complicating the picture.  Also an existential pattern
2343 binding at the top level of a module doesn't make sense, because it's
2344 not clear how to prevent the existentially-quantified type "escaping".
2345 So for now, there's a simple-to-state restriction.  We'll see how
2346 annoying it is.
2347
2348 </Para>
2349 </ListItem>
2350 <ListItem>
2351
2352 <Para>
2353 You can't use existential quantification for <Literal>newtype</Literal>
2354 declarations.  So this is illegal:
2355
2356
2357 <ProgramListing>
2358   newtype T = forall a. Ord a =&#62; MkT a
2359 </ProgramListing>
2360
2361
2362 Reason: a value of type <Literal>T</Literal> must be represented as a pair
2363 of a dictionary for <Literal>Ord t</Literal> and a value of type <Literal>t</Literal>.
2364 That contradicts the idea that <Literal>newtype</Literal> should have no
2365 concrete representation.  You can get just the same efficiency and effect
2366 by using <Literal>data</Literal> instead of <Literal>newtype</Literal>.  If there is no
2367 overloading involved, then there is more of a case for allowing
2368 an existentially-quantified <Literal>newtype</Literal>, because the <Literal>data</Literal>
2369 because the <Literal>data</Literal> version does carry an implementation cost,
2370 but single-field existentially quantified constructors aren't much
2371 use.  So the simple restriction (no existential stuff on <Literal>newtype</Literal>)
2372 stands, unless there are convincing reasons to change it.
2373
2374
2375 </Para>
2376 </ListItem>
2377 <ListItem>
2378
2379 <Para>
2380  You can't use <Literal>deriving</Literal> to define instances of a
2381 data type with existentially quantified data constructors.
2382
2383 Reason: in most cases it would not make sense. For example:&num;
2384
2385 <ProgramListing>
2386   data T = forall a. MkT [a] deriving( Eq )
2387 </ProgramListing>
2388
2389 To derive <Literal>Eq</Literal> in the standard way we would need to have equality
2390 between the single component of two <Literal>MkT</Literal> constructors:
2391
2392 <ProgramListing>
2393   instance Eq T where
2394     (MkT a) == (MkT b) = ???
2395 </ProgramListing>
2396
2397 But <Literal>a</Literal> and <Literal>b</Literal> have distinct types, and so can't be compared.
2398 It's just about possible to imagine examples in which the derived instance
2399 would make sense, but it seems altogether simpler simply to prohibit such
2400 declarations.  Define your own instances!
2401 </Para>
2402 </ListItem>
2403
2404 </ItemizedList>
2405
2406 </Para>
2407
2408 </Sect2>
2409
2410 </Sect1>
2411
2412 <Sect1 id="sec-assertions">
2413 <Title>Assertions
2414 <IndexTerm><Primary>Assertions</Primary></IndexTerm>
2415 </Title>
2416
2417 <Para>
2418 If you want to make use of assertions in your standard Haskell code, you
2419 could define a function like the following:
2420 </Para>
2421
2422 <Para>
2423
2424 <ProgramListing>
2425 assert :: Bool -&#62; a -&#62; a
2426 assert False x = error "assertion failed!"
2427 assert _     x = x
2428 </ProgramListing>
2429
2430 </Para>
2431
2432 <Para>
2433 which works, but gives you back a less than useful error message --
2434 an assertion failed, but which and where?
2435 </Para>
2436
2437 <Para>
2438 One way out is to define an extended <Literal>assert</Literal> function which also
2439 takes a descriptive string to include in the error message and
2440 perhaps combine this with the use of a pre-processor which inserts
2441 the source location where <Literal>assert</Literal> was used.
2442 </Para>
2443
2444 <Para>
2445 Ghc offers a helping hand here, doing all of this for you. For every
2446 use of <Literal>assert</Literal> in the user's source:
2447 </Para>
2448
2449 <Para>
2450
2451 <ProgramListing>
2452 kelvinToC :: Double -&#62; Double
2453 kelvinToC k = assert (k &amp;gt;= 0.0) (k+273.15)
2454 </ProgramListing>
2455
2456 </Para>
2457
2458 <Para>
2459 Ghc will rewrite this to also include the source location where the
2460 assertion was made,
2461 </Para>
2462
2463 <Para>
2464
2465 <ProgramListing>
2466 assert pred val ==&#62; assertError "Main.hs|15" pred val
2467 </ProgramListing>
2468
2469 </Para>
2470
2471 <Para>
2472 The rewrite is only performed by the compiler when it spots
2473 applications of <Literal>Exception.assert</Literal>, so you can still define and
2474 use your own versions of <Literal>assert</Literal>, should you so wish. If not,
2475 import <Literal>Exception</Literal> to make use <Literal>assert</Literal> in your code.
2476 </Para>
2477
2478 <Para>
2479 To have the compiler ignore uses of assert, use the compiler option
2480 <Literal>-fignore-asserts</Literal>. <IndexTerm><Primary>-fignore-asserts option</Primary></IndexTerm> That is,
2481 expressions of the form <Literal>assert pred e</Literal> will be rewritten to <Literal>e</Literal>.
2482 </Para>
2483
2484 <Para>
2485 Assertion failures can be caught, see the documentation for the
2486 Hugs/GHC Exception library for information of how.
2487 </Para>
2488
2489 </Sect1>
2490
2491 <Sect1 id="scoped-type-variables">
2492 <Title>Scoped Type Variables
2493 </Title>
2494
2495 <Para>
2496 A <Emphasis>pattern type signature</Emphasis> can introduce a <Emphasis>scoped type
2497 variable</Emphasis>.  For example
2498 </Para>
2499
2500 <Para>
2501
2502 <ProgramListing>
2503 f (xs::[a]) = ys ++ ys
2504            where
2505               ys :: [a]
2506               ys = reverse xs
2507 </ProgramListing>
2508
2509 </Para>
2510
2511 <Para>
2512 The pattern <Literal>(xs::[a])</Literal> includes a type signature for <Literal>xs</Literal>.
2513 This brings the type variable <Literal>a</Literal> into scope; it scopes over
2514 all the patterns and right hand sides for this equation for <Literal>f</Literal>.
2515 In particular, it is in scope at the type signature for <Literal>y</Literal>.
2516 </Para>
2517
2518 <Para>
2519 At ordinary type signatures, such as that for <Literal>ys</Literal>, any type variables
2520 mentioned in the type signature <Emphasis>that are not in scope</Emphasis> are
2521 implicitly universally quantified.  (If there are no type variables in
2522 scope, all type variables mentioned in the signature are universally
2523 quantified, which is just as in Haskell 98.)  In this case, since <Literal>a</Literal>
2524 is in scope, it is not universally quantified, so the type of <Literal>ys</Literal> is
2525 the same as that of <Literal>xs</Literal>.  In Haskell 98 it is not possible to declare
2526 a type for <Literal>ys</Literal>; a major benefit of scoped type variables is that
2527 it becomes possible to do so.
2528 </Para>
2529
2530 <Para>
2531 Scoped type variables are implemented in both GHC and Hugs.  Where the
2532 implementations differ from the specification below, those differences
2533 are noted.
2534 </Para>
2535
2536 <Para>
2537 So much for the basic idea.  Here are the details.
2538 </Para>
2539
2540 <Sect2>
2541 <Title>Scope and implicit quantification</Title>
2542
2543 <Para>
2544
2545 <ItemizedList>
2546 <ListItem>
2547
2548 <Para>
2549  All the type variables mentioned in the patterns for a single
2550 function definition equation, that are not already in scope,
2551 are brought into scope by the patterns.  We describe this set as
2552 the <Emphasis>type variables bound by the equation</Emphasis>.
2553
2554 </Para>
2555 </ListItem>
2556 <ListItem>
2557
2558 <Para>
2559  The type variables thus brought into scope may be mentioned
2560 in ordinary type signatures or pattern type signatures anywhere within
2561 their scope.
2562
2563 </Para>
2564 </ListItem>
2565 <ListItem>
2566
2567 <Para>
2568  In ordinary type signatures, any type variable mentioned in the
2569 signature that is in scope is <Emphasis>not</Emphasis> universally quantified.
2570
2571 </Para>
2572 </ListItem>
2573 <ListItem>
2574
2575 <Para>
2576  Ordinary type signatures do not bring any new type variables
2577 into scope (except in the type signature itself!). So this is illegal:
2578
2579
2580 <ProgramListing>
2581   f :: a -&#62; a
2582   f x = x::a
2583 </ProgramListing>
2584
2585
2586 It's illegal because <Literal>a</Literal> is not in scope in the body of <Literal>f</Literal>,
2587 so the ordinary signature <Literal>x::a</Literal> is equivalent to <Literal>x::forall a.a</Literal>;
2588 and that is an incorrect typing.
2589
2590 </Para>
2591 </ListItem>
2592 <ListItem>
2593
2594 <Para>
2595  There is no implicit universal quantification on pattern type
2596 signatures, nor may one write an explicit <Literal>forall</Literal> type in a pattern
2597 type signature.  The pattern type signature is a monotype.
2598
2599 </Para>
2600 </ListItem>
2601 <ListItem>
2602
2603 <Para>
2604
2605 The type variables in the head of a <Literal>class</Literal> or <Literal>instance</Literal> declaration
2606 scope over the methods defined in the <Literal>where</Literal> part.  For example:
2607
2608
2609 <ProgramListing>
2610   class C a where
2611     op :: [a] -&#62; a
2612
2613     op xs = let ys::[a]
2614                 ys = reverse xs
2615             in
2616             head ys
2617 </ProgramListing>
2618
2619
2620 (Not implemented in Hugs yet, Dec 98).
2621 </Para>
2622 </ListItem>
2623
2624 </ItemizedList>
2625
2626 </Para>
2627
2628 </Sect2>
2629
2630 <Sect2>
2631 <Title>Polymorphism</Title>
2632
2633 <Para>
2634
2635 <ItemizedList>
2636 <ListItem>
2637
2638 <Para>
2639  Pattern type signatures are completely orthogonal to ordinary, separate
2640 type signatures.  The two can be used independently or together.  There is
2641 no scoping associated with the names of the type variables in a separate type signature.
2642
2643
2644 <ProgramListing>
2645    f :: [a] -&#62; [a]
2646    f (xs::[b]) = reverse xs
2647 </ProgramListing>
2648
2649
2650 </Para>
2651 </ListItem>
2652 <ListItem>
2653
2654 <Para>
2655  The function must be polymorphic in the type variables
2656 bound by all its equations.  Operationally, the type variables bound
2657 by one equation must not:
2658
2659
2660 <ItemizedList>
2661 <ListItem>
2662
2663 <Para>
2664  Be unified with a type (such as <Literal>Int</Literal>, or <Literal>[a]</Literal>).
2665 </Para>
2666 </ListItem>
2667 <ListItem>
2668
2669 <Para>
2670  Be unified with a type variable free in the environment.
2671 </Para>
2672 </ListItem>
2673 <ListItem>
2674
2675 <Para>
2676  Be unified with each other.  (They may unify with the type variables
2677 bound by another equation for the same function, of course.)
2678 </Para>
2679 </ListItem>
2680
2681 </ItemizedList>
2682
2683
2684 For example, the following all fail to type check:
2685
2686
2687 <ProgramListing>
2688   f (x::a) (y::b) = [x,y]       -- a unifies with b
2689
2690   g (x::a) = x + 1::Int         -- a unifies with Int
2691
2692   h x = let k (y::a) = [x,y]    -- a is free in the
2693         in k x                  -- environment
2694
2695   k (x::a) True    = ...        -- a unifies with Int
2696   k (x::Int) False = ...
2697
2698   w :: [b] -&#62; [b]
2699   w (x::a) = x                  -- a unifies with [b]
2700 </ProgramListing>
2701
2702
2703 </Para>
2704 </ListItem>
2705 <ListItem>
2706
2707 <Para>
2708  The pattern-bound type variable may, however, be constrained
2709 by the context of the principal type, thus:
2710
2711
2712 <ProgramListing>
2713   f (x::a) (y::a) = x+y*2
2714 </ProgramListing>
2715
2716
2717 gets the inferred type: <Literal>forall a. Num a =&gt; a -&gt; a -&gt; a</Literal>.
2718 </Para>
2719 </ListItem>
2720
2721 </ItemizedList>
2722
2723 </Para>
2724
2725 </Sect2>
2726
2727 <Sect2>
2728 <Title>Result type signatures</Title>
2729
2730 <Para>
2731
2732 <ItemizedList>
2733 <ListItem>
2734
2735 <Para>
2736  The result type of a function can be given a signature,
2737 thus:
2738
2739
2740 <ProgramListing>
2741   f (x::a) :: [a] = [x,x,x]
2742 </ProgramListing>
2743
2744
2745 The final <Literal>":: [a]"</Literal> after all the patterns gives a signature to the
2746 result type.  Sometimes this is the only way of naming the type variable
2747 you want:
2748
2749
2750 <ProgramListing>
2751   f :: Int -&#62; [a] -&#62; [a]
2752   f n :: ([a] -&#62; [a]) = let g (x::a, y::a) = (y,x)
2753                         in \xs -&#62; map g (reverse xs `zip` xs)
2754 </ProgramListing>
2755
2756
2757 </Para>
2758 </ListItem>
2759
2760 </ItemizedList>
2761
2762 </Para>
2763
2764 <Para>
2765 Result type signatures are not yet implemented in Hugs.
2766 </Para>
2767
2768 </Sect2>
2769
2770 <Sect2>
2771 <Title>Pattern signatures on other constructs</Title>
2772
2773 <Para>
2774
2775 <ItemizedList>
2776 <ListItem>
2777
2778 <Para>
2779  A pattern type signature can be on an arbitrary sub-pattern, not
2780 just on a variable:
2781
2782
2783 <ProgramListing>
2784   f ((x,y)::(a,b)) = (y,x) :: (b,a)
2785 </ProgramListing>
2786
2787
2788 </Para>
2789 </ListItem>
2790 <ListItem>
2791
2792 <Para>
2793  Pattern type signatures, including the result part, can be used
2794 in lambda abstractions:
2795
2796
2797 <ProgramListing>
2798   (\ (x::a, y) :: a -&#62; x)
2799 </ProgramListing>
2800
2801
2802 Type variables bound by these patterns must be polymorphic in
2803 the sense defined above.
2804 For example:
2805
2806
2807 <ProgramListing>
2808   f1 (x::c) = f1 x      -- ok
2809   f2 = \(x::c) -&#62; f2 x  -- not ok
2810 </ProgramListing>
2811
2812
2813 Here, <Literal>f1</Literal> is OK, but <Literal>f2</Literal> is not, because <Literal>c</Literal> gets unified
2814 with a type variable free in the environment, in this
2815 case, the type of <Literal>f2</Literal>, which is in the environment when
2816 the lambda abstraction is checked.
2817
2818 </Para>
2819 </ListItem>
2820 <ListItem>
2821
2822 <Para>
2823  Pattern type signatures, including the result part, can be used
2824 in <Literal>case</Literal> expressions:
2825
2826
2827 <ProgramListing>
2828   case e of { (x::a, y) :: a -&#62; x }
2829 </ProgramListing>
2830
2831
2832 The pattern-bound type variables must, as usual,
2833 be polymorphic in the following sense: each case alternative,
2834 considered as a lambda abstraction, must be polymorphic.
2835 Thus this is OK:
2836
2837
2838 <ProgramListing>
2839   case (True,False) of { (x::a, y) -&#62; x }
2840 </ProgramListing>
2841
2842
2843 Even though the context is that of a pair of booleans,
2844 the alternative itself is polymorphic.  Of course, it is
2845 also OK to say:
2846
2847
2848 <ProgramListing>
2849   case (True,False) of { (x::Bool, y) -&#62; x }
2850 </ProgramListing>
2851
2852
2853 </Para>
2854 </ListItem>
2855 <ListItem>
2856
2857 <Para>
2858 To avoid ambiguity, the type after the ``<Literal>::</Literal>'' in a result
2859 pattern signature on a lambda or <Literal>case</Literal> must be atomic (i.e. a single
2860 token or a parenthesised type of some sort).  To see why,
2861 consider how one would parse this:
2862
2863
2864 <ProgramListing>
2865   \ x :: a -&#62; b -&#62; x
2866 </ProgramListing>
2867
2868
2869 </Para>
2870 </ListItem>
2871 <ListItem>
2872
2873 <Para>
2874  Pattern type signatures that bind new type variables
2875 may not be used in pattern bindings at all.
2876 So this is illegal:
2877
2878
2879 <ProgramListing>
2880   f x = let (y, z::a) = x in ...
2881 </ProgramListing>
2882
2883
2884 But these are OK, because they do not bind fresh type variables:
2885
2886
2887 <ProgramListing>
2888   f1 x            = let (y, z::Int) = x in ...
2889   f2 (x::(Int,a)) = let (y, z::a)   = x in ...
2890 </ProgramListing>
2891
2892
2893 However a single variable is considered a degenerate function binding,
2894 rather than a degerate pattern binding, so this is permitted, even
2895 though it binds a type variable:
2896
2897
2898 <ProgramListing>
2899   f :: (b-&#62;b) = \(x::b) -&#62; x
2900 </ProgramListing>
2901
2902
2903 </Para>
2904 </ListItem>
2905
2906 </ItemizedList>
2907
2908 Such degnerate function bindings do not fall under the monomorphism
2909 restriction.  Thus:
2910 </Para>
2911
2912 <Para>
2913
2914 <ProgramListing>
2915   g :: a -&#62; a -&#62; Bool = \x y. x==y
2916 </ProgramListing>
2917
2918 </Para>
2919
2920 <Para>
2921 Here <Literal>g</Literal> has type <Literal>forall a. Eq a =&gt; a -&gt; a -&gt; Bool</Literal>, just as if
2922 <Literal>g</Literal> had a separate type signature.  Lacking a type signature, <Literal>g</Literal>
2923 would get a monomorphic type.
2924 </Para>
2925
2926 </Sect2>
2927
2928 <Sect2>
2929 <Title>Existentials</Title>
2930
2931 <Para>
2932
2933 <ItemizedList>
2934 <ListItem>
2935
2936 <Para>
2937  Pattern type signatures can bind existential type variables.
2938 For example:
2939
2940
2941 <ProgramListing>
2942   data T = forall a. MkT [a]
2943
2944   f :: T -&#62; T
2945   f (MkT [t::a]) = MkT t3
2946                  where
2947                    t3::[a] = [t,t,t]
2948 </ProgramListing>
2949
2950
2951 </Para>
2952 </ListItem>
2953
2954 </ItemizedList>
2955
2956 </Para>
2957
2958 </Sect2>
2959
2960 </Sect1>
2961
2962 <Sect1 id="pragmas">
2963 <Title>Pragmas
2964 </Title>
2965
2966 <Para>
2967 GHC supports several pragmas, or instructions to the compiler placed
2968 in the source code.  Pragmas don't affect the meaning of the program,
2969 but they might affect the efficiency of the generated code.
2970 </Para>
2971
2972 <Sect2 id="inline-pragma">
2973 <Title>INLINE pragma
2974
2975 <IndexTerm><Primary>INLINE pragma</Primary></IndexTerm>
2976 <IndexTerm><Primary>pragma, INLINE</Primary></IndexTerm></Title>
2977
2978 <Para>
2979 GHC (with <Literal>-O</Literal>, as always) tries to inline (or ``unfold'')
2980 functions/values that are ``small enough,'' thus avoiding the call
2981 overhead and possibly exposing other more-wonderful optimisations.
2982 </Para>
2983
2984 <Para>
2985 You will probably see these unfoldings (in Core syntax) in your
2986 interface files.
2987 </Para>
2988
2989 <Para>
2990 Normally, if GHC decides a function is ``too expensive'' to inline, it
2991 will not do so, nor will it export that unfolding for other modules to
2992 use.
2993 </Para>
2994
2995 <Para>
2996 The sledgehammer you can bring to bear is the
2997 <Literal>INLINE</Literal><IndexTerm><Primary>INLINE pragma</Primary></IndexTerm> pragma, used thusly:
2998
2999 <ProgramListing>
3000 key_function :: Int -&#62; String -&#62; (Bool, Double)
3001
3002 #ifdef __GLASGOW_HASKELL__
3003 {-# INLINE key_function #-}
3004 #endif
3005 </ProgramListing>
3006
3007 (You don't need to do the C pre-processor carry-on unless you're going
3008 to stick the code through HBC&mdash;it doesn't like <Literal>INLINE</Literal> pragmas.)
3009 </Para>
3010
3011 <Para>
3012 The major effect of an <Literal>INLINE</Literal> pragma is to declare a function's
3013 ``cost'' to be very low.  The normal unfolding machinery will then be
3014 very keen to inline it.
3015 </Para>
3016
3017 <Para>
3018 An <Literal>INLINE</Literal> pragma for a function can be put anywhere its type
3019 signature could be put.
3020 </Para>
3021
3022 <Para>
3023 <Literal>INLINE</Literal> pragmas are a particularly good idea for the
3024 <Literal>then</Literal>/<Literal>return</Literal> (or <Literal>bind</Literal>/<Literal>unit</Literal>) functions in a monad.
3025 For example, in GHC's own <Literal>UniqueSupply</Literal> monad code, we have:
3026
3027 <ProgramListing>
3028 #ifdef __GLASGOW_HASKELL__
3029 {-# INLINE thenUs #-}
3030 {-# INLINE returnUs #-}
3031 #endif
3032 </ProgramListing>
3033
3034 </Para>
3035
3036 </Sect2>
3037
3038 <Sect2 id="noinline-pragma">
3039 <Title>NOINLINE pragma
3040 </Title>
3041
3042 <Para>
3043 <IndexTerm><Primary>NOINLINE pragma</Primary></IndexTerm>
3044 <IndexTerm><Primary>pragma, NOINLINE</Primary></IndexTerm>
3045 </Para>
3046
3047 <Para>
3048 The <Literal>NOINLINE</Literal> pragma does exactly what you'd expect: it stops the
3049 named function from being inlined by the compiler.  You shouldn't ever
3050 need to do this, unless you're very cautious about code size.
3051 </Para>
3052
3053 </Sect2>
3054
3055 <Sect2 id="specialize-pragma">
3056 <Title>SPECIALIZE pragma
3057 </Title>
3058
3059 <Para>
3060 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3061 <IndexTerm><Primary>pragma, SPECIALIZE</Primary></IndexTerm>
3062 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3063 </Para>
3064
3065 <Para>
3066 (UK spelling also accepted.)  For key overloaded functions, you can
3067 create extra versions (NB: more code space) specialised to particular
3068 types.  Thus, if you have an overloaded function:
3069 </Para>
3070
3071 <Para>
3072
3073 <ProgramListing>
3074 hammeredLookup :: Ord key =&#62; [(key, value)] -&#62; key -&#62; value
3075 </ProgramListing>
3076
3077 </Para>
3078
3079 <Para>
3080 If it is heavily used on lists with <Literal>Widget</Literal> keys, you could
3081 specialise it as follows:
3082
3083 <ProgramListing>
3084 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -&#62; Widget -&#62; value #-}
3085 </ProgramListing>
3086
3087 </Para>
3088
3089 <Para>
3090 To get very fancy, you can also specify a named function to use for
3091 the specialised value, by adding <Literal>= blah</Literal>, as in:
3092
3093 <ProgramListing>
3094 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
3095 </ProgramListing>
3096
3097 It's <Emphasis>Your Responsibility</Emphasis> to make sure that <Literal>blah</Literal> really
3098 behaves as a specialised version of <Literal>hammeredLookup</Literal>!!!
3099 </Para>
3100
3101 <Para>
3102 NOTE: the <Literal>=blah</Literal> feature isn't implemented in GHC 4.xx.
3103 </Para>
3104
3105 <Para>
3106 An example in which the <Literal>= blah</Literal> form will Win Big:
3107
3108 <ProgramListing>
3109 toDouble :: Real a =&#62; a -&#62; Double
3110 toDouble = fromRational . toRational
3111
3112 {-# SPECIALIZE toDouble :: Int -&#62; Double = i2d #-}
3113 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
3114 </ProgramListing>
3115
3116 The <Literal>i2d</Literal> function is virtually one machine instruction; the
3117 default conversion&mdash;via an intermediate <Literal>Rational</Literal>&mdash;is obscenely
3118 expensive by comparison.
3119 </Para>
3120
3121 <Para>
3122 By using the US spelling, your <Literal>SPECIALIZE</Literal> pragma will work with
3123 HBC, too.  Note that HBC doesn't support the <Literal>= blah</Literal> form.
3124 </Para>
3125
3126 <Para>
3127 A <Literal>SPECIALIZE</Literal> pragma for a function can be put anywhere its type
3128 signature could be put.
3129 </Para>
3130
3131 </Sect2>
3132
3133 <Sect2 id="specialize-instance-pragma">
3134 <Title>SPECIALIZE instance pragma
3135 </Title>
3136
3137 <Para>
3138 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3139 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3140 Same idea, except for instance declarations.  For example:
3141
3142 <ProgramListing>
3143 instance (Eq a) =&#62; Eq (Foo a) where { ... usual stuff ... }
3144
3145 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
3146 </ProgramListing>
3147
3148 Compatible with HBC, by the way.
3149 </Para>
3150
3151 </Sect2>
3152
3153 <Sect2 id="line-pragma">
3154 <Title>LINE pragma
3155 </Title>
3156
3157 <Para>
3158 <IndexTerm><Primary>LINE pragma</Primary></IndexTerm>
3159 <IndexTerm><Primary>pragma, LINE</Primary></IndexTerm>
3160 </Para>
3161
3162 <Para>
3163 This pragma is similar to C's <Literal>&num;line</Literal> pragma, and is mainly for use in
3164 automatically generated Haskell code.  It lets you specify the line
3165 number and filename of the original code; for example
3166 </Para>
3167
3168 <Para>
3169
3170 <ProgramListing>
3171 {-# LINE 42 "Foo.vhs" #-}
3172 </ProgramListing>
3173
3174 </Para>
3175
3176 <Para>
3177 if you'd generated the current file from something called <Literal>Foo.vhs</Literal>
3178 and this line corresponds to line 42 in the original.  GHC will adjust
3179 its error messages to refer to the line/file named in the <Literal>LINE</Literal>
3180 pragma.
3181 </Para>
3182
3183 </Sect2>
3184
3185 <Sect2>
3186 <Title>RULES pragma</Title>
3187
3188 <Para>
3189 The RULES pragma lets you specify rewrite rules.  It is described in
3190 <XRef LinkEnd="rewrite-rules">.
3191 </Para>
3192
3193 </Sect2>
3194
3195 </Sect1>
3196
3197 <Sect1 id="rewrite-rules">
3198 <Title>Rewrite rules
3199
3200 <IndexTerm><Primary>RULES pagma</Primary></IndexTerm>
3201 <IndexTerm><Primary>pragma, RULES</Primary></IndexTerm>
3202 <IndexTerm><Primary>rewrite rules</Primary></IndexTerm></Title>
3203
3204 <Para>
3205 The programmer can specify rewrite rules as part of the source program
3206 (in a pragma).  GHC applies these rewrite rules wherever it can.
3207 </Para>
3208
3209 <Para>
3210 Here is an example:
3211
3212 <ProgramListing>
3213   {-# RULES
3214         "map/map"       forall f g xs. map f (map g xs) = map (f.g) xs
3215   #-}
3216 </ProgramListing>
3217
3218 </Para>
3219
3220 <Sect2>
3221 <Title>Syntax</Title>
3222
3223 <Para>
3224 From a syntactic point of view:
3225
3226 <ItemizedList>
3227 <ListItem>
3228
3229 <Para>
3230  Each rule has a name, enclosed in double quotes.  The name itself has
3231 no significance at all.  It is only used when reporting how many times the rule fired.
3232 </Para>
3233 </ListItem>
3234 <ListItem>
3235
3236 <Para>
3237  There may be zero or more rules in a <Literal>RULES</Literal> pragma.
3238 </Para>
3239 </ListItem>
3240 <ListItem>
3241
3242 <Para>
3243  Layout applies in a <Literal>RULES</Literal> pragma.  Currently no new indentation level
3244 is set, so you must lay out your rules starting in the same column as the
3245 enclosing definitions.
3246 </Para>
3247 </ListItem>
3248 <ListItem>
3249
3250 <Para>
3251  Each variable mentioned in a rule must either be in scope (e.g. <Literal>map</Literal>),
3252 or bound by the <Literal>forall</Literal> (e.g. <Literal>f</Literal>, <Literal>g</Literal>, <Literal>xs</Literal>).  The variables bound by
3253 the <Literal>forall</Literal> are called the <Emphasis>pattern</Emphasis> variables.  They are separated
3254 by spaces, just like in a type <Literal>forall</Literal>.
3255 </Para>
3256 </ListItem>
3257 <ListItem>
3258
3259 <Para>
3260  A pattern variable may optionally have a type signature.
3261 If the type of the pattern variable is polymorphic, it <Emphasis>must</Emphasis> have a type signature.
3262 For example, here is the <Literal>foldr/build</Literal> rule:
3263
3264 <ProgramListing>
3265   "fold/build"  forall k z (g::forall b. (a-&#62;b-&#62;b) -&#62; b -&#62; b) .
3266                 foldr k z (build g) = g k z
3267 </ProgramListing>
3268
3269 Since <Literal>g</Literal> has a polymorphic type, it must have a type signature.
3270
3271 </Para>
3272 </ListItem>
3273 <ListItem>
3274
3275 <Para>
3276  The left hand side of a rule must consist of a top-level variable applied
3277 to arbitrary expressions.  For example, this is <Emphasis>not</Emphasis> OK:
3278
3279 <ProgramListing>
3280   "wrong1"   forall e1 e2.  case True of { True -&#62; e1; False -&#62; e2 } = e1
3281   "wrong2"   forall f.      f True = True
3282 </ProgramListing>
3283
3284 In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong1"</Literal>, the LHS has a pattern variable
3285 in the head.
3286 </Para>
3287 </ListItem>
3288 <ListItem>
3289
3290 <Para>
3291  A rule does not need to be in the same module as (any of) the
3292 variables it mentions, though of course they need to be in scope.
3293 </Para>
3294 </ListItem>
3295 <ListItem>
3296
3297 <Para>
3298  Rules are automatically exported from a module, just as instance declarations are.
3299 </Para>
3300 </ListItem>
3301
3302 </ItemizedList>
3303
3304 </Para>
3305
3306 </Sect2>
3307
3308 <Sect2>
3309 <Title>Semantics</Title>
3310
3311 <Para>
3312 From a semantic point of view:
3313
3314 <ItemizedList>
3315 <ListItem>
3316
3317 <Para>
3318  Rules are only applied if you use the <Literal>-O</Literal> flag.
3319
3320 </Para>
3321 </ListItem>
3322 <ListItem>
3323
3324 <Para>
3325  Rules are regarded as left-to-right rewrite rules.
3326 When GHC finds an expression that is a substitution instance of the LHS
3327 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
3328 By "a substitution instance" we mean that the LHS can be made equal to the
3329 expression by substituting for the pattern variables.
3330
3331 </Para>
3332 </ListItem>
3333 <ListItem>
3334
3335 <Para>
3336  The LHS and RHS of a rule are typechecked, and must have the
3337 same type.
3338
3339 </Para>
3340 </ListItem>
3341 <ListItem>
3342
3343 <Para>
3344  GHC makes absolutely no attempt to verify that the LHS and RHS
3345 of a rule have the same meaning.  That is undecideable in general, and
3346 infeasible in most interesting cases.  The responsibility is entirely the programmer's!
3347
3348 </Para>
3349 </ListItem>
3350 <ListItem>
3351
3352 <Para>
3353  GHC makes no attempt to make sure that the rules are confluent or
3354 terminating.  For example:
3355
3356 <ProgramListing>
3357   "loop"        forall x,y.  f x y = f y x
3358 </ProgramListing>
3359
3360 This rule will cause the compiler to go into an infinite loop.
3361
3362 </Para>
3363 </ListItem>
3364 <ListItem>
3365
3366 <Para>
3367  If more than one rule matches a call, GHC will choose one arbitrarily to apply.
3368
3369 </Para>
3370 </ListItem>
3371 <ListItem>
3372 <Para>
3373  GHC currently uses a very simple, syntactic, matching algorithm
3374 for matching a rule LHS with an expression.  It seeks a substitution
3375 which makes the LHS and expression syntactically equal modulo alpha
3376 conversion.  The pattern (rule), but not the expression, is eta-expanded if
3377 necessary.  (Eta-expanding the epression can lead to laziness bugs.)
3378 But not beta conversion (that's called higher-order matching).
3379 </Para>
3380
3381 <Para>
3382 Matching is carried out on GHC's intermediate language, which includes
3383 type abstractions and applications.  So a rule only matches if the
3384 types match too.  See <XRef LinkEnd="rule-spec"> below.
3385 </Para>
3386 </ListItem>
3387 <ListItem>
3388
3389 <Para>
3390  GHC keeps trying to apply the rules as it optimises the program.
3391 For example, consider:
3392
3393 <ProgramListing>
3394   let s = map f
3395       t = map g
3396   in
3397   s (t xs)
3398 </ProgramListing>
3399
3400 The expression <Literal>s (t xs)</Literal> does not match the rule <Literal>"map/map"</Literal>, but GHC
3401 will substitute for <Literal>s</Literal> and <Literal>t</Literal>, giving an expression which does match.
3402 If <Literal>s</Literal> or <Literal>t</Literal> was (a) used more than once, and (b) large or a redex, then it would
3403 not be substituted, and the rule would not fire.
3404
3405 </Para>
3406 </ListItem>
3407 <ListItem>
3408
3409 <Para>
3410  In the earlier phases of compilation, GHC inlines <Emphasis>nothing
3411 that appears on the LHS of a rule</Emphasis>, because once you have substituted
3412 for something you can't match against it (given the simple minded
3413 matching).  So if you write the rule
3414
3415 <ProgramListing>
3416         "map/map"       forall f,g.  map f . map g = map (f.g)
3417 </ProgramListing>
3418
3419 this <Emphasis>won't</Emphasis> match the expression <Literal>map f (map g xs)</Literal>.
3420 It will only match something written with explicit use of ".".
3421 Well, not quite.  It <Emphasis>will</Emphasis> match the expression
3422
3423 <ProgramListing>
3424         wibble f g xs
3425 </ProgramListing>
3426
3427 where <Literal>wibble</Literal> is defined:
3428
3429 <ProgramListing>
3430         wibble f g = map f . map g
3431 </ProgramListing>
3432
3433 because <Literal>wibble</Literal> will be inlined (it's small).
3434
3435 Later on in compilation, GHC starts inlining even things on the
3436 LHS of rules, but still leaves the rules enabled.  This inlining
3437 policy is controlled by the per-simplification-pass flag <Literal>-finline-phase</Literal>n.
3438
3439 </Para>
3440 </ListItem>
3441 <ListItem>
3442
3443 <Para>
3444  All rules are implicitly exported from the module, and are therefore
3445 in force in any module that imports the module that defined the rule, directly
3446 or indirectly.  (That is, if A imports B, which imports C, then C's rules are
3447 in force when compiling A.)  The situation is very similar to that for instance
3448 declarations.
3449 </Para>
3450 </ListItem>
3451
3452 </ItemizedList>
3453
3454 </Para>
3455
3456 </Sect2>
3457
3458 <Sect2>
3459 <Title>List fusion</Title>
3460
3461 <Para>
3462 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
3463 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
3464 intermediate list should be eliminated entirely.
3465 </Para>
3466
3467 <Para>
3468 The following are good producers:
3469
3470 <ItemizedList>
3471 <ListItem>
3472
3473 <Para>
3474  List comprehensions
3475 </Para>
3476 </ListItem>
3477 <ListItem>
3478
3479 <Para>
3480  Enumerations of <Literal>Int</Literal> and <Literal>Char</Literal> (e.g. <Literal>['a'..'z']</Literal>).
3481 </Para>
3482 </ListItem>
3483 <ListItem>
3484
3485 <Para>
3486  Explicit lists (e.g. <Literal>[True, False]</Literal>)
3487 </Para>
3488 </ListItem>
3489 <ListItem>
3490
3491 <Para>
3492  The cons constructor (e.g <Literal>3:4:[]</Literal>)
3493 </Para>
3494 </ListItem>
3495 <ListItem>
3496
3497 <Para>
3498  <Literal>++</Literal>
3499 </Para>
3500 </ListItem>
3501 <ListItem>
3502
3503 <Para>
3504  <Literal>map</Literal>
3505 </Para>
3506 </ListItem>
3507 <ListItem>
3508
3509 <Para>
3510  <Literal>filter</Literal>
3511 </Para>
3512 </ListItem>
3513 <ListItem>
3514
3515 <Para>
3516  <Literal>iterate</Literal>, <Literal>repeat</Literal>
3517 </Para>
3518 </ListItem>
3519 <ListItem>
3520
3521 <Para>
3522  <Literal>zip</Literal>, <Literal>zipWith</Literal>
3523 </Para>
3524 </ListItem>
3525
3526 </ItemizedList>
3527
3528 </Para>
3529
3530 <Para>
3531 The following are good consumers:
3532
3533 <ItemizedList>
3534 <ListItem>
3535
3536 <Para>
3537  List comprehensions
3538 </Para>
3539 </ListItem>
3540 <ListItem>
3541
3542 <Para>
3543  <Literal>array</Literal> (on its second argument)
3544 </Para>
3545 </ListItem>
3546 <ListItem>
3547
3548 <Para>
3549  <Literal>length</Literal>
3550 </Para>
3551 </ListItem>
3552 <ListItem>
3553
3554 <Para>
3555  <Literal>++</Literal> (on its first argument)
3556 </Para>
3557 </ListItem>
3558 <ListItem>
3559
3560 <Para>
3561  <Literal>map</Literal>
3562 </Para>
3563 </ListItem>
3564 <ListItem>
3565
3566 <Para>
3567  <Literal>filter</Literal>
3568 </Para>
3569 </ListItem>
3570 <ListItem>
3571
3572 <Para>
3573  <Literal>concat</Literal>
3574 </Para>
3575 </ListItem>
3576 <ListItem>
3577
3578 <Para>
3579  <Literal>unzip</Literal>, <Literal>unzip2</Literal>, <Literal>unzip3</Literal>, <Literal>unzip4</Literal>
3580 </Para>
3581 </ListItem>
3582 <ListItem>
3583
3584 <Para>
3585  <Literal>zip</Literal>, <Literal>zipWith</Literal> (but on one argument only; if both are good producers, <Literal>zip</Literal>
3586 will fuse with one but not the other)
3587 </Para>
3588 </ListItem>
3589 <ListItem>
3590
3591 <Para>
3592  <Literal>partition</Literal>
3593 </Para>
3594 </ListItem>
3595 <ListItem>
3596
3597 <Para>
3598  <Literal>head</Literal>
3599 </Para>
3600 </ListItem>
3601 <ListItem>
3602
3603 <Para>
3604  <Literal>and</Literal>, <Literal>or</Literal>, <Literal>any</Literal>, <Literal>all</Literal>
3605 </Para>
3606 </ListItem>
3607 <ListItem>
3608
3609 <Para>
3610  <Literal>sequence&lowbar;</Literal>
3611 </Para>
3612 </ListItem>
3613 <ListItem>
3614
3615 <Para>
3616  <Literal>msum</Literal>
3617 </Para>
3618 </ListItem>
3619 <ListItem>
3620
3621 <Para>
3622  <Literal>sortBy</Literal>
3623 </Para>
3624 </ListItem>
3625
3626 </ItemizedList>
3627
3628 </Para>
3629
3630 <Para>
3631 So, for example, the following should generate no intermediate lists:
3632
3633 <ProgramListing>
3634         array (1,10) [(i,i*i) | i &#60;- map (+ 1) [0..9]]
3635 </ProgramListing>
3636
3637 </Para>
3638
3639 <Para>
3640 This list could readily be extended; if there are Prelude functions that you use
3641 a lot which are not included, please tell us.
3642 </Para>
3643
3644 <Para>
3645 If you want to write your own good consumers or producers, look at the
3646 Prelude definitions of the above functions to see how to do so.
3647 </Para>
3648
3649 </Sect2>
3650
3651 <Sect2 id="rule-spec">
3652 <Title>Specialisation
3653 </Title>
3654
3655 <Para>
3656 Rewrite rules can be used to get the same effect as a feature
3657 present in earlier version of GHC:
3658
3659 <ProgramListing>
3660   {-# SPECIALIZE fromIntegral :: Int8 -&#62; Int16 = int8ToInt16 #-}
3661 </ProgramListing>
3662
3663 This told GHC to use <Literal>int8ToInt16</Literal> instead of <Literal>fromIntegral</Literal> whenever
3664 the latter was called with type <Literal>Int8 -&gt; Int16</Literal>.  That is, rather than
3665 specialising the original definition of <Literal>fromIntegral</Literal> the programmer is
3666 promising that it is safe to use <Literal>int8ToInt16</Literal> instead.
3667 </Para>
3668
3669 <Para>
3670 This feature is no longer in GHC.  But rewrite rules let you do the
3671 same thing:
3672
3673 <ProgramListing>
3674   {-# RULES
3675     "fromIntegral/Int8/Int16" fromIntegral = int8ToInt16
3676   #-}
3677 </ProgramListing>
3678
3679 This slightly odd-looking rule instructs GHC to replace <Literal>fromIntegral</Literal>
3680 by <Literal>int8ToInt16</Literal> <Emphasis>whenever the types match</Emphasis>.  Speaking more operationally,
3681 GHC adds the type and dictionary applications to get the typed rule
3682
3683 <ProgramListing>
3684         forall (d1::Integral Int8) (d2::Num Int16) .
3685                 fromIntegral Int8 Int16 d1 d2 = int8ToInt16
3686 </ProgramListing>
3687
3688 What is more,
3689 this rule does not need to be in the same file as fromIntegral,
3690 unlike the <Literal>SPECIALISE</Literal> pragmas which currently do (so that they
3691 have an original definition available to specialise).
3692 </Para>
3693
3694 </Sect2>
3695
3696 <Sect2>
3697 <Title>Controlling what's going on</Title>
3698
3699 <Para>
3700
3701 <ItemizedList>
3702 <ListItem>
3703
3704 <Para>
3705  Use <Literal>-ddump-rules</Literal> to see what transformation rules GHC is using.
3706 </Para>
3707 </ListItem>
3708 <ListItem>
3709
3710 <Para>
3711  Use <Literal>-ddump-simpl-stats</Literal> to see what rules are being fired.
3712 If you add <Literal>-dppr-debug</Literal> you get a more detailed listing.
3713 </Para>
3714 </ListItem>
3715 <ListItem>
3716
3717 <Para>
3718  The defintion of (say) <Literal>build</Literal> in <Literal>PrelBase.lhs</Literal> looks llike this:
3719
3720 <ProgramListing>
3721         build   :: forall a. (forall b. (a -&#62; b -&#62; b) -&#62; b -&#62; b) -&#62; [a]
3722         {-# INLINE build #-}
3723         build g = g (:) []
3724 </ProgramListing>
3725
3726 Notice the <Literal>INLINE</Literal>!  That prevents <Literal>(:)</Literal> from being inlined when compiling
3727 <Literal>PrelBase</Literal>, so that an importing module will ``see'' the <Literal>(:)</Literal>, and can
3728 match it on the LHS of a rule.  <Literal>INLINE</Literal> prevents any inlining happening
3729 in the RHS of the <Literal>INLINE</Literal> thing.  I regret the delicacy of this.
3730
3731 </Para>
3732 </ListItem>
3733 <ListItem>
3734
3735 <Para>
3736  In <Literal>ghc/lib/std/PrelBase.lhs</Literal> look at the rules for <Literal>map</Literal> to
3737 see how to write rules that will do fusion and yet give an efficient
3738 program even if fusion doesn't happen.  More rules in <Literal>PrelList.lhs</Literal>.
3739 </Para>
3740 </ListItem>
3741
3742 </ItemizedList>
3743
3744 </Para>
3745
3746 </Sect2>
3747
3748 </Sect1>