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