[project @ 2000-01-10 14:52:21 by rrt]
[ghc-hetmet.git] / ghc / docs / users_guide / glasgow_exts.sgml
1 <Para>
2 <IndexTerm><Primary>language, GHC</Primary></IndexTerm>
3 <IndexTerm><Primary>extensions, GHC</Primary></IndexTerm>
4 As with all known Haskell systems, GHC implements some extensions to
5 the language.  To use them, you'll need to give a <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 ``stuck'' on
14 performance because of the implementation costs of Haskell's
15 ``high-level'' features&mdash;you can always code ``under'' them.  In an
16 extreme case, you can write all your time-critical code in C, and then
17 just glue it together with Haskell!
18 </Para>
19
20 <Para>
21 Executive summary of our extensions:
22 </Para>
23
24 <Para>
25 <VariableList>
26
27 <VarListEntry>
28 <Term>Unboxed types and primitive operations:</Term>
29 <ListItem>
30 <Para>
31 You can get right down to the raw machine types and operations;
32 included in this are ``primitive arrays'' (direct access to Big Wads
33 of Bytes).  Please see <XRef LinkEnd="glasgow-unboxed"> and following.
34 </Para>
35 </ListItem>
36 </VarListEntry>
37
38 <VarListEntry>
39 <Term>Multi-parameter type classes:</Term>
40 <ListItem>
41 <Para>
42 GHC's type system supports extended type classes with multiple
43 parameters.  Please see <XRef LinkEnd="multi-param-type-classes">.
44 </Para>
45 </ListItem>
46 </VarListEntry>
47
48 <VarListEntry>
49 <Term>Local universal quantification:</Term>
50 <ListItem>
51 <Para>
52 GHC's type system supports explicit universal quantification in
53 constructor fields and function arguments.  This is useful for things
54 like defining <Literal>runST</Literal> from the state-thread world.  See <XRef LinkEnd="universal-quantification">.
55 </Para>
56 </ListItem>
57 </VarListEntry>
58
59 <VarListEntry>
60 <Term>Extistentially quantification in data types:</Term>
61 <ListItem>
62 <Para>
63 Some or all of the type variables in a datatype declaration may be
64 <Emphasis>existentially quantified</Emphasis>.  More details in <XRef LinkEnd="existential-quantification">.
65 </Para>
66 </ListItem>
67 </VarListEntry>
68
69 <VarListEntry>
70 <Term>Scoped type variables:</Term>
71 <ListItem>
72 <Para>
73 Scoped type variables enable the programmer to supply type signatures
74 for some nested declarations, where this would not be legal in Haskell
75 98.  Details in <XRef LinkEnd="scoped-type-variables">.
76 </Para>
77 </ListItem>
78 </VarListEntry>
79
80 <VarListEntry>
81 <Term>Calling out to C:</Term>
82 <ListItem>
83 <Para>
84 Just what it sounds like.  We provide <Emphasis>lots</Emphasis> of rope that you
85 can dangle around your neck.  Please see <XRef LinkEnd="glasgow-ccalls">.
86 </Para>
87 </ListItem>
88 </VarListEntry>
89
90 <VarListEntry>
91 <Term>Pragmas</Term>
92 <ListItem>
93 <Para>
94 Pragmas are special instructions to the compiler placed in the source
95 file.  The pragmas GHC supports are described in <XRef LinkEnd="pragmas">.
96 </Para>
97 </ListItem>
98 </VarListEntry>
99
100 <VarListEntry>
101 <Term>Rewrite rules:</Term>
102 <ListItem>
103 <Para>
104 The programmer can specify rewrite rules as part of the source program
105 (in a pragma).  GHC applies these rewrite rules wherever it can.
106 Details in <XRef LinkEnd="rewrite-rules">.
107 </Para>
108 </ListItem>
109 </VarListEntry>
110 </VariableList>
111 </Para>
112
113 <Para>
114 Before you get too carried away working at the lowest level (e.g.,
115 sloshing <Literal>MutableByteArray&num;</Literal>s around your program), you may wish to
116 check if there are system libraries that provide a ``Haskellised
117 veneer'' over the features you want.  See <XRef LinkEnd="ghc-prelude">.
118 </Para>
119
120 <Sect1 id="glasgow-unboxed">
121 <Title>Unboxed types
122 </Title>
123
124 <Para>
125 <IndexTerm><Primary>Unboxed types (Glasgow extension)</Primary></IndexTerm>
126 </Para>
127
128 <Para>
129 These types correspond to the ``raw machine'' types you would use in
130 C: <Literal>Int&num;</Literal> (long int), <Literal>Double&num;</Literal> (double), <Literal>Addr&num;</Literal> (void *), etc.  The
131 <Emphasis>primitive operations</Emphasis> (PrimOps) on these types are what you
132 might expect; e.g., <Literal>(+&num;)</Literal> is addition on <Literal>Int&num;</Literal>s, and is the
133 machine-addition that we all know and love&mdash;usually one instruction.
134 </Para>
135
136 <Para>
137 There are some restrictions on the use of unboxed types, the main one
138 being that you can't pass an unboxed value to a polymorphic function
139 or store one in a polymorphic data type.  This rules out things like
140 <Literal>[Int&num;]</Literal> (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 ``standard'' counterpart&mdash;we saw a
153 threefold speedup on one example.
154 </Para>
155
156 <Para>
157 Please see <XRef LinkEnd="ghc-libs-ghc"> for the details of unboxed types and the
158 operations on them.
159 </Para>
160
161 </Sect1>
162
163 <Sect1 id="glasgow-ST-monad">
164 <Title>Primitive state-transformer monad
165 </Title>
166
167 <Para>
168 <IndexTerm><Primary>state transformers (Glasgow extensions)</Primary></IndexTerm>
169 <IndexTerm><Primary>ST monad (Glasgow extension)</Primary></IndexTerm>
170 </Para>
171
172 <Para>
173 This monad underlies our implementation of arrays, mutable and
174 immutable, and our implementation of I/O, including ``C calls''.
175 </Para>
176
177 <Para>
178 The <Literal>ST</Literal> library, which provides access to the <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 ``standard'' Haskell arrays); you
215 can only read from them.  Obviously, they do not need the care and
216 attention of the state-transformer monad.
217 </Para>
218 </ListItem>
219 </VarListEntry>
220 <VarListEntry>
221 <Term>Mutable:</Term>
222 <ListItem>
223 <Para>
224 Arrays that may be changed or ``mutated.''  All the operations on them
225 live within the state-transformer monad and the updates happen
226 <Emphasis>in-place</Emphasis>.
227 </Para>
228 </ListItem>
229 </VarListEntry>
230 <VarListEntry>
231 <Term>``Static'' (in C land):</Term>
232 <ListItem>
233 <Para>
234 A C routine may pass an <Literal>Addr&num;</Literal> pointer back into Haskell land.  There
235 are then primitive operations with which you may merrily grab values
236 over in C land, by indexing off the ``static'' pointer.
237 </Para>
238 </ListItem>
239 </VarListEntry>
240 <VarListEntry>
241 <Term>``Stable'' pointers:</Term>
242 <ListItem>
243 <Para>
244 If, for some reason, you wish to hand a Haskell pointer (i.e.,
245 <Emphasis>not</Emphasis> an unboxed value) to a C routine, you first make the
246 pointer ``stable,'' so that the garbage collector won't forget that it
247 exists.  That is, GHC provides a safe way to pass Haskell pointers to
248 C.
249 </Para>
250
251 <Para>
252 Please see <XRef LinkEnd="glasgow-stablePtrs"> for more details.
253 </Para>
254 </ListItem>
255 </VarListEntry>
256 <VarListEntry>
257 <Term>``Foreign objects'':</Term>
258 <ListItem>
259 <Para>
260 A ``foreign object'' is a safe way to pass an external object (a
261 C-allocated pointer, say) to Haskell and have Haskell do the Right
262 Thing when it no longer references the object.  So, for example, C
263 could pass a large bitmap over to Haskell and say ``please free this
264 memory when you're done with it.''
265 </Para>
266
267 <Para>
268 Please see <XRef LinkEnd="glasgow-foreignObjs"> for more details.
269 </Para>
270 </ListItem>
271 </VarListEntry>
272 </VariableList>
273 </Para>
274
275 <Para>
276 The libraries section gives more details on all these ``primitive
277 array'' types and the operations on them, <XRef LinkEnd="ghc-prelude">.  Some of these extensions
278 are also supported by Hugs, and the supporting libraries are described
279 in the <ULink
280 URL="libs.html"
281 >GHC/Hugs Extension Libraries</ULink
282 >
283 document.
284 </Para>
285
286 </Sect1>
287
288 <Sect1 id="glasgow-ccalls">
289 <Title>Calling&nbsp;C directly from Haskell
290 </Title>
291
292 <Para>
293 <IndexTerm><Primary>C calls (Glasgow extension)</Primary></IndexTerm>
294 <IndexTerm><Primary>&lowbar;ccall&lowbar; (Glasgow extension)</Primary></IndexTerm>
295 <IndexTerm><Primary>&lowbar;casm&lowbar; (Glasgow extension)</Primary></IndexTerm>
296 </Para>
297
298 <Para>
299 GOOD ADVICE: Because this stuff is not Entirely Stable as far as names
300 and things go, you would be well-advised to keep your C-callery
301 corraled in a few modules, rather than sprinkled all over your code.
302 It will then be quite easy to update later on.
303 </Para>
304
305 <Sect2 id="ccall-intro">
306 <Title><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 (``stdin''::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_ ``%r = getenv((char *) %0);'' name &#62;&#62;= \ litstring -&#62;
354     return (
355         if (litstring == nullAddr) then
356             Left ("Fail:oldGetEnv:"++name)
357         else
358             Right (unpackCString litstring)
359     )
360 </ProgramListing>
361
362 </Para>
363
364 <Para>
365 The first literal-literal argument to a <Function>&lowbar;casm&lowbar;</Function> is like a <Function>printf</Function>
366 format: <Literal>&percnt;r</Literal> is replaced with the ``result,'' <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 (``stdin''::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 ``stable pointers''
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 ``stable
605 pointer'' 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_ ``sincosd( %0, &amp;((double *)%1[0]), &amp;((double *)%1[1]) );'' 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 = (``stderr'' :: 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 ``gotchas'' 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; T1 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 </Sect1>
2082
2083 <Sect1 id="existential-quantification">
2084 <Title>Existentially quantified data constructors
2085 </Title>
2086
2087 <Para>
2088 The idea of using existential quantification in data type declarations
2089 was suggested by Laufer (I believe, thought doubtless someone will
2090 correct me), and implemented in Hope+. It's been in Lennart
2091 Augustsson's <Command>hbc</Command> Haskell compiler for several years, and
2092 proved very useful.  Here's the idea.  Consider the declaration:
2093 </Para>
2094
2095 <Para>
2096
2097 <ProgramListing>
2098   data Foo = forall a. MkFoo a (a -&#62; Bool)
2099            | Nil
2100 </ProgramListing>
2101
2102 </Para>
2103
2104 <Para>
2105 The data type <Literal>Foo</Literal> has two constructors with types:
2106 </Para>
2107
2108 <Para>
2109
2110 <ProgramListing>
2111   MkFoo :: forall a. a -&#62; (a -&#62; Bool) -&#62; Foo
2112   Nil   :: Foo
2113 </ProgramListing>
2114
2115 </Para>
2116
2117 <Para>
2118 Notice that the type variable <Literal>a</Literal> in the type of <Function>MkFoo</Function>
2119 does not appear in the data type itself, which is plain <Literal>Foo</Literal>.
2120 For example, the following expression is fine:
2121 </Para>
2122
2123 <Para>
2124
2125 <ProgramListing>
2126   [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
2127 </ProgramListing>
2128
2129 </Para>
2130
2131 <Para>
2132 Here, <Literal>(MkFoo 3 even)</Literal> packages an integer with a function
2133 <Function>even</Function> that maps an integer to <Literal>Bool</Literal>; and <Function>MkFoo 'c'
2134 isUpper</Function> packages a character with a compatible function.  These
2135 two things are each of type <Literal>Foo</Literal> and can be put in a list.
2136 </Para>
2137
2138 <Para>
2139 What can we do with a value of type <Literal>Foo</Literal>?.  In particular,
2140 what happens when we pattern-match on <Function>MkFoo</Function>?
2141 </Para>
2142
2143 <Para>
2144
2145 <ProgramListing>
2146   f (MkFoo val fn) = ???
2147 </ProgramListing>
2148
2149 </Para>
2150
2151 <Para>
2152 Since all we know about <Literal>val</Literal> and <Function>fn</Function> is that they
2153 are compatible, the only (useful) thing we can do with them is to
2154 apply <Function>fn</Function> to <Literal>val</Literal> to get a boolean.  For example:
2155 </Para>
2156
2157 <Para>
2158
2159 <ProgramListing>
2160   f :: Foo -&#62; Bool
2161   f (MkFoo val fn) = fn val
2162 </ProgramListing>
2163
2164 </Para>
2165
2166 <Para>
2167 What this allows us to do is to package heterogenous values
2168 together with a bunch of functions that manipulate them, and then treat
2169 that collection of packages in a uniform manner.  You can express
2170 quite a bit of object-oriented-like programming this way.
2171 </Para>
2172
2173 <Sect2 id="existential">
2174 <Title>Why existential?
2175 </Title>
2176
2177 <Para>
2178 What has this to do with <Emphasis>existential</Emphasis> quantification?
2179 Simply that <Function>MkFoo</Function> has the (nearly) isomorphic type
2180 </Para>
2181
2182 <Para>
2183
2184 <ProgramListing>
2185   MkFoo :: (exists a . (a, a -&#62; Bool)) -&#62; Foo
2186 </ProgramListing>
2187
2188 </Para>
2189
2190 <Para>
2191 But Haskell programmers can safely think of the ordinary
2192 <Emphasis>universally</Emphasis> quantified type given above, thereby avoiding
2193 adding a new existential quantification construct.
2194 </Para>
2195
2196 </Sect2>
2197
2198 <Sect2>
2199 <Title>Type classes</Title>
2200
2201 <Para>
2202 An easy extension (implemented in <Command>hbc</Command>) is to allow
2203 arbitrary contexts before the constructor.  For example:
2204 </Para>
2205
2206 <Para>
2207
2208 <ProgramListing>
2209 data Baz = forall a. Eq a =&#62; Baz1 a a
2210          | forall b. Show b =&#62; Baz2 b (b -&#62; b)
2211 </ProgramListing>
2212
2213 </Para>
2214
2215 <Para>
2216 The two constructors have the types you'd expect:
2217 </Para>
2218
2219 <Para>
2220
2221 <ProgramListing>
2222 Baz1 :: forall a. Eq a =&#62; a -&#62; a -&#62; Baz
2223 Baz2 :: forall b. Show b =&#62; b -&#62; (b -&#62; b) -&#62; Baz
2224 </ProgramListing>
2225
2226 </Para>
2227
2228 <Para>
2229 But when pattern matching on <Function>Baz1</Function> the matched values can be compared
2230 for equality, and when pattern matching on <Function>Baz2</Function> the first matched
2231 value can be converted to a string (as well as applying the function to it).
2232 So this program is legal:
2233 </Para>
2234
2235 <Para>
2236
2237 <ProgramListing>
2238   f :: Baz -&#62; String
2239   f (Baz1 p q) | p == q    = "Yes"
2240                | otherwise = "No"
2241   f (Baz1 v fn)            = show (fn v)
2242 </ProgramListing>
2243
2244 </Para>
2245
2246 <Para>
2247 Operationally, in a dictionary-passing implementation, the
2248 constructors <Function>Baz1</Function> and <Function>Baz2</Function> must store the
2249 dictionaries for <Literal>Eq</Literal> and <Literal>Show</Literal> respectively, and
2250 extract it on pattern matching.
2251 </Para>
2252
2253 <Para>
2254 Notice the way that the syntax fits smoothly with that used for
2255 universal quantification earlier.
2256 </Para>
2257
2258 </Sect2>
2259
2260 <Sect2>
2261 <Title>Restrictions</Title>
2262
2263 <Para>
2264 There are several restrictions on the ways in which existentially-quantified
2265 constructors can be use.
2266 </Para>
2267
2268 <Para>
2269
2270 <ItemizedList>
2271 <ListItem>
2272
2273 <Para>
2274  When pattern matching, each pattern match introduces a new,
2275 distinct, type for each existential type variable.  These types cannot
2276 be unified with any other type, nor can they escape from the scope of
2277 the pattern match.  For example, these fragments are incorrect:
2278
2279
2280 <ProgramListing>
2281 f1 (MkFoo a f) = a
2282 </ProgramListing>
2283
2284
2285 Here, the type bound by <Function>MkFoo</Function> "escapes", because <Literal>a</Literal>
2286 is the result of <Function>f1</Function>.  One way to see why this is wrong is to
2287 ask what type <Function>f1</Function> has:
2288
2289
2290 <ProgramListing>
2291   f1 :: Foo -&#62; a             -- Weird!
2292 </ProgramListing>
2293
2294
2295 What is this "<Literal>a</Literal>" in the result type? Clearly we don't mean
2296 this:
2297
2298
2299 <ProgramListing>
2300   f1 :: forall a. Foo -&#62; a   -- Wrong!
2301 </ProgramListing>
2302
2303
2304 The original program is just plain wrong.  Here's another sort of error
2305
2306
2307 <ProgramListing>
2308   f2 (Baz1 a b) (Baz1 p q) = a==q
2309 </ProgramListing>
2310
2311
2312 It's ok to say <Literal>a==b</Literal> or <Literal>p==q</Literal>, but
2313 <Literal>a==q</Literal> is wrong because it equates the two distinct types arising
2314 from the two <Function>Baz1</Function> constructors.
2315
2316
2317 </Para>
2318 </ListItem>
2319 <ListItem>
2320
2321 <Para>
2322 You can't pattern-match on an existentially quantified
2323 constructor in a <Literal>let</Literal> or <Literal>where</Literal> group of
2324 bindings. So this is illegal:
2325
2326
2327 <ProgramListing>
2328   f3 x = a==b where { Baz1 a b = x }
2329 </ProgramListing>
2330
2331
2332 You can only pattern-match
2333 on an existentially-quantified constructor in a <Literal>case</Literal> expression or
2334 in the patterns of a function definition.
2335
2336 The reason for this restriction is really an implementation one.
2337 Type-checking binding groups is already a nightmare without
2338 existentials complicating the picture.  Also an existential pattern
2339 binding at the top level of a module doesn't make sense, because it's
2340 not clear how to prevent the existentially-quantified type "escaping".
2341 So for now, there's a simple-to-state restriction.  We'll see how
2342 annoying it is.
2343
2344 </Para>
2345 </ListItem>
2346 <ListItem>
2347
2348 <Para>
2349 You can't use existential quantification for <Literal>newtype</Literal>
2350 declarations.  So this is illegal:
2351
2352
2353 <ProgramListing>
2354   newtype T = forall a. Ord a =&#62; MkT a
2355 </ProgramListing>
2356
2357
2358 Reason: a value of type <Literal>T</Literal> must be represented as a pair
2359 of a dictionary for <Literal>Ord t</Literal> and a value of type <Literal>t</Literal>.
2360 That contradicts the idea that <Literal>newtype</Literal> should have no
2361 concrete representation.  You can get just the same efficiency and effect
2362 by using <Literal>data</Literal> instead of <Literal>newtype</Literal>.  If there is no
2363 overloading involved, then there is more of a case for allowing
2364 an existentially-quantified <Literal>newtype</Literal>, because the <Literal>data</Literal>
2365 because the <Literal>data</Literal> version does carry an implementation cost,
2366 but single-field existentially quantified constructors aren't much
2367 use.  So the simple restriction (no existential stuff on <Literal>newtype</Literal>)
2368 stands, unless there are convincing reasons to change it.
2369
2370
2371 </Para>
2372 </ListItem>
2373 <ListItem>
2374
2375 <Para>
2376  You can't use <Literal>deriving</Literal> to define instances of a
2377 data type with existentially quantified data constructors.
2378
2379 Reason: in most cases it would not make sense. For example:&num;
2380
2381 <ProgramListing>
2382 data T = forall a. MkT [a] deriving( Eq )
2383 </ProgramListing>
2384
2385 To derive <Literal>Eq</Literal> in the standard way we would need to have equality
2386 between the single component of two <Function>MkT</Function> constructors:
2387
2388 <ProgramListing>
2389 instance Eq T where
2390   (MkT a) == (MkT b) = ???
2391 </ProgramListing>
2392
2393 But <VarName>a</VarName> and <VarName>b</VarName> have distinct types, and so can't be compared.
2394 It's just about possible to imagine examples in which the derived instance
2395 would make sense, but it seems altogether simpler simply to prohibit such
2396 declarations.  Define your own instances!
2397 </Para>
2398 </ListItem>
2399
2400 </ItemizedList>
2401
2402 </Para>
2403
2404 </Sect2>
2405
2406 </Sect1>
2407
2408 <Sect1 id="sec-assertions">
2409 <Title>Assertions
2410 <IndexTerm><Primary>Assertions</Primary></IndexTerm>
2411 </Title>
2412
2413 <Para>
2414 If you want to make use of assertions in your standard Haskell code, you
2415 could define a function like the following:
2416 </Para>
2417
2418 <Para>
2419
2420 <ProgramListing>
2421 assert :: Bool -&#62; a -&#62; a
2422 assert False x = error "assertion failed!"
2423 assert _     x = x
2424 </ProgramListing>
2425
2426 </Para>
2427
2428 <Para>
2429 which works, but gives you back a less than useful error message --
2430 an assertion failed, but which and where?
2431 </Para>
2432
2433 <Para>
2434 One way out is to define an extended <Function>assert</Function> function which also
2435 takes a descriptive string to include in the error message and
2436 perhaps combine this with the use of a pre-processor which inserts
2437 the source location where <Function>assert</Function> was used.
2438 </Para>
2439
2440 <Para>
2441 Ghc offers a helping hand here, doing all of this for you. For every
2442 use of <Function>assert</Function> in the user's source:
2443 </Para>
2444
2445 <Para>
2446
2447 <ProgramListing>
2448 kelvinToC :: Double -&#62; Double
2449 kelvinToC k = assert (k &amp;gt;= 0.0) (k+273.15)
2450 </ProgramListing>
2451
2452 </Para>
2453
2454 <Para>
2455 Ghc will rewrite this to also include the source location where the
2456 assertion was made,
2457 </Para>
2458
2459 <Para>
2460
2461 <ProgramListing>
2462 assert pred val ==&#62; assertError "Main.hs|15" pred val
2463 </ProgramListing>
2464
2465 </Para>
2466
2467 <Para>
2468 The rewrite is only performed by the compiler when it spots
2469 applications of <Function>Exception.assert</Function>, so you can still define and
2470 use your own versions of <Function>assert</Function>, should you so wish. If not,
2471 import <Literal>Exception</Literal> to make use <Function>assert</Function> in your code.
2472 </Para>
2473
2474 <Para>
2475 To have the compiler ignore uses of assert, use the compiler option
2476 <Option>-fignore-asserts</Option>. <IndexTerm><Primary>-fignore-asserts option</Primary></IndexTerm> That is,
2477 expressions of the form <Literal>assert pred e</Literal> will be rewritten to <Literal>e</Literal>.
2478 </Para>
2479
2480 <Para>
2481 Assertion failures can be caught, see the documentation for the
2482 Hugs/GHC Exception library for information of how.
2483 </Para>
2484
2485 </Sect1>
2486
2487 <Sect1 id="scoped-type-variables">
2488 <Title>Scoped Type Variables
2489 </Title>
2490
2491 <Para>
2492 A <Emphasis>pattern type signature</Emphasis> can introduce a <Emphasis>scoped type
2493 variable</Emphasis>.  For example
2494 </Para>
2495
2496 <Para>
2497
2498 <ProgramListing>
2499 f (xs::[a]) = ys ++ ys
2500            where
2501               ys :: [a]
2502               ys = reverse xs
2503 </ProgramListing>
2504
2505 </Para>
2506
2507 <Para>
2508 The pattern <Literal>(xs::[a])</Literal> includes a type signature for <VarName>xs</VarName>.
2509 This brings the type variable <Literal>a</Literal> into scope; it scopes over
2510 all the patterns and right hand sides for this equation for <Function>f</Function>.
2511 In particular, it is in scope at the type signature for <VarName>y</VarName>.
2512 </Para>
2513
2514 <Para>
2515 At ordinary type signatures, such as that for <VarName>ys</VarName>, any type variables
2516 mentioned in the type signature <Emphasis>that are not in scope</Emphasis> are
2517 implicitly universally quantified.  (If there are no type variables in
2518 scope, all type variables mentioned in the signature are universally
2519 quantified, which is just as in Haskell 98.)  In this case, since <VarName>a</VarName>
2520 is in scope, it is not universally quantified, so the type of <VarName>ys</VarName> is
2521 the same as that of <VarName>xs</VarName>.  In Haskell 98 it is not possible to declare
2522 a type for <VarName>ys</VarName>; a major benefit of scoped type variables is that
2523 it becomes possible to do so.
2524 </Para>
2525
2526 <Para>
2527 Scoped type variables are implemented in both GHC and Hugs.  Where the
2528 implementations differ from the specification below, those differences
2529 are noted.
2530 </Para>
2531
2532 <Para>
2533 So much for the basic idea.  Here are the details.
2534 </Para>
2535
2536 <Sect2>
2537 <Title>Scope and implicit quantification</Title>
2538
2539 <Para>
2540
2541 <ItemizedList>
2542 <ListItem>
2543
2544 <Para>
2545  All the type variables mentioned in the patterns for a single
2546 function definition equation, that are not already in scope,
2547 are brought into scope by the patterns.  We describe this set as
2548 the <Emphasis>type variables bound by the equation</Emphasis>.
2549
2550 </Para>
2551 </ListItem>
2552 <ListItem>
2553
2554 <Para>
2555  The type variables thus brought into scope may be mentioned
2556 in ordinary type signatures or pattern type signatures anywhere within
2557 their scope.
2558
2559 </Para>
2560 </ListItem>
2561 <ListItem>
2562
2563 <Para>
2564  In ordinary type signatures, any type variable mentioned in the
2565 signature that is in scope is <Emphasis>not</Emphasis> universally quantified.
2566
2567 </Para>
2568 </ListItem>
2569 <ListItem>
2570
2571 <Para>
2572  Ordinary type signatures do not bring any new type variables
2573 into scope (except in the type signature itself!). So this is illegal:
2574
2575
2576 <ProgramListing>
2577   f :: a -&#62; a
2578   f x = x::a
2579 </ProgramListing>
2580
2581
2582 It's illegal because <VarName>a</VarName> is not in scope in the body of <Function>f</Function>,
2583 so the ordinary signature <Literal>x::a</Literal> is equivalent to <Literal>x::forall a.a</Literal>;
2584 and that is an incorrect typing.
2585
2586 </Para>
2587 </ListItem>
2588 <ListItem>
2589
2590 <Para>
2591  There is no implicit universal quantification on pattern type
2592 signatures, nor may one write an explicit <Literal>forall</Literal> type in a pattern
2593 type signature.  The pattern type signature is a monotype.
2594
2595 </Para>
2596 </ListItem>
2597 <ListItem>
2598
2599 <Para>
2600
2601 The type variables in the head of a <Literal>class</Literal> or <Literal>instance</Literal> declaration
2602 scope over the methods defined in the <Literal>where</Literal> part.  For example:
2603
2604
2605 <ProgramListing>
2606   class C a where
2607     op :: [a] -&#62; a
2608
2609     op xs = let ys::[a]
2610                 ys = reverse xs
2611             in
2612             head ys
2613 </ProgramListing>
2614
2615
2616 (Not implemented in Hugs yet, Dec 98).
2617 </Para>
2618 </ListItem>
2619
2620 </ItemizedList>
2621
2622 </Para>
2623
2624 </Sect2>
2625
2626 <Sect2>
2627 <Title>Polymorphism</Title>
2628
2629 <Para>
2630
2631 <ItemizedList>
2632 <ListItem>
2633
2634 <Para>
2635  Pattern type signatures are completely orthogonal to ordinary, separate
2636 type signatures.  The two can be used independently or together.  There is
2637 no scoping associated with the names of the type variables in a separate type signature.
2638
2639
2640 <ProgramListing>
2641    f :: [a] -&#62; [a]
2642    f (xs::[b]) = reverse xs
2643 </ProgramListing>
2644
2645
2646 </Para>
2647 </ListItem>
2648 <ListItem>
2649
2650 <Para>
2651  The function must be polymorphic in the type variables
2652 bound by all its equations.  Operationally, the type variables bound
2653 by one equation must not:
2654
2655
2656 <ItemizedList>
2657 <ListItem>
2658
2659 <Para>
2660  Be unified with a type (such as <Literal>Int</Literal>, or <Literal>[a]</Literal>).
2661 </Para>
2662 </ListItem>
2663 <ListItem>
2664
2665 <Para>
2666  Be unified with a type variable free in the environment.
2667 </Para>
2668 </ListItem>
2669 <ListItem>
2670
2671 <Para>
2672  Be unified with each other.  (They may unify with the type variables
2673 bound by another equation for the same function, of course.)
2674 </Para>
2675 </ListItem>
2676
2677 </ItemizedList>
2678
2679
2680 For example, the following all fail to type check:
2681
2682
2683 <ProgramListing>
2684   f (x::a) (y::b) = [x,y]       -- a unifies with b
2685
2686   g (x::a) = x + 1::Int         -- a unifies with Int
2687
2688   h x = let k (y::a) = [x,y]    -- a is free in the
2689         in k x                  -- environment
2690
2691   k (x::a) True    = ...        -- a unifies with Int
2692   k (x::Int) False = ...
2693
2694   w :: [b] -&#62; [b]
2695   w (x::a) = x                  -- a unifies with [b]
2696 </ProgramListing>
2697
2698
2699 </Para>
2700 </ListItem>
2701 <ListItem>
2702
2703 <Para>
2704  The pattern-bound type variable may, however, be constrained
2705 by the context of the principal type, thus:
2706
2707
2708 <ProgramListing>
2709   f (x::a) (y::a) = x+y*2
2710 </ProgramListing>
2711
2712
2713 gets the inferred type: <Literal>forall a. Num a =&gt; a -&gt; a -&gt; a</Literal>.
2714 </Para>
2715 </ListItem>
2716
2717 </ItemizedList>
2718
2719 </Para>
2720
2721 </Sect2>
2722
2723 <Sect2>
2724 <Title>Result type signatures</Title>
2725
2726 <Para>
2727
2728 <ItemizedList>
2729 <ListItem>
2730
2731 <Para>
2732  The result type of a function can be given a signature,
2733 thus:
2734
2735
2736 <ProgramListing>
2737   f (x::a) :: [a] = [x,x,x]
2738 </ProgramListing>
2739
2740
2741 The final <Literal>:: [a]</Literal> after all the patterns gives a signature to the
2742 result type.  Sometimes this is the only way of naming the type variable
2743 you want:
2744
2745
2746 <ProgramListing>
2747   f :: Int -&#62; [a] -&#62; [a]
2748   f n :: ([a] -&#62; [a]) = let g (x::a, y::a) = (y,x)
2749                         in \xs -&#62; map g (reverse xs `zip` xs)
2750 </ProgramListing>
2751
2752
2753 </Para>
2754 </ListItem>
2755
2756 </ItemizedList>
2757
2758 </Para>
2759
2760 <Para>
2761 Result type signatures are not yet implemented in Hugs.
2762 </Para>
2763
2764 </Sect2>
2765
2766 <Sect2>
2767 <Title>Pattern signatures on other constructs</Title>
2768
2769 <Para>
2770
2771 <ItemizedList>
2772 <ListItem>
2773
2774 <Para>
2775  A pattern type signature can be on an arbitrary sub-pattern, not
2776 just on a variable:
2777
2778
2779 <ProgramListing>
2780   f ((x,y)::(a,b)) = (y,x) :: (b,a)
2781 </ProgramListing>
2782
2783
2784 </Para>
2785 </ListItem>
2786 <ListItem>
2787
2788 <Para>
2789  Pattern type signatures, including the result part, can be used
2790 in lambda abstractions:
2791
2792
2793 <ProgramListing>
2794   (\ (x::a, y) :: a -&#62; x)
2795 </ProgramListing>
2796
2797
2798 Type variables bound by these patterns must be polymorphic in
2799 the sense defined above.
2800 For example:
2801
2802
2803 <ProgramListing>
2804   f1 (x::c) = f1 x      -- ok
2805   f2 = \(x::c) -&#62; f2 x  -- not ok
2806 </ProgramListing>
2807
2808
2809 Here, <Function>f1</Function> is OK, but <Function>f2</Function> is not, because <VarName>c</VarName> gets unified
2810 with a type variable free in the environment, in this
2811 case, the type of <Function>f2</Function>, which is in the environment when
2812 the lambda abstraction is checked.
2813
2814 </Para>
2815 </ListItem>
2816 <ListItem>
2817
2818 <Para>
2819  Pattern type signatures, including the result part, can be used
2820 in <Literal>case</Literal> expressions:
2821
2822
2823 <ProgramListing>
2824   case e of { (x::a, y) :: a -&#62; x }
2825 </ProgramListing>
2826
2827
2828 The pattern-bound type variables must, as usual,
2829 be polymorphic in the following sense: each case alternative,
2830 considered as a lambda abstraction, must be polymorphic.
2831 Thus this is OK:
2832
2833
2834 <ProgramListing>
2835   case (True,False) of { (x::a, y) -&#62; x }
2836 </ProgramListing>
2837
2838
2839 Even though the context is that of a pair of booleans,
2840 the alternative itself is polymorphic.  Of course, it is
2841 also OK to say:
2842
2843
2844 <ProgramListing>
2845   case (True,False) of { (x::Bool, y) -&#62; x }
2846 </ProgramListing>
2847
2848
2849 </Para>
2850 </ListItem>
2851 <ListItem>
2852
2853 <Para>
2854 To avoid ambiguity, the type after the ``<Literal>::</Literal>'' in a result
2855 pattern signature on a lambda or <Literal>case</Literal> must be atomic (i.e. a single
2856 token or a parenthesised type of some sort).  To see why,
2857 consider how one would parse this:
2858
2859
2860 <ProgramListing>
2861   \ x :: a -&#62; b -&#62; x
2862 </ProgramListing>
2863
2864
2865 </Para>
2866 </ListItem>
2867 <ListItem>
2868
2869 <Para>
2870  Pattern type signatures that bind new type variables
2871 may not be used in pattern bindings at all.
2872 So this is illegal:
2873
2874
2875 <ProgramListing>
2876   f x = let (y, z::a) = x in ...
2877 </ProgramListing>
2878
2879
2880 But these are OK, because they do not bind fresh type variables:
2881
2882
2883 <ProgramListing>
2884   f1 x            = let (y, z::Int) = x in ...
2885   f2 (x::(Int,a)) = let (y, z::a)   = x in ...
2886 </ProgramListing>
2887
2888
2889 However a single variable is considered a degenerate function binding,
2890 rather than a degerate pattern binding, so this is permitted, even
2891 though it binds a type variable:
2892
2893
2894 <ProgramListing>
2895   f :: (b-&#62;b) = \(x::b) -&#62; x
2896 </ProgramListing>
2897
2898
2899 </Para>
2900 </ListItem>
2901
2902 </ItemizedList>
2903
2904 Such degnerate function bindings do not fall under the monomorphism
2905 restriction.  Thus:
2906 </Para>
2907
2908 <Para>
2909
2910 <ProgramListing>
2911   g :: a -&#62; a -&#62; Bool = \x y. x==y
2912 </ProgramListing>
2913
2914 </Para>
2915
2916 <Para>
2917 Here <Function>g</Function> has type <Literal>forall a. Eq a =&gt; a -&gt; a -&gt; Bool</Literal>, just as if
2918 <Function>g</Function> had a separate type signature.  Lacking a type signature, <Function>g</Function>
2919 would get a monomorphic type.
2920 </Para>
2921
2922 </Sect2>
2923
2924 <Sect2>
2925 <Title>Existentials</Title>
2926
2927 <Para>
2928
2929 <ItemizedList>
2930 <ListItem>
2931
2932 <Para>
2933  Pattern type signatures can bind existential type variables.
2934 For example:
2935
2936
2937 <ProgramListing>
2938   data T = forall a. MkT [a]
2939
2940   f :: T -&#62; T
2941   f (MkT [t::a]) = MkT t3
2942                  where
2943                    t3::[a] = [t,t,t]
2944 </ProgramListing>
2945
2946
2947 </Para>
2948 </ListItem>
2949
2950 </ItemizedList>
2951
2952 </Para>
2953
2954 </Sect2>
2955
2956 </Sect1>
2957
2958 <Sect1 id="pragmas">
2959 <Title>Pragmas
2960 </Title>
2961
2962 <Para>
2963 GHC supports several pragmas, or instructions to the compiler placed
2964 in the source code.  Pragmas don't affect the meaning of the program,
2965 but they might affect the efficiency of the generated code.
2966 </Para>
2967
2968 <Sect2 id="inline-pragma">
2969 <Title>INLINE pragma
2970
2971 <IndexTerm><Primary>INLINE pragma</Primary></IndexTerm>
2972 <IndexTerm><Primary>pragma, INLINE</Primary></IndexTerm></Title>
2973
2974 <Para>
2975 GHC (with <Option>-O</Option>, as always) tries to inline (or ``unfold'')
2976 functions/values that are ``small enough,'' thus avoiding the call
2977 overhead and possibly exposing other more-wonderful optimisations.
2978 </Para>
2979
2980 <Para>
2981 You will probably see these unfoldings (in Core syntax) in your
2982 interface files.
2983 </Para>
2984
2985 <Para>
2986 Normally, if GHC decides a function is ``too expensive'' to inline, it
2987 will not do so, nor will it export that unfolding for other modules to
2988 use.
2989 </Para>
2990
2991 <Para>
2992 The sledgehammer you can bring to bear is the
2993 <Literal>INLINE</Literal><IndexTerm><Primary>INLINE pragma</Primary></IndexTerm> pragma, used thusly:
2994
2995 <ProgramListing>
2996 key_function :: Int -&#62; String -&#62; (Bool, Double)
2997
2998 #ifdef __GLASGOW_HASKELL__
2999 {-# INLINE key_function #-}
3000 #endif
3001 </ProgramListing>
3002
3003 (You don't need to do the C pre-processor carry-on unless you're going
3004 to stick the code through HBC&mdash;it doesn't like <Literal>INLINE</Literal> pragmas.)
3005 </Para>
3006
3007 <Para>
3008 The major effect of an <Literal>INLINE</Literal> pragma is to declare a function's
3009 ``cost'' to be very low.  The normal unfolding machinery will then be
3010 very keen to inline it.
3011 </Para>
3012
3013 <Para>
3014 An <Literal>INLINE</Literal> pragma for a function can be put anywhere its type
3015 signature could be put.
3016 </Para>
3017
3018 <Para>
3019 <Literal>INLINE</Literal> pragmas are a particularly good idea for the
3020 <Literal>then</Literal>/<Literal>return</Literal> (or <Literal>bind</Literal>/<Literal>unit</Literal>) functions in a monad.
3021 For example, in GHC's own <Literal>UniqueSupply</Literal> monad code, we have:
3022
3023 <ProgramListing>
3024 #ifdef __GLASGOW_HASKELL__
3025 {-# INLINE thenUs #-}
3026 {-# INLINE returnUs #-}
3027 #endif
3028 </ProgramListing>
3029
3030 </Para>
3031
3032 </Sect2>
3033
3034 <Sect2 id="noinline-pragma">
3035 <Title>NOINLINE pragma
3036 </Title>
3037
3038 <Para>
3039 <IndexTerm><Primary>NOINLINE pragma</Primary></IndexTerm>
3040 <IndexTerm><Primary>pragma, NOINLINE</Primary></IndexTerm>
3041 </Para>
3042
3043 <Para>
3044 The <Literal>NOINLINE</Literal> pragma does exactly what you'd expect: it stops the
3045 named function from being inlined by the compiler.  You shouldn't ever
3046 need to do this, unless you're very cautious about code size.
3047 </Para>
3048
3049 </Sect2>
3050
3051 <Sect2 id="specialize-pragma">
3052 <Title>SPECIALIZE pragma
3053 </Title>
3054
3055 <Para>
3056 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3057 <IndexTerm><Primary>pragma, SPECIALIZE</Primary></IndexTerm>
3058 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3059 </Para>
3060
3061 <Para>
3062 (UK spelling also accepted.)  For key overloaded functions, you can
3063 create extra versions (NB: more code space) specialised to particular
3064 types.  Thus, if you have an overloaded function:
3065 </Para>
3066
3067 <Para>
3068
3069 <ProgramListing>
3070 hammeredLookup :: Ord key =&#62; [(key, value)] -&#62; key -&#62; value
3071 </ProgramListing>
3072
3073 </Para>
3074
3075 <Para>
3076 If it is heavily used on lists with <Literal>Widget</Literal> keys, you could
3077 specialise it as follows:
3078
3079 <ProgramListing>
3080 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -&#62; Widget -&#62; value #-}
3081 </ProgramListing>
3082
3083 </Para>
3084
3085 <Para>
3086 To get very fancy, you can also specify a named function to use for
3087 the specialised value, by adding <Literal>= blah</Literal>, as in:
3088
3089 <ProgramListing>
3090 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
3091 </ProgramListing>
3092
3093 It's <Emphasis>Your Responsibility</Emphasis> to make sure that <Function>blah</Function> really
3094 behaves as a specialised version of <Function>hammeredLookup</Function>!!!
3095 </Para>
3096
3097 <Para>
3098 NOTE: the <Literal>=blah</Literal> feature isn't implemented in GHC 4.xx.
3099 </Para>
3100
3101 <Para>
3102 An example in which the <Literal>= blah</Literal> form will Win Big:
3103
3104 <ProgramListing>
3105 toDouble :: Real a =&#62; a -&#62; Double
3106 toDouble = fromRational . toRational
3107
3108 {-# SPECIALIZE toDouble :: Int -&#62; Double = i2d #-}
3109 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
3110 </ProgramListing>
3111
3112 The <Function>i2d</Function> function is virtually one machine instruction; the
3113 default conversion&mdash;via an intermediate <Literal>Rational</Literal>&mdash;is obscenely
3114 expensive by comparison.
3115 </Para>
3116
3117 <Para>
3118 By using the US spelling, your <Literal>SPECIALIZE</Literal> pragma will work with
3119 HBC, too.  Note that HBC doesn't support the <Literal>= blah</Literal> form.
3120 </Para>
3121
3122 <Para>
3123 A <Literal>SPECIALIZE</Literal> pragma for a function can be put anywhere its type
3124 signature could be put.
3125 </Para>
3126
3127 </Sect2>
3128
3129 <Sect2 id="specialize-instance-pragma">
3130 <Title>SPECIALIZE instance pragma
3131 </Title>
3132
3133 <Para>
3134 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
3135 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
3136 Same idea, except for instance declarations.  For example:
3137
3138 <ProgramListing>
3139 instance (Eq a) =&#62; Eq (Foo a) where { ... usual stuff ... }
3140
3141 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
3142 </ProgramListing>
3143
3144 Compatible with HBC, by the way.
3145 </Para>
3146
3147 </Sect2>
3148
3149 <Sect2 id="line-pragma">
3150 <Title>LINE pragma
3151 </Title>
3152
3153 <Para>
3154 <IndexTerm><Primary>LINE pragma</Primary></IndexTerm>
3155 <IndexTerm><Primary>pragma, LINE</Primary></IndexTerm>
3156 </Para>
3157
3158 <Para>
3159 This pragma is similar to C's <Literal>&num;line</Literal> pragma, and is mainly for use in
3160 automatically generated Haskell code.  It lets you specify the line
3161 number and filename of the original code; for example
3162 </Para>
3163
3164 <Para>
3165
3166 <ProgramListing>
3167 {-# LINE 42 "Foo.vhs" #-}
3168 </ProgramListing>
3169
3170 </Para>
3171
3172 <Para>
3173 if you'd generated the current file from something called <Filename>Foo.vhs</Filename>
3174 and this line corresponds to line 42 in the original.  GHC will adjust
3175 its error messages to refer to the line/file named in the <Literal>LINE</Literal>
3176 pragma.
3177 </Para>
3178
3179 </Sect2>
3180
3181 <Sect2>
3182 <Title>RULES pragma</Title>
3183
3184 <Para>
3185 The RULES pragma lets you specify rewrite rules.  It is described in
3186 <XRef LinkEnd="rewrite-rules">.
3187 </Para>
3188
3189 </Sect2>
3190
3191 </Sect1>
3192
3193 <Sect1 id="rewrite-rules">
3194 <Title>Rewrite rules
3195
3196 <IndexTerm><Primary>RULES pagma</Primary></IndexTerm>
3197 <IndexTerm><Primary>pragma, RULES</Primary></IndexTerm>
3198 <IndexTerm><Primary>rewrite rules</Primary></IndexTerm></Title>
3199
3200 <Para>
3201 The programmer can specify rewrite rules as part of the source program
3202 (in a pragma).  GHC applies these rewrite rules wherever it can.
3203 </Para>
3204
3205 <Para>
3206 Here is an example:
3207
3208 <ProgramListing>
3209   {-# RULES
3210         "map/map"       forall f g xs. map f (map g xs) = map (f.g) xs
3211   #-}
3212 </ProgramListing>
3213
3214 </Para>
3215
3216 <Sect2>
3217 <Title>Syntax</Title>
3218
3219 <Para>
3220 From a syntactic point of view:
3221
3222 <ItemizedList>
3223 <ListItem>
3224
3225 <Para>
3226  Each rule has a name, enclosed in double quotes.  The name itself has
3227 no significance at all.  It is only used when reporting how many times the rule fired.
3228 </Para>
3229 </ListItem>
3230 <ListItem>
3231
3232 <Para>
3233  There may be zero or more rules in a <Literal>RULES</Literal> pragma.
3234 </Para>
3235 </ListItem>
3236 <ListItem>
3237
3238 <Para>
3239  Layout applies in a <Literal>RULES</Literal> pragma.  Currently no new indentation level
3240 is set, so you must lay out your rules starting in the same column as the
3241 enclosing definitions.
3242 </Para>
3243 </ListItem>
3244 <ListItem>
3245
3246 <Para>
3247  Each variable mentioned in a rule must either be in scope (e.g. <Function>map</Function>),
3248 or bound by the <Literal>forall</Literal> (e.g. <Function>f</Function>, <Function>g</Function>, <Function>xs</Function>).  The variables bound by
3249 the <Literal>forall</Literal> are called the <Emphasis>pattern</Emphasis> variables.  They are separated
3250 by spaces, just like in a type <Literal>forall</Literal>.
3251 </Para>
3252 </ListItem>
3253 <ListItem>
3254
3255 <Para>
3256  A pattern variable may optionally have a type signature.
3257 If the type of the pattern variable is polymorphic, it <Emphasis>must</Emphasis> have a type signature.
3258 For example, here is the <Literal>foldr/build</Literal> rule:
3259
3260 <ProgramListing>
3261 "fold/build"  forall k z (g::forall b. (a-&#62;b-&#62;b) -&#62; b -&#62; b) .
3262               foldr k z (build g) = g k z
3263 </ProgramListing>
3264
3265 Since <Function>g</Function> has a polymorphic type, it must have a type signature.
3266
3267 </Para>
3268 </ListItem>
3269 <ListItem>
3270
3271 <Para>
3272 The left hand side of a rule must consist of a top-level variable applied
3273 to arbitrary expressions.  For example, this is <Emphasis>not</Emphasis> OK:
3274
3275 <ProgramListing>
3276 "wrong1"   forall e1 e2.  case True of { True -&#62; e1; False -&#62; e2 } = e1
3277 "wrong2"   forall f.      f True = True
3278 </ProgramListing>
3279
3280 In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong1"</Literal>, the LHS has a pattern variable
3281 in the head.
3282 </Para>
3283 </ListItem>
3284 <ListItem>
3285
3286 <Para>
3287  A rule does not need to be in the same module as (any of) the
3288 variables it mentions, though of course they need to be in scope.
3289 </Para>
3290 </ListItem>
3291 <ListItem>
3292
3293 <Para>
3294  Rules are automatically exported from a module, just as instance declarations are.
3295 </Para>
3296 </ListItem>
3297
3298 </ItemizedList>
3299
3300 </Para>
3301
3302 </Sect2>
3303
3304 <Sect2>
3305 <Title>Semantics</Title>
3306
3307 <Para>
3308 From a semantic point of view:
3309
3310 <ItemizedList>
3311 <ListItem>
3312
3313 <Para>
3314 Rules are only applied if you use the <Option>-O</Option> flag.
3315 </Para>
3316 </ListItem>
3317
3318 <ListItem>
3319 <Para>
3320  Rules are regarded as left-to-right rewrite rules.
3321 When GHC finds an expression that is a substitution instance of the LHS
3322 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
3323 By "a substitution instance" we mean that the LHS can be made equal to the
3324 expression by substituting for the pattern variables.
3325
3326 </Para>
3327 </ListItem>
3328 <ListItem>
3329
3330 <Para>
3331  The LHS and RHS of a rule are typechecked, and must have the
3332 same type.
3333
3334 </Para>
3335 </ListItem>
3336 <ListItem>
3337
3338 <Para>
3339  GHC makes absolutely no attempt to verify that the LHS and RHS
3340 of a rule have the same meaning.  That is undecideable in general, and
3341 infeasible in most interesting cases.  The responsibility is entirely the programmer's!
3342
3343 </Para>
3344 </ListItem>
3345 <ListItem>
3346
3347 <Para>
3348  GHC makes no attempt to make sure that the rules are confluent or
3349 terminating.  For example:
3350
3351 <ProgramListing>
3352   "loop"        forall x,y.  f x y = f y x
3353 </ProgramListing>
3354
3355 This rule will cause the compiler to go into an infinite loop.
3356
3357 </Para>
3358 </ListItem>
3359 <ListItem>
3360
3361 <Para>
3362  If more than one rule matches a call, GHC will choose one arbitrarily to apply.
3363
3364 </Para>
3365 </ListItem>
3366 <ListItem>
3367 <Para>
3368  GHC currently uses a very simple, syntactic, matching algorithm
3369 for matching a rule LHS with an expression.  It seeks a substitution
3370 which makes the LHS and expression syntactically equal modulo alpha
3371 conversion.  The pattern (rule), but not the expression, is eta-expanded if
3372 necessary.  (Eta-expanding the epression can lead to laziness bugs.)
3373 But not beta conversion (that's called higher-order matching).
3374 </Para>
3375
3376 <Para>
3377 Matching is carried out on GHC's intermediate language, which includes
3378 type abstractions and applications.  So a rule only matches if the
3379 types match too.  See <XRef LinkEnd="rule-spec"> below.
3380 </Para>
3381 </ListItem>
3382 <ListItem>
3383
3384 <Para>
3385  GHC keeps trying to apply the rules as it optimises the program.
3386 For example, consider:
3387
3388 <ProgramListing>
3389   let s = map f
3390       t = map g
3391   in
3392   s (t xs)
3393 </ProgramListing>
3394
3395 The expression <Literal>s (t xs)</Literal> does not match the rule <Literal>"map/map"</Literal>, but GHC
3396 will substitute for <VarName>s</VarName> and <VarName>t</VarName>, giving an expression which does match.
3397 If <VarName>s</VarName> or <VarName>t</VarName> was (a) used more than once, and (b) large or a redex, then it would
3398 not be substituted, and the rule would not fire.
3399
3400 </Para>
3401 </ListItem>
3402 <ListItem>
3403
3404 <Para>
3405  In the earlier phases of compilation, GHC inlines <Emphasis>nothing
3406 that appears on the LHS of a rule</Emphasis>, because once you have substituted
3407 for something you can't match against it (given the simple minded
3408 matching).  So if you write the rule
3409
3410 <ProgramListing>
3411         "map/map"       forall f,g.  map f . map g = map (f.g)
3412 </ProgramListing>
3413
3414 this <Emphasis>won't</Emphasis> match the expression <Literal>map f (map g xs)</Literal>.
3415 It will only match something written with explicit use of ".".
3416 Well, not quite.  It <Emphasis>will</Emphasis> match the expression
3417
3418 <ProgramListing>
3419 wibble f g xs
3420 </ProgramListing>
3421
3422 where <Function>wibble</Function> is defined:
3423
3424 <ProgramListing>
3425 wibble f g = map f . map g
3426 </ProgramListing>
3427
3428 because <Function>wibble</Function> will be inlined (it's small).
3429
3430 Later on in compilation, GHC starts inlining even things on the
3431 LHS of rules, but still leaves the rules enabled.  This inlining
3432 policy is controlled by the per-simplification-pass flag <Option>-finline-phase</Option><Emphasis>n</Emphasis>.
3433
3434 </Para>
3435 </ListItem>
3436 <ListItem>
3437
3438 <Para>
3439  All rules are implicitly exported from the module, and are therefore
3440 in force in any module that imports the module that defined the rule, directly
3441 or indirectly.  (That is, if A imports B, which imports C, then C's rules are
3442 in force when compiling A.)  The situation is very similar to that for instance
3443 declarations.
3444 </Para>
3445 </ListItem>
3446
3447 </ItemizedList>
3448
3449 </Para>
3450
3451 </Sect2>
3452
3453 <Sect2>
3454 <Title>List fusion</Title>
3455
3456 <Para>
3457 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
3458 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
3459 intermediate list should be eliminated entirely.
3460 </Para>
3461
3462 <Para>
3463 The following are good producers:
3464
3465 <ItemizedList>
3466 <ListItem>
3467
3468 <Para>
3469  List comprehensions
3470 </Para>
3471 </ListItem>
3472 <ListItem>
3473
3474 <Para>
3475  Enumerations of <Literal>Int</Literal> and <Literal>Char</Literal> (e.g. <Literal>['a'..'z']</Literal>).
3476 </Para>
3477 </ListItem>
3478 <ListItem>
3479
3480 <Para>
3481  Explicit lists (e.g. <Literal>[True, False]</Literal>)
3482 </Para>
3483 </ListItem>
3484 <ListItem>
3485
3486 <Para>
3487  The cons constructor (e.g <Literal>3:4:[]</Literal>)
3488 </Para>
3489 </ListItem>
3490 <ListItem>
3491
3492 <Para>
3493  <Function>++</Function>
3494 </Para>
3495 </ListItem>
3496 <ListItem>
3497
3498 <Para>
3499  <Function>map</Function>
3500 </Para>
3501 </ListItem>
3502 <ListItem>
3503
3504 <Para>
3505  <Function>filter</Function>
3506 </Para>
3507 </ListItem>
3508 <ListItem>
3509
3510 <Para>
3511  <Function>iterate</Function>, <Function>repeat</Function>
3512 </Para>
3513 </ListItem>
3514 <ListItem>
3515
3516 <Para>
3517  <Function>zip</Function>, <Function>zipWith</Function>
3518 </Para>
3519 </ListItem>
3520
3521 </ItemizedList>
3522
3523 </Para>
3524
3525 <Para>
3526 The following are good consumers:
3527
3528 <ItemizedList>
3529 <ListItem>
3530
3531 <Para>
3532  List comprehensions
3533 </Para>
3534 </ListItem>
3535 <ListItem>
3536
3537 <Para>
3538  <Function>array</Function> (on its second argument)
3539 </Para>
3540 </ListItem>
3541 <ListItem>
3542
3543 <Para>
3544  <Function>length</Function>
3545 </Para>
3546 </ListItem>
3547 <ListItem>
3548
3549 <Para>
3550  <Function>++</Function> (on its first argument)
3551 </Para>
3552 </ListItem>
3553 <ListItem>
3554
3555 <Para>
3556  <Function>map</Function>
3557 </Para>
3558 </ListItem>
3559 <ListItem>
3560
3561 <Para>
3562  <Function>filter</Function>
3563 </Para>
3564 </ListItem>
3565 <ListItem>
3566
3567 <Para>
3568  <Function>concat</Function>
3569 </Para>
3570 </ListItem>
3571 <ListItem>
3572
3573 <Para>
3574  <Function>unzip</Function>, <Function>unzip2</Function>, <Function>unzip3</Function>, <Function>unzip4</Function>
3575 </Para>
3576 </ListItem>
3577 <ListItem>
3578
3579 <Para>
3580  <Function>zip</Function>, <Function>zipWith</Function> (but on one argument only; if both are good producers, <Function>zip</Function>
3581 will fuse with one but not the other)
3582 </Para>
3583 </ListItem>
3584 <ListItem>
3585
3586 <Para>
3587  <Function>partition</Function>
3588 </Para>
3589 </ListItem>
3590 <ListItem>
3591
3592 <Para>
3593  <Function>head</Function>
3594 </Para>
3595 </ListItem>
3596 <ListItem>
3597
3598 <Para>
3599  <Function>and</Function>, <Function>or</Function>, <Function>any</Function>, <Function>all</Function>
3600 </Para>
3601 </ListItem>
3602 <ListItem>
3603
3604 <Para>
3605  <Function>sequence&lowbar;</Function>
3606 </Para>
3607 </ListItem>
3608 <ListItem>
3609
3610 <Para>
3611  <Function>msum</Function>
3612 </Para>
3613 </ListItem>
3614 <ListItem>
3615
3616 <Para>
3617  <Function>sortBy</Function>
3618 </Para>
3619 </ListItem>
3620
3621 </ItemizedList>
3622
3623 </Para>
3624
3625 <Para>
3626 So, for example, the following should generate no intermediate lists:
3627
3628 <ProgramListing>
3629 array (1,10) [(i,i*i) | i &#60;- map (+ 1) [0..9]]
3630 </ProgramListing>
3631
3632 </Para>
3633
3634 <Para>
3635 This list could readily be extended; if there are Prelude functions that you use
3636 a lot which are not included, please tell us.
3637 </Para>
3638
3639 <Para>
3640 If you want to write your own good consumers or producers, look at the
3641 Prelude definitions of the above functions to see how to do so.
3642 </Para>
3643
3644 </Sect2>
3645
3646 <Sect2 id="rule-spec">
3647 <Title>Specialisation
3648 </Title>
3649
3650 <Para>
3651 Rewrite rules can be used to get the same effect as a feature
3652 present in earlier version of GHC:
3653
3654 <ProgramListing>
3655   {-# SPECIALIZE fromIntegral :: Int8 -&#62; Int16 = int8ToInt16 #-}
3656 </ProgramListing>
3657
3658 This told GHC to use <Function>int8ToInt16</Function> instead of <Function>fromIntegral</Function> whenever
3659 the latter was called with type <Literal>Int8 -&gt; Int16</Literal>.  That is, rather than
3660 specialising the original definition of <Function>fromIntegral</Function> the programmer is
3661 promising that it is safe to use <Function>int8ToInt16</Function> instead.
3662 </Para>
3663
3664 <Para>
3665 This feature is no longer in GHC.  But rewrite rules let you do the
3666 same thing:
3667
3668 <ProgramListing>
3669 {-# RULES
3670   "fromIntegral/Int8/Int16" fromIntegral = int8ToInt16
3671 #-}
3672 </ProgramListing>
3673
3674 This slightly odd-looking rule instructs GHC to replace <Function>fromIntegral</Function>
3675 by <Function>int8ToInt16</Function> <Emphasis>whenever the types match</Emphasis>.  Speaking more operationally,
3676 GHC adds the type and dictionary applications to get the typed rule
3677
3678 <ProgramListing>
3679 forall (d1::Integral Int8) (d2::Num Int16) .
3680         fromIntegral Int8 Int16 d1 d2 = int8ToInt16
3681 </ProgramListing>
3682
3683 What is more,
3684 this rule does not need to be in the same file as fromIntegral,
3685 unlike the <Literal>SPECIALISE</Literal> pragmas which currently do (so that they
3686 have an original definition available to specialise).
3687 </Para>
3688
3689 </Sect2>
3690
3691 <Sect2>
3692 <Title>Controlling what's going on</Title>
3693
3694 <Para>
3695
3696 <ItemizedList>
3697 <ListItem>
3698
3699 <Para>
3700  Use <Option>-ddump-rules</Option> to see what transformation rules GHC is using.
3701 </Para>
3702 </ListItem>
3703 <ListItem>
3704
3705 <Para>
3706  Use <Option>-ddump-simpl-stats</Option> to see what rules are being fired.
3707 If you add <Option>-dppr-debug</Option> you get a more detailed listing.
3708 </Para>
3709 </ListItem>
3710 <ListItem>
3711
3712 <Para>
3713  The defintion of (say) <Function>build</Function> in <FileName>PrelBase.lhs</FileName> looks llike this:
3714
3715 <ProgramListing>
3716         build   :: forall a. (forall b. (a -&#62; b -&#62; b) -&#62; b -&#62; b) -&#62; [a]
3717         {-# INLINE build #-}
3718         build g = g (:) []
3719 </ProgramListing>
3720
3721 Notice the <Literal>INLINE</Literal>!  That prevents <Literal>(:)</Literal> from being inlined when compiling
3722 <Literal>PrelBase</Literal>, so that an importing module will ``see'' the <Literal>(:)</Literal>, and can
3723 match it on the LHS of a rule.  <Literal>INLINE</Literal> prevents any inlining happening
3724 in the RHS of the <Literal>INLINE</Literal> thing.  I regret the delicacy of this.
3725
3726 </Para>
3727 </ListItem>
3728 <ListItem>
3729
3730 <Para>
3731  In <Filename>ghc/lib/std/PrelBase.lhs</Filename> look at the rules for <Function>map</Function> to
3732 see how to write rules that will do fusion and yet give an efficient
3733 program even if fusion doesn't happen.  More rules in <Filename>PrelList.lhs</Filename>.
3734 </Para>
3735 </ListItem>
3736
3737 </ItemizedList>
3738
3739 </Para>
3740
3741 </Sect2>
3742
3743 </Sect1>