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