[project @ 2000-04-07 13:26:33 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://research.microsoft.com/~simonpj/multi.ps.gz" >Type
2216 classes: exploring the design space</ULink > (Simon Peyton Jones, Mark
2217 Jones, Erik Meijer).
2218 </Para>
2219
2220 <Para>
2221 I'd like to thank people who reported shorcomings in the GHC 3.02
2222 implementation.  Our default decisions were all conservative ones, and
2223 the experience of these heroic pioneers has given useful concrete
2224 examples to support several generalisations.  (These appear below as
2225 design choices not implemented in 3.02.)
2226 </Para>
2227
2228 <Para>
2229 I've discussed these notes with Mark Jones, and I believe that Hugs
2230 will migrate towards the same design choices as I outline here.
2231 Thanks to him, and to many others who have offered very useful
2232 feedback.
2233 </Para>
2234
2235 <Sect2>
2236 <Title>Types</Title>
2237
2238 <Para>
2239 There are the following restrictions on the form of a qualified
2240 type:
2241 </Para>
2242
2243 <Para>
2244
2245 <ProgramListing>
2246   forall tv1..tvn (c1, ...,cn) => type
2247 </ProgramListing>
2248
2249 </Para>
2250
2251 <Para>
2252 (Here, I write the "foralls" explicitly, although the Haskell source
2253 language omits them; in Haskell 1.4, all the free type variables of an
2254 explicit source-language type signature are universally quantified,
2255 except for the class type variables in a class declaration.  However,
2256 in GHC, you can give the foralls if you want.  See <XRef LinkEnd="universal-quantification">).
2257 </Para>
2258
2259 <Para>
2260
2261 <OrderedList>
2262 <ListItem>
2263
2264 <Para>
2265  <Emphasis>Each universally quantified type variable
2266 <Literal>tvi</Literal> must be mentioned (i.e. appear free) in <Literal>type</Literal></Emphasis>.
2267
2268 The reason for this is that a value with a type that does not obey
2269 this restriction could not be used without introducing
2270 ambiguity. Here, for example, is an illegal type:
2271
2272
2273 <ProgramListing>
2274   forall a. Eq a => Int
2275 </ProgramListing>
2276
2277
2278 When a value with this type was used, the constraint <Literal>Eq tv</Literal>
2279 would be introduced where <Literal>tv</Literal> is a fresh type variable, and
2280 (in the dictionary-translation implementation) the value would be
2281 applied to a dictionary for <Literal>Eq tv</Literal>.  The difficulty is that we
2282 can never know which instance of <Literal>Eq</Literal> to use because we never
2283 get any more information about <Literal>tv</Literal>.
2284
2285 </Para>
2286 </ListItem>
2287 <ListItem>
2288
2289 <Para>
2290  <Emphasis>Every constraint <Literal>ci</Literal> must mention at least one of the
2291 universally quantified type variables <Literal>tvi</Literal></Emphasis>.
2292
2293 For example, this type is OK because <Literal>C a b</Literal> mentions the
2294 universally quantified type variable <Literal>b</Literal>:
2295
2296
2297 <ProgramListing>
2298   forall a. C a b => burble
2299 </ProgramListing>
2300
2301
2302 The next type is illegal because the constraint <Literal>Eq b</Literal> does not
2303 mention <Literal>a</Literal>:
2304
2305
2306 <ProgramListing>
2307   forall a. Eq b => burble
2308 </ProgramListing>
2309
2310
2311 The reason for this restriction is milder than the other one.  The
2312 excluded types are never useful or necessary (because the offending
2313 context doesn't need to be witnessed at this point; it can be floated
2314 out).  Furthermore, floating them out increases sharing. Lastly,
2315 excluding them is a conservative choice; it leaves a patch of
2316 territory free in case we need it later.
2317
2318 </Para>
2319 </ListItem>
2320
2321 </OrderedList>
2322
2323 </Para>
2324
2325 <Para>
2326 These restrictions apply to all types, whether declared in a type signature
2327 or inferred.
2328 </Para>
2329
2330 <Para>
2331 Unlike Haskell 1.4, constraints in types do <Emphasis>not</Emphasis> have to be of
2332 the form <Emphasis>(class type-variables)</Emphasis>.  Thus, these type signatures
2333 are perfectly OK
2334 </Para>
2335
2336 <Para>
2337
2338 <ProgramListing>
2339   f :: Eq (m a) => [m a] -> [m a]
2340   g :: Eq [a] => ...
2341 </ProgramListing>
2342
2343 </Para>
2344
2345 <Para>
2346 This choice recovers principal types, a property that Haskell 1.4 does not have.
2347 </Para>
2348
2349 </Sect2>
2350
2351 <Sect2>
2352 <Title>Class declarations</Title>
2353
2354 <Para>
2355
2356 <OrderedList>
2357 <ListItem>
2358
2359 <Para>
2360  <Emphasis>Multi-parameter type classes are permitted</Emphasis>. For example:
2361
2362
2363 <ProgramListing>
2364   class Collection c a where
2365     union :: c a -> c a -> c a
2366     ...etc.
2367 </ProgramListing>
2368
2369
2370
2371 </Para>
2372 </ListItem>
2373 <ListItem>
2374
2375 <Para>
2376  <Emphasis>The class hierarchy must be acyclic</Emphasis>.  However, the definition
2377 of "acyclic" involves only the superclass relationships.  For example,
2378 this is OK:
2379
2380
2381 <ProgramListing>
2382   class C a where {
2383     op :: D b => a -> b -> b
2384   }
2385
2386   class C a => D a where { ... }
2387 </ProgramListing>
2388
2389
2390 Here, <Literal>C</Literal> is a superclass of <Literal>D</Literal>, but it's OK for a
2391 class operation <Literal>op</Literal> of <Literal>C</Literal> to mention <Literal>D</Literal>.  (It
2392 would not be OK for <Literal>D</Literal> to be a superclass of <Literal>C</Literal>.)
2393
2394 </Para>
2395 </ListItem>
2396 <ListItem>
2397
2398 <Para>
2399  <Emphasis>There are no restrictions on the context in a class declaration
2400 (which introduces superclasses), except that the class hierarchy must
2401 be acyclic</Emphasis>.  So these class declarations are OK:
2402
2403
2404 <ProgramListing>
2405   class Functor (m k) => FiniteMap m k where
2406     ...
2407
2408   class (Monad m, Monad (t m)) => Transform t m where
2409     lift :: m a -> (t m) a
2410 </ProgramListing>
2411
2412
2413 </Para>
2414 </ListItem>
2415 <ListItem>
2416
2417 <Para>
2418  <Emphasis>In the signature of a class operation, every constraint
2419 must mention at least one type variable that is not a class type
2420 variable</Emphasis>.
2421
2422 Thus:
2423
2424
2425 <ProgramListing>
2426   class Collection c a where
2427     mapC :: Collection c b => (a->b) -> c a -> c b
2428 </ProgramListing>
2429
2430
2431 is OK because the constraint <Literal>(Collection a b)</Literal> mentions
2432 <Literal>b</Literal>, even though it also mentions the class variable
2433 <Literal>a</Literal>.  On the other hand:
2434
2435
2436 <ProgramListing>
2437   class C a where
2438     op :: Eq a => (a,b) -> (a,b)
2439 </ProgramListing>
2440
2441
2442 is not OK because the constraint <Literal>(Eq a)</Literal> mentions on the class
2443 type variable <Literal>a</Literal>, but not <Literal>b</Literal>.  However, any such
2444 example is easily fixed by moving the offending context up to the
2445 superclass context:
2446
2447
2448 <ProgramListing>
2449   class Eq a => C a where
2450     op ::(a,b) -> (a,b)
2451 </ProgramListing>
2452
2453
2454 A yet more relaxed rule would allow the context of a class-op signature
2455 to mention only class type variables.  However, that conflicts with
2456 Rule 1(b) for types above.
2457
2458 </Para>
2459 </ListItem>
2460 <ListItem>
2461
2462 <Para>
2463  <Emphasis>The type of each class operation must mention <Emphasis>all</Emphasis> of
2464 the class type variables</Emphasis>.  For example:
2465
2466
2467 <ProgramListing>
2468   class Coll s a where
2469     empty  :: s
2470     insert :: s -> a -> s
2471 </ProgramListing>
2472
2473
2474 is not OK, because the type of <Literal>empty</Literal> doesn't mention
2475 <Literal>a</Literal>.  This rule is a consequence of Rule 1(a), above, for
2476 types, and has the same motivation.
2477
2478 Sometimes, offending class declarations exhibit misunderstandings.  For
2479 example, <Literal>Coll</Literal> might be rewritten
2480
2481
2482 <ProgramListing>
2483   class Coll s a where
2484     empty  :: s a
2485     insert :: s a -> a -> s a
2486 </ProgramListing>
2487
2488
2489 which makes the connection between the type of a collection of
2490 <Literal>a</Literal>'s (namely <Literal>(s a)</Literal>) and the element type <Literal>a</Literal>.
2491 Occasionally this really doesn't work, in which case you can split the
2492 class like this:
2493
2494
2495 <ProgramListing>
2496   class CollE s where
2497     empty  :: s
2498
2499   class CollE s => Coll s a where
2500     insert :: s -> a -> s
2501 </ProgramListing>
2502
2503
2504 </Para>
2505 </ListItem>
2506
2507 </OrderedList>
2508
2509 </Para>
2510
2511 </Sect2>
2512
2513 <Sect2>
2514 <Title>Instance declarations</Title>
2515
2516 <Para>
2517
2518 <OrderedList>
2519 <ListItem>
2520
2521 <Para>
2522  <Emphasis>Instance declarations may not overlap</Emphasis>.  The two instance
2523 declarations
2524
2525
2526 <ProgramListing>
2527   instance context1 => C type1 where ...
2528   instance context2 => C type2 where ...
2529 </ProgramListing>
2530
2531
2532 "overlap" if <Literal>type1</Literal> and <Literal>type2</Literal> unify
2533
2534 However, if you give the command line option
2535 <Option>-fallow-overlapping-instances</Option><IndexTerm><Primary>-fallow-overlapping-instances
2536 option</Primary></IndexTerm> then two overlapping instance declarations are permitted
2537 iff
2538
2539
2540 <ItemizedList>
2541 <ListItem>
2542
2543 <Para>
2544  EITHER <Literal>type1</Literal> and <Literal>type2</Literal> do not unify
2545 </Para>
2546 </ListItem>
2547 <ListItem>
2548
2549 <Para>
2550  OR <Literal>type2</Literal> is a substitution instance of <Literal>type1</Literal>
2551 (but not identical to <Literal>type1</Literal>)
2552 </Para>
2553 </ListItem>
2554 <ListItem>
2555
2556 <Para>
2557  OR vice versa
2558 </Para>
2559 </ListItem>
2560
2561 </ItemizedList>
2562
2563
2564 Notice that these rules
2565
2566
2567 <ItemizedList>
2568 <ListItem>
2569
2570 <Para>
2571  make it clear which instance decl to use
2572 (pick the most specific one that matches)
2573
2574 </Para>
2575 </ListItem>
2576 <ListItem>
2577
2578 <Para>
2579  do not mention the contexts <Literal>context1</Literal>, <Literal>context2</Literal>
2580 Reason: you can pick which instance decl
2581 "matches" based on the type.
2582 </Para>
2583 </ListItem>
2584
2585 </ItemizedList>
2586
2587
2588 Regrettably, GHC doesn't guarantee to detect overlapping instance
2589 declarations if they appear in different modules.  GHC can "see" the
2590 instance declarations in the transitive closure of all the modules
2591 imported by the one being compiled, so it can "see" all instance decls
2592 when it is compiling <Literal>Main</Literal>.  However, it currently chooses not
2593 to look at ones that can't possibly be of use in the module currently
2594 being compiled, in the interests of efficiency.  (Perhaps we should
2595 change that decision, at least for <Literal>Main</Literal>.)
2596
2597 </Para>
2598 </ListItem>
2599 <ListItem>
2600
2601 <Para>
2602  <Emphasis>There are no restrictions on the type in an instance
2603 <Emphasis>head</Emphasis>, except that at least one must not be a type variable</Emphasis>.
2604 The instance "head" is the bit after the "=>" in an instance decl. For
2605 example, these are OK:
2606
2607
2608 <ProgramListing>
2609   instance C Int a where ...
2610
2611   instance D (Int, Int) where ...
2612
2613   instance E [[a]] where ...
2614 </ProgramListing>
2615
2616
2617 Note that instance heads <Emphasis>may</Emphasis> contain repeated type variables.
2618 For example, this is OK:
2619
2620
2621 <ProgramListing>
2622   instance Stateful (ST s) (MutVar s) where ...
2623 </ProgramListing>
2624
2625
2626 The "at least one not a type variable" restriction is to ensure that
2627 context reduction terminates: each reduction step removes one type
2628 constructor.  For example, the following would make the type checker
2629 loop if it wasn't excluded:
2630
2631
2632 <ProgramListing>
2633   instance C a => C a where ...
2634 </ProgramListing>
2635
2636
2637 There are two situations in which the rule is a bit of a pain. First,
2638 if one allows overlapping instance declarations then it's quite
2639 convenient to have a "default instance" declaration that applies if
2640 something more specific does not:
2641
2642
2643 <ProgramListing>
2644   instance C a where
2645     op = ... -- Default
2646 </ProgramListing>
2647
2648
2649 Second, sometimes you might want to use the following to get the
2650 effect of a "class synonym":
2651
2652
2653 <ProgramListing>
2654   class (C1 a, C2 a, C3 a) => C a where { }
2655
2656   instance (C1 a, C2 a, C3 a) => C a where { }
2657 </ProgramListing>
2658
2659
2660 This allows you to write shorter signatures:
2661
2662
2663 <ProgramListing>
2664   f :: C a => ...
2665 </ProgramListing>
2666
2667
2668 instead of
2669
2670
2671 <ProgramListing>
2672   f :: (C1 a, C2 a, C3 a) => ...
2673 </ProgramListing>
2674
2675
2676 I'm on the lookout for a simple rule that preserves decidability while
2677 allowing these idioms.  The experimental flag
2678 <Option>-fallow-undecidable-instances</Option><IndexTerm><Primary>-fallow-undecidable-instances
2679 option</Primary></IndexTerm> lifts this restriction, allowing all the types in an
2680 instance head to be type variables.
2681
2682 </Para>
2683 </ListItem>
2684 <ListItem>
2685
2686 <Para>
2687  <Emphasis>Unlike Haskell 1.4, instance heads may use type
2688 synonyms</Emphasis>.  As always, using a type synonym is just shorthand for
2689 writing the RHS of the type synonym definition.  For example:
2690
2691
2692 <ProgramListing>
2693   type Point = (Int,Int)
2694   instance C Point   where ...
2695   instance C [Point] where ...
2696 </ProgramListing>
2697
2698
2699 is legal.  However, if you added
2700
2701
2702 <ProgramListing>
2703   instance C (Int,Int) where ...
2704 </ProgramListing>
2705
2706
2707 as well, then the compiler will complain about the overlapping
2708 (actually, identical) instance declarations.  As always, type synonyms
2709 must be fully applied.  You cannot, for example, write:
2710
2711
2712 <ProgramListing>
2713   type P a = [[a]]
2714   instance Monad P where ...
2715 </ProgramListing>
2716
2717
2718 This design decision is independent of all the others, and easily
2719 reversed, but it makes sense to me.
2720
2721 </Para>
2722 </ListItem>
2723 <ListItem>
2724
2725 <Para>
2726 <Emphasis>The types in an instance-declaration <Emphasis>context</Emphasis> must all
2727 be type variables</Emphasis>. Thus
2728
2729
2730 <ProgramListing>
2731 instance C a b => Eq (a,b) where ...
2732 </ProgramListing>
2733
2734
2735 is OK, but
2736
2737
2738 <ProgramListing>
2739 instance C Int b => Foo b where ...
2740 </ProgramListing>
2741
2742
2743 is not OK.  Again, the intent here is to make sure that context
2744 reduction terminates.
2745
2746 Voluminous correspondence on the Haskell mailing list has convinced me
2747 that it's worth experimenting with a more liberal rule.  If you use
2748 the flag <Option>-fallow-undecidable-instances</Option> can use arbitrary
2749 types in an instance context.  Termination is ensured by having a
2750 fixed-depth recursion stack.  If you exceed the stack depth you get a
2751 sort of backtrace, and the opportunity to increase the stack depth
2752 with <Option>-fcontext-stack</Option><Emphasis>N</Emphasis>.
2753
2754 </Para>
2755 </ListItem>
2756
2757 </OrderedList>
2758
2759 </Para>
2760
2761 </Sect2>
2762
2763 </Sect1>
2764
2765 <Sect1 id="universal-quantification">
2766 <Title>Explicit universal quantification
2767 </Title>
2768
2769 <Para>
2770 GHC now allows you to write explicitly quantified types.  GHC's
2771 syntax for this now agrees with Hugs's, namely:
2772 </Para>
2773
2774 <Para>
2775
2776 <ProgramListing>
2777         forall a b. (Ord a, Eq  b) => a -> b -> a
2778 </ProgramListing>
2779
2780 </Para>
2781
2782 <Para>
2783 The context is, of course, optional.  You can't use <Literal>forall</Literal> as
2784 a type variable any more!
2785 </Para>
2786
2787 <Para>
2788 Haskell type signatures are implicitly quantified.  The <Literal>forall</Literal>
2789 allows us to say exactly what this means.  For example:
2790 </Para>
2791
2792 <Para>
2793
2794 <ProgramListing>
2795         g :: b -> b
2796 </ProgramListing>
2797
2798 </Para>
2799
2800 <Para>
2801 means this:
2802 </Para>
2803
2804 <Para>
2805
2806 <ProgramListing>
2807         g :: forall b. (b -> b)
2808 </ProgramListing>
2809
2810 </Para>
2811
2812 <Para>
2813 The two are treated identically.
2814 </Para>
2815
2816 <Sect2 id="univ">
2817 <Title>Universally-quantified data type fields
2818 </Title>
2819
2820 <Para>
2821 In a <Literal>data</Literal> or <Literal>newtype</Literal> declaration one can quantify
2822 the types of the constructor arguments.  Here are several examples:
2823 </Para>
2824
2825 <Para>
2826
2827 <ProgramListing>
2828 data T a = T1 (forall b. b -> b -> b) a
2829
2830 data MonadT m = MkMonad { return :: forall a. a -> m a,
2831                           bind   :: forall a b. m a -> (a -> m b) -> m b
2832                         }
2833
2834 newtype Swizzle = MkSwizzle (Ord a => [a] -> [a])
2835 </ProgramListing>
2836
2837 </Para>
2838
2839 <Para>
2840 The constructors now have so-called <Emphasis>rank 2</Emphasis> polymorphic
2841 types, in which there is a for-all in the argument types.:
2842 </Para>
2843
2844 <Para>
2845
2846 <ProgramListing>
2847 T1 :: forall a. (forall b. b -> b -> b) -> a -> T a
2848 MkMonad :: forall m. (forall a. a -> m a)
2849                   -> (forall a b. m a -> (a -> m b) -> m b)
2850                   -> MonadT m
2851 MkSwizzle :: (Ord a => [a] -> [a]) -> Swizzle
2852 </ProgramListing>
2853
2854 </Para>
2855
2856 <Para>
2857 Notice that you don't need to use a <Literal>forall</Literal> if there's an
2858 explicit context.  For example in the first argument of the
2859 constructor <Function>MkSwizzle</Function>, an implicit "<Literal>forall a.</Literal>" is
2860 prefixed to the argument type.  The implicit <Literal>forall</Literal>
2861 quantifies all type variables that are not already in scope, and are
2862 mentioned in the type quantified over.
2863 </Para>
2864
2865 <Para>
2866 As for type signatures, implicit quantification happens for non-overloaded
2867 types too.  So if you write this:
2868
2869 <ProgramListing>
2870   data T a = MkT (Either a b) (b -> b)
2871 </ProgramListing>
2872
2873 it's just as if you had written this:
2874
2875 <ProgramListing>
2876   data T a = MkT (forall b. Either a b) (forall b. b -> b)
2877 </ProgramListing>
2878
2879 That is, since the type variable <Literal>b</Literal> isn't in scope, it's
2880 implicitly universally quantified.  (Arguably, it would be better
2881 to <Emphasis>require</Emphasis> explicit quantification on constructor arguments
2882 where that is what is wanted.  Feedback welcomed.)
2883 </Para>
2884
2885 </Sect2>
2886
2887 <Sect2>
2888 <Title>Construction </Title>
2889
2890 <Para>
2891 You construct values of types <Literal>T1, MonadT, Swizzle</Literal> by applying
2892 the constructor to suitable values, just as usual.  For example,
2893 </Para>
2894
2895 <Para>
2896
2897 <ProgramListing>
2898 (T1 (\xy->x) 3) :: T Int
2899
2900 (MkSwizzle sort)    :: Swizzle
2901 (MkSwizzle reverse) :: Swizzle
2902
2903 (let r x = Just x
2904      b m k = case m of
2905                 Just y -> k y
2906                 Nothing -> Nothing
2907   in
2908   MkMonad r b) :: MonadT Maybe
2909 </ProgramListing>
2910
2911 </Para>
2912
2913 <Para>
2914 The type of the argument can, as usual, be more general than the type
2915 required, as <Literal>(MkSwizzle reverse)</Literal> shows.  (<Function>reverse</Function>
2916 does not need the <Literal>Ord</Literal> constraint.)
2917 </Para>
2918
2919 </Sect2>
2920
2921 <Sect2>
2922 <Title>Pattern matching</Title>
2923
2924 <Para>
2925 When you use pattern matching, the bound variables may now have
2926 polymorphic types.  For example:
2927 </Para>
2928
2929 <Para>
2930
2931 <ProgramListing>
2932         f :: T a -> a -> (a, Char)
2933         f (T1 f k) x = (f k x, f 'c' 'd')
2934
2935         g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b]
2936         g (MkSwizzle s) xs f = s (map f (s xs))
2937
2938         h :: MonadT m -> [m a] -> m [a]
2939         h m [] = return m []
2940         h m (x:xs) = bind m x           $ \y ->
2941                       bind m (h m xs)   $ \ys ->
2942                       return m (y:ys)
2943 </ProgramListing>
2944
2945 </Para>
2946
2947 <Para>
2948 In the function <Function>h</Function> we use the record selectors <Literal>return</Literal>
2949 and <Literal>bind</Literal> to extract the polymorphic bind and return functions
2950 from the <Literal>MonadT</Literal> data structure, rather than using pattern
2951 matching.
2952 </Para>
2953
2954 <Para>
2955 You cannot pattern-match against an argument that is polymorphic.
2956 For example:
2957
2958 <ProgramListing>
2959         newtype TIM s a = TIM (ST s (Maybe a))
2960
2961         runTIM :: (forall s. TIM s a) -> Maybe a
2962         runTIM (TIM m) = runST m
2963 </ProgramListing>
2964
2965 </Para>
2966
2967 <Para>
2968 Here the pattern-match fails, because you can't pattern-match against
2969 an argument of type <Literal>(forall s. TIM s a)</Literal>.  Instead you
2970 must bind the variable and pattern match in the right hand side:
2971
2972 <ProgramListing>
2973         runTIM :: (forall s. TIM s a) -> Maybe a
2974         runTIM tm = case tm of { TIM m -> runST m }
2975 </ProgramListing>
2976
2977 The <Literal>tm</Literal> on the right hand side is (invisibly) instantiated, like
2978 any polymorphic value at its occurrence site, and now you can pattern-match
2979 against it.
2980 </Para>
2981
2982 </Sect2>
2983
2984 <Sect2>
2985 <Title>The partial-application restriction</Title>
2986
2987 <Para>
2988 There is really only one way in which data structures with polymorphic
2989 components might surprise you: you must not partially apply them.
2990 For example, this is illegal:
2991 </Para>
2992
2993 <Para>
2994
2995 <ProgramListing>
2996         map MkSwizzle [sort, reverse]
2997 </ProgramListing>
2998
2999 </Para>
3000
3001 <Para>
3002 The restriction is this: <Emphasis>every subexpression of the program must
3003 have a type that has no for-alls, except that in a function
3004 application (f e1&hellip;en) the partial applications are not subject to
3005 this rule</Emphasis>.  The restriction makes type inference feasible.
3006 </Para>
3007
3008 <Para>
3009 In the illegal example, the sub-expression <Literal>MkSwizzle</Literal> has the
3010 polymorphic type <Literal>(Ord b => [b] -> [b]) -> Swizzle</Literal> and is not
3011 a sub-expression of an enclosing application.  On the other hand, this
3012 expression is OK:
3013 </Para>
3014
3015 <Para>
3016
3017 <ProgramListing>
3018         map (T1 (\a b -> a)) [1,2,3]
3019 </ProgramListing>
3020
3021 </Para>
3022
3023 <Para>
3024 even though it involves a partial application of <Function>T1</Function>, because
3025 the sub-expression <Literal>T1 (\a b -> a)</Literal> has type <Literal>Int -> T
3026 Int</Literal>.
3027 </Para>
3028
3029 </Sect2>
3030
3031 <Sect2 id="sigs">
3032 <Title>Type signatures
3033 </Title>
3034
3035 <Para>
3036 Once you have data constructors with universally-quantified fields, or
3037 constants such as <Constant>runST</Constant> that have rank-2 types, it isn't long
3038 before you discover that you need more!  Consider:
3039 </Para>
3040
3041 <Para>
3042
3043 <ProgramListing>
3044   mkTs f x y = [T1 f x, T1 f y]
3045 </ProgramListing>
3046
3047 </Para>
3048
3049 <Para>
3050 <Function>mkTs</Function> is a fuction that constructs some values of type
3051 <Literal>T</Literal>, using some pieces passed to it.  The trouble is that since
3052 <Literal>f</Literal> is a function argument, Haskell assumes that it is
3053 monomorphic, so we'll get a type error when applying <Function>T1</Function> to
3054 it.  This is a rather silly example, but the problem really bites in
3055 practice.  Lots of people trip over the fact that you can't make
3056 "wrappers functions" for <Constant>runST</Constant> for exactly the same reason.
3057 In short, it is impossible to build abstractions around functions with
3058 rank-2 types.
3059 </Para>
3060
3061 <Para>
3062 The solution is fairly clear.  We provide the ability to give a rank-2
3063 type signature for <Emphasis>ordinary</Emphasis> functions (not only data
3064 constructors), thus:
3065 </Para>
3066
3067 <Para>
3068
3069 <ProgramListing>
3070   mkTs :: (forall b. b -> b -> b) -> a -> [T a]
3071   mkTs f x y = [T1 f x, T1 f y]
3072 </ProgramListing>
3073
3074 </Para>
3075
3076 <Para>
3077 This type signature tells the compiler to attribute <Literal>f</Literal> with
3078 the polymorphic type <Literal>(forall b. b -> b -> b)</Literal> when type
3079 checking the body of <Function>mkTs</Function>, so now the application of
3080 <Function>T1</Function> is fine.
3081 </Para>
3082
3083 <Para>
3084 There are two restrictions:
3085 </Para>
3086
3087 <Para>
3088
3089 <ItemizedList>
3090 <ListItem>
3091
3092 <Para>
3093  You can only define a rank 2 type, specified by the following
3094 grammar:
3095
3096
3097 <ProgramListing>
3098 rank2type ::= [forall tyvars .] [context =>] funty
3099 funty     ::= ([forall tyvars .] [context =>] ty) -> funty
3100             | ty
3101 ty        ::= ...current Haskell monotype syntax...
3102 </ProgramListing>
3103
3104
3105 Informally, the universal quantification must all be right at the beginning,
3106 or at the top level of a function argument.
3107
3108 </Para>
3109 </ListItem>
3110 <ListItem>
3111
3112 <Para>
3113  There is a restriction on the definition of a function whose
3114 type signature is a rank-2 type: the polymorphic arguments must be
3115 matched on the left hand side of the "<Literal>=</Literal>" sign.  You can't
3116 define <Function>mkTs</Function> like this:
3117
3118
3119 <ProgramListing>
3120 mkTs :: (forall b. b -> b -> b) -> a -> [T a]
3121 mkTs = \ f x y -> [T1 f x, T1 f y]
3122 </ProgramListing>
3123
3124
3125
3126 The same partial-application rule applies to ordinary functions with
3127 rank-2 types as applied to data constructors.
3128
3129 </Para>
3130 </ListItem>
3131
3132 </ItemizedList>
3133
3134 </Para>
3135
3136 </Sect2>
3137
3138
3139 <Sect2 id="hoist">
3140 <Title>Type synonyms and hoisting
3141 </Title>
3142
3143 <Para>
3144 GHC also allows you to write a <Literal>forall</Literal> in a type synonym, thus:
3145 <ProgramListing>
3146   type Discard a = forall b. a -> b -> a
3147
3148   f :: Discard a
3149   f x y = x
3150 </ProgramListing>
3151 However, it is often convenient to use these sort of synonyms at the right hand
3152 end of an arrow, thus:
3153 <ProgramListing>
3154   type Discard a = forall b. a -> b -> a
3155
3156   g :: Int -> Discard Int
3157   g x y z = x+y
3158 </ProgramListing>
3159 Simply expanding the type synonym would give
3160 <ProgramListing>
3161   g :: Int -> (forall b. Int -> b -> Int)
3162 </ProgramListing>
3163 but GHC "hoists" the <Literal>forall</Literal> to give the isomorphic type
3164 <ProgramListing>
3165   g :: forall b. Int -> Int -> b -> Int
3166 </ProgramListing>
3167 In general, the rule is this: <Emphasis>to determine the type specified by any explicit
3168 user-written type (e.g. in a type signature), GHC expands type synonyms and then repeatedly
3169 performs the transformation:</Emphasis>
3170 <ProgramListing>
3171   <Emphasis>type1</Emphasis> -> forall a. <Emphasis>type2</Emphasis>
3172 ==>
3173   forall a. <Emphasis>type1</Emphasis> -> <Emphasis>type2</Emphasis>
3174 </ProgramListing>
3175 (In fact, GHC tries to retain as much synonym information as possible for use in
3176 error messages, but that is a usability issue.)  This rule applies, of course, whether
3177 or not the <Literal>forall</Literal> comes from a synonym. For example, here is another
3178 valid way to write <Literal>g</Literal>'s type signature:
3179 <ProgramListing>
3180   g :: Int -> Int -> forall b. b -> Int
3181 </ProgramListing>
3182 </Para>
3183 </Sect2>
3184
3185 </Sect1>
3186
3187 <Sect1 id="existential-quantification">
3188 <Title>Existentially quantified data constructors
3189 </Title>
3190
3191 <Para>
3192 The idea of using existential quantification in data type declarations
3193 was suggested by Laufer (I believe, thought doubtless someone will
3194 correct me), and implemented in Hope+. It's been in Lennart
3195 Augustsson's <Command>hbc</Command> Haskell compiler for several years, and
3196 proved very useful.  Here's the idea.  Consider the declaration:
3197 </Para>
3198
3199 <Para>
3200
3201 <ProgramListing>
3202   data Foo = forall a. MkFoo a (a -> Bool)
3203            | Nil
3204 </ProgramListing>
3205
3206 </Para>
3207
3208 <Para>
3209 The data type <Literal>Foo</Literal> has two constructors with types:
3210 </Para>
3211
3212 <Para>
3213
3214 <ProgramListing>
3215   MkFoo :: forall a. a -> (a -> Bool) -> Foo
3216   Nil   :: Foo
3217 </ProgramListing>
3218
3219 </Para>
3220
3221 <Para>
3222 Notice that the type variable <Literal>a</Literal> in the type of <Function>MkFoo</Function>
3223 does not appear in the data type itself, which is plain <Literal>Foo</Literal>.
3224 For example, the following expression is fine:
3225 </Para>
3226
3227 <Para>
3228
3229 <ProgramListing>
3230   [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
3231 </ProgramListing>
3232
3233 </Para>
3234
3235 <Para>
3236 Here, <Literal>(MkFoo 3 even)</Literal> packages an integer with a function
3237 <Function>even</Function> that maps an integer to <Literal>Bool</Literal>; and <Function>MkFoo 'c'
3238 isUpper</Function> packages a character with a compatible function.  These
3239 two things are each of type <Literal>Foo</Literal> and can be put in a list.
3240 </Para>
3241
3242 <Para>
3243 What can we do with a value of type <Literal>Foo</Literal>?.  In particular,
3244 what happens when we pattern-match on <Function>MkFoo</Function>?
3245 </Para>
3246
3247 <Para>
3248
3249 <ProgramListing>
3250   f (MkFoo val fn) = ???
3251 </ProgramListing>
3252
3253 </Para>
3254
3255 <Para>
3256 Since all we know about <Literal>val</Literal> and <Function>fn</Function> is that they
3257 are compatible, the only (useful) thing we can do with them is to
3258 apply <Function>fn</Function> to <Literal>val</Literal> to get a boolean.  For example:
3259 </Para>
3260
3261 <Para>
3262
3263 <ProgramListing>
3264   f :: Foo -> Bool
3265   f (MkFoo val fn) = fn val
3266 </ProgramListing>
3267
3268 </Para>
3269
3270 <Para>
3271 What this allows us to do is to package heterogenous values
3272 together with a bunch of functions that manipulate them, and then treat
3273 that collection of packages in a uniform manner.  You can express
3274 quite a bit of object-oriented-like programming this way.
3275 </Para>
3276
3277 <Sect2 id="existential">
3278 <Title>Why existential?
3279 </Title>
3280
3281 <Para>
3282 What has this to do with <Emphasis>existential</Emphasis> quantification?
3283 Simply that <Function>MkFoo</Function> has the (nearly) isomorphic type
3284 </Para>
3285
3286 <Para>
3287
3288 <ProgramListing>
3289   MkFoo :: (exists a . (a, a -> Bool)) -> Foo
3290 </ProgramListing>
3291
3292 </Para>
3293
3294 <Para>
3295 But Haskell programmers can safely think of the ordinary
3296 <Emphasis>universally</Emphasis> quantified type given above, thereby avoiding
3297 adding a new existential quantification construct.
3298 </Para>
3299
3300 </Sect2>
3301
3302 <Sect2>
3303 <Title>Type classes</Title>
3304
3305 <Para>
3306 An easy extension (implemented in <Command>hbc</Command>) is to allow
3307 arbitrary contexts before the constructor.  For example:
3308 </Para>
3309
3310 <Para>
3311
3312 <ProgramListing>
3313 data Baz = forall a. Eq a => Baz1 a a
3314          | forall b. Show b => Baz2 b (b -> b)
3315 </ProgramListing>
3316
3317 </Para>
3318
3319 <Para>
3320 The two constructors have the types you'd expect:
3321 </Para>
3322
3323 <Para>
3324
3325 <ProgramListing>
3326 Baz1 :: forall a. Eq a => a -> a -> Baz
3327 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
3328 </ProgramListing>
3329
3330 </Para>
3331
3332 <Para>
3333 But when pattern matching on <Function>Baz1</Function> the matched values can be compared
3334 for equality, and when pattern matching on <Function>Baz2</Function> the first matched
3335 value can be converted to a string (as well as applying the function to it).
3336 So this program is legal:
3337 </Para>
3338
3339 <Para>
3340
3341 <ProgramListing>
3342   f :: Baz -> String
3343   f (Baz1 p q) | p == q    = "Yes"
3344                | otherwise = "No"
3345   f (Baz1 v fn)            = show (fn v)
3346 </ProgramListing>
3347
3348 </Para>
3349
3350 <Para>
3351 Operationally, in a dictionary-passing implementation, the
3352 constructors <Function>Baz1</Function> and <Function>Baz2</Function> must store the
3353 dictionaries for <Literal>Eq</Literal> and <Literal>Show</Literal> respectively, and
3354 extract it on pattern matching.
3355 </Para>
3356
3357 <Para>
3358 Notice the way that the syntax fits smoothly with that used for
3359 universal quantification earlier.
3360 </Para>
3361
3362 </Sect2>
3363
3364 <Sect2>
3365 <Title>Restrictions</Title>
3366
3367 <Para>
3368 There are several restrictions on the ways in which existentially-quantified
3369 constructors can be use.
3370 </Para>
3371
3372 <Para>
3373
3374 <ItemizedList>
3375 <ListItem>
3376
3377 <Para>
3378  When pattern matching, each pattern match introduces a new,
3379 distinct, type for each existential type variable.  These types cannot
3380 be unified with any other type, nor can they escape from the scope of
3381 the pattern match.  For example, these fragments are incorrect:
3382
3383
3384 <ProgramListing>
3385 f1 (MkFoo a f) = a
3386 </ProgramListing>
3387
3388
3389 Here, the type bound by <Function>MkFoo</Function> "escapes", because <Literal>a</Literal>
3390 is the result of <Function>f1</Function>.  One way to see why this is wrong is to
3391 ask what type <Function>f1</Function> has:
3392
3393
3394 <ProgramListing>
3395   f1 :: Foo -> a             -- Weird!
3396 </ProgramListing>
3397
3398
3399 What is this "<Literal>a</Literal>" in the result type? Clearly we don't mean
3400 this:
3401
3402
3403 <ProgramListing>
3404   f1 :: forall a. Foo -> a   -- Wrong!
3405 </ProgramListing>
3406
3407
3408 The original program is just plain wrong.  Here's another sort of error
3409
3410
3411 <ProgramListing>
3412   f2 (Baz1 a b) (Baz1 p q) = a==q
3413 </ProgramListing>
3414
3415
3416 It's ok to say <Literal>a==b</Literal> or <Literal>p==q</Literal>, but
3417 <Literal>a==q</Literal> is wrong because it equates the two distinct types arising
3418 from the two <Function>Baz1</Function> constructors.
3419
3420
3421 </Para>
3422 </ListItem>
3423 <ListItem>
3424
3425 <Para>
3426 You can't pattern-match on an existentially quantified
3427 constructor in a <Literal>let</Literal> or <Literal>where</Literal> group of
3428 bindings. So this is illegal:
3429
3430
3431 <ProgramListing>
3432   f3 x = a==b where { Baz1 a b = x }
3433 </ProgramListing>
3434
3435
3436 You can only pattern-match
3437 on an existentially-quantified constructor in a <Literal>case</Literal> expression or
3438 in the patterns of a function definition.
3439
3440 The reason for this restriction is really an implementation one.
3441 Type-checking binding groups is already a nightmare without
3442 existentials complicating the picture.  Also an existential pattern
3443 binding at the top level of a module doesn't make sense, because it's
3444 not clear how to prevent the existentially-quantified type "escaping".
3445 So for now, there's a simple-to-state restriction.  We'll see how
3446 annoying it is.
3447
3448 </Para>
3449 </ListItem>
3450 <ListItem>
3451
3452 <Para>
3453 You can't use existential quantification for <Literal>newtype</Literal>
3454 declarations.  So this is illegal:
3455
3456
3457 <ProgramListing>
3458   newtype T = forall a. Ord a => MkT a
3459 </ProgramListing>
3460
3461
3462 Reason: a value of type <Literal>T</Literal> must be represented as a pair
3463 of a dictionary for <Literal>Ord t</Literal> and a value of type <Literal>t</Literal>.
3464 That contradicts the idea that <Literal>newtype</Literal> should have no
3465 concrete representation.  You can get just the same efficiency and effect
3466 by using <Literal>data</Literal> instead of <Literal>newtype</Literal>.  If there is no
3467 overloading involved, then there is more of a case for allowing
3468 an existentially-quantified <Literal>newtype</Literal>, because the <Literal>data</Literal>
3469 because the <Literal>data</Literal> version does carry an implementation cost,
3470 but single-field existentially quantified constructors aren't much
3471 use.  So the simple restriction (no existential stuff on <Literal>newtype</Literal>)
3472 stands, unless there are convincing reasons to change it.
3473
3474
3475 </Para>
3476 </ListItem>
3477 <ListItem>
3478
3479 <Para>
3480  You can't use <Literal>deriving</Literal> to define instances of a
3481 data type with existentially quantified data constructors.
3482
3483 Reason: in most cases it would not make sense. For example:&num;
3484
3485 <ProgramListing>
3486 data T = forall a. MkT [a] deriving( Eq )
3487 </ProgramListing>
3488
3489 To derive <Literal>Eq</Literal> in the standard way we would need to have equality
3490 between the single component of two <Function>MkT</Function> constructors:
3491
3492 <ProgramListing>
3493 instance Eq T where
3494   (MkT a) == (MkT b) = ???
3495 </ProgramListing>
3496
3497 But <VarName>a</VarName> and <VarName>b</VarName> have distinct types, and so can't be compared.
3498 It's just about possible to imagine examples in which the derived instance
3499 would make sense, but it seems altogether simpler simply to prohibit such
3500 declarations.  Define your own instances!
3501 </Para>
3502 </ListItem>
3503
3504 </ItemizedList>
3505
3506 </Para>
3507
3508 </Sect2>
3509
3510 </Sect1>
3511
3512 <Sect1 id="sec-assertions">
3513 <Title>Assertions
3514 <IndexTerm><Primary>Assertions</Primary></IndexTerm>
3515 </Title>
3516
3517 <Para>
3518 If you want to make use of assertions in your standard Haskell code, you
3519 could define a function like the following:
3520 </Para>
3521
3522 <Para>
3523
3524 <ProgramListing>
3525 assert :: Bool -> a -> a
3526 assert False x = error "assertion failed!"
3527 assert _     x = x
3528 </ProgramListing>
3529
3530 </Para>
3531
3532 <Para>
3533 which works, but gives you back a less than useful error message --
3534 an assertion failed, but which and where?
3535 </Para>
3536
3537 <Para>
3538 One way out is to define an extended <Function>assert</Function> function which also
3539 takes a descriptive string to include in the error message and
3540 perhaps combine this with the use of a pre-processor which inserts
3541 the source location where <Function>assert</Function> was used.
3542 </Para>
3543
3544 <Para>
3545 Ghc offers a helping hand here, doing all of this for you. For every
3546 use of <Function>assert</Function> in the user's source:
3547 </Para>
3548
3549 <Para>
3550
3551 <ProgramListing>
3552 kelvinToC :: Double -> Double
3553 kelvinToC k = assert (k &amp;gt;= 0.0) (k+273.15)
3554 </ProgramListing>
3555
3556 </Para>
3557
3558 <Para>
3559 Ghc will rewrite this to also include the source location where the
3560 assertion was made,
3561 </Para>
3562
3563 <Para>
3564
3565 <ProgramListing>
3566 assert pred val ==> assertError "Main.hs|15" pred val
3567 </ProgramListing>
3568
3569 </Para>
3570
3571 <Para>
3572 The rewrite is only performed by the compiler when it spots
3573 applications of <Function>Exception.assert</Function>, so you can still define and
3574 use your own versions of <Function>assert</Function>, should you so wish. If not,
3575 import <Literal>Exception</Literal> to make use <Function>assert</Function> in your code.
3576 </Para>
3577
3578 <Para>
3579 To have the compiler ignore uses of assert, use the compiler option
3580 <Option>-fignore-asserts</Option>. <IndexTerm><Primary>-fignore-asserts option</Primary></IndexTerm> That is,
3581 expressions of the form <Literal>assert pred e</Literal> will be rewritten to <Literal>e</Literal>.
3582 </Para>
3583
3584 <Para>
3585 Assertion failures can be caught, see the documentation for the
3586 Hugs/GHC Exception library for information of how.
3587 </Para>
3588
3589 </Sect1>
3590
3591 <Sect1 id="scoped-type-variables">
3592 <Title>Scoped Type Variables
3593 </Title>
3594
3595 <Para>
3596 A <Emphasis>pattern type signature</Emphasis> can introduce a <Emphasis>scoped type
3597 variable</Emphasis>.  For example
3598 </Para>
3599
3600 <Para>
3601
3602 <ProgramListing>
3603 f (xs::[a]) = ys ++ ys
3604            where
3605               ys :: [a]
3606               ys = reverse xs
3607 </ProgramListing>
3608
3609 </Para>
3610
3611 <Para>
3612 The pattern <Literal>(xs::[a])</Literal> includes a type signature for <VarName>xs</VarName>.
3613 This brings the type variable <Literal>a</Literal> into scope; it scopes over
3614 all the patterns and right hand sides for this equation for <Function>f</Function>.
3615 In particular, it is in scope at the type signature for <VarName>y</VarName>.
3616 </Para>
3617
3618 <Para>
3619 At ordinary type signatures, such as that for <VarName>ys</VarName>, any type variables
3620 mentioned in the type signature <Emphasis>that are not in scope</Emphasis> are
3621 implicitly universally quantified.  (If there are no type variables in
3622 scope, all type variables mentioned in the signature are universally
3623 quantified, which is just as in Haskell 98.)  In this case, since <VarName>a</VarName>
3624 is in scope, it is not universally quantified, so the type of <VarName>ys</VarName> is
3625 the same as that of <VarName>xs</VarName>.  In Haskell 98 it is not possible to declare
3626 a type for <VarName>ys</VarName>; a major benefit of scoped type variables is that
3627 it becomes possible to do so.
3628 </Para>
3629
3630 <Para>
3631 Scoped type variables are implemented in both GHC and Hugs.  Where the
3632 implementations differ from the specification below, those differences
3633 are noted.
3634 </Para>
3635
3636 <Para>
3637 So much for the basic idea.  Here are the details.
3638 </Para>
3639
3640 <Sect2>
3641 <Title>Scope and implicit quantification</Title>
3642
3643 <Para>
3644
3645 <ItemizedList>
3646 <ListItem>
3647
3648 <Para>
3649  All the type variables mentioned in the patterns for a single
3650 function definition equation, that are not already in scope,
3651 are brought into scope by the patterns.  We describe this set as
3652 the <Emphasis>type variables bound by the equation</Emphasis>.
3653
3654 </Para>
3655 </ListItem>
3656 <ListItem>
3657
3658 <Para>
3659  The type variables thus brought into scope may be mentioned
3660 in ordinary type signatures or pattern type signatures anywhere within
3661 their scope.
3662
3663 </Para>
3664 </ListItem>
3665 <ListItem>
3666
3667 <Para>
3668  In ordinary type signatures, any type variable mentioned in the
3669 signature that is in scope is <Emphasis>not</Emphasis> universally quantified.
3670
3671 </Para>
3672 </ListItem>
3673 <ListItem>
3674
3675 <Para>
3676  Ordinary type signatures do not bring any new type variables
3677 into scope (except in the type signature itself!). So this is illegal:
3678
3679
3680 <ProgramListing>
3681   f :: a -> a
3682   f x = x::a
3683 </ProgramListing>
3684
3685
3686 It's illegal because <VarName>a</VarName> is not in scope in the body of <Function>f</Function>,
3687 so the ordinary signature <Literal>x::a</Literal> is equivalent to <Literal>x::forall a.a</Literal>;
3688 and that is an incorrect typing.
3689
3690 </Para>
3691 </ListItem>
3692 <ListItem>
3693
3694 <Para>
3695  There is no implicit universal quantification on pattern type
3696 signatures, nor may one write an explicit <Literal>forall</Literal> type in a pattern
3697 type signature.  The pattern type signature is a monotype.
3698
3699 </Para>
3700 </ListItem>
3701 <ListItem>
3702
3703 <Para>
3704
3705 The type variables in the head of a <Literal>class</Literal> or <Literal>instance</Literal> declaration
3706 scope over the methods defined in the <Literal>where</Literal> part.  For example:
3707
3708
3709 <ProgramListing>
3710   class C a where
3711     op :: [a] -> a
3712
3713     op xs = let ys::[a]
3714                 ys = reverse xs
3715             in
3716             head ys
3717 </ProgramListing>
3718
3719
3720 (Not implemented in Hugs yet, Dec 98).
3721 </Para>
3722 </ListItem>
3723
3724 </ItemizedList>
3725
3726 </Para>
3727
3728 </Sect2>
3729
3730 <Sect2>
3731 <Title>Polymorphism</Title>
3732
3733 <Para>
3734
3735 <ItemizedList>
3736 <ListItem>
3737
3738 <Para>
3739  Pattern type signatures are completely orthogonal to ordinary, separate
3740 type signatures.  The two can be used independently or together.  There is
3741 no scoping associated with the names of the type variables in a separate type signature.
3742
3743
3744 <ProgramListing>
3745    f :: [a] -> [a]
3746    f (xs::[b]) = reverse xs
3747 </ProgramListing>
3748
3749
3750 </Para>
3751 </ListItem>
3752 <ListItem>
3753
3754 <Para>
3755  The function must be polymorphic in the type variables
3756 bound by all its equations.  Operationally, the type variables bound
3757 by one equation must not:
3758
3759
3760 <ItemizedList>
3761 <ListItem>
3762
3763 <Para>
3764  Be unified with a type (such as <Literal>Int</Literal>, or <Literal>[a]</Literal>).
3765 </Para>
3766 </ListItem>
3767 <ListItem>
3768
3769 <Para>
3770  Be unified with a type variable free in the environment.
3771 </Para>
3772 </ListItem>
3773 <ListItem>
3774
3775 <Para>
3776  Be unified with each other.  (They may unify with the type variables
3777 bound by another equation for the same function, of course.)
3778 </Para>
3779 </ListItem>
3780
3781 </ItemizedList>
3782
3783
3784 For example, the following all fail to type check:
3785
3786
3787 <ProgramListing>
3788   f (x::a) (y::b) = [x,y]       -- a unifies with b
3789
3790   g (x::a) = x + 1::Int         -- a unifies with Int
3791
3792   h x = let k (y::a) = [x,y]    -- a is free in the
3793         in k x                  -- environment
3794
3795   k (x::a) True    = ...        -- a unifies with Int
3796   k (x::Int) False = ...
3797
3798   w :: [b] -> [b]
3799   w (x::a) = x                  -- a unifies with [b]
3800 </ProgramListing>
3801
3802
3803 </Para>
3804 </ListItem>
3805 <ListItem>
3806
3807 <Para>
3808  The pattern-bound type variable may, however, be constrained
3809 by the context of the principal type, thus:
3810
3811
3812 <ProgramListing>
3813   f (x::a) (y::a) = x+y*2
3814 </ProgramListing>
3815
3816
3817 gets the inferred type: <Literal>forall a. Num a =&gt; a -&gt; a -&gt; a</Literal>.
3818 </Para>
3819 </ListItem>
3820
3821 </ItemizedList>
3822
3823 </Para>
3824
3825 </Sect2>
3826
3827 <Sect2>
3828 <Title>Result type signatures</Title>
3829
3830 <Para>
3831
3832 <ItemizedList>
3833 <ListItem>
3834
3835 <Para>
3836  The result type of a function can be given a signature,
3837 thus:
3838
3839
3840 <ProgramListing>
3841   f (x::a) :: [a] = [x,x,x]
3842 </ProgramListing>
3843
3844
3845 The final <Literal>:: [a]</Literal> after all the patterns gives a signature to the
3846 result type.  Sometimes this is the only way of naming the type variable
3847 you want:
3848
3849
3850 <ProgramListing>
3851   f :: Int -> [a] -> [a]
3852   f n :: ([a] -> [a]) = let g (x::a, y::a) = (y,x)
3853                         in \xs -> map g (reverse xs `zip` xs)
3854 </ProgramListing>
3855
3856
3857 </Para>
3858 </ListItem>
3859
3860 </ItemizedList>
3861
3862 </Para>
3863
3864 <Para>
3865 Result type signatures are not yet implemented in Hugs.
3866 </Para>
3867
3868 </Sect2>
3869
3870 <Sect2>
3871 <Title>Pattern signatures on other constructs</Title>
3872
3873 <Para>
3874
3875 <ItemizedList>
3876 <ListItem>
3877
3878 <Para>
3879  A pattern type signature can be on an arbitrary sub-pattern, not
3880 just on a variable:
3881
3882
3883 <ProgramListing>
3884   f ((x,y)::(a,b)) = (y,x) :: (b,a)
3885 </ProgramListing>
3886
3887
3888 </Para>
3889 </ListItem>
3890 <ListItem>
3891
3892 <Para>
3893  Pattern type signatures, including the result part, can be used
3894 in lambda abstractions:
3895
3896
3897 <ProgramListing>
3898   (\ (x::a, y) :: a -> x)
3899 </ProgramListing>
3900
3901
3902 Type variables bound by these patterns must be polymorphic in
3903 the sense defined above.
3904 For example:
3905
3906
3907 <ProgramListing>
3908   f1 (x::c) = f1 x      -- ok
3909   f2 = \(x::c) -> f2 x  -- not ok
3910 </ProgramListing>
3911
3912
3913 Here, <Function>f1</Function> is OK, but <Function>f2</Function> is not, because <VarName>c</VarName> gets unified
3914 with a type variable free in the environment, in this
3915 case, the type of <Function>f2</Function>, which is in the environment when
3916 the lambda abstraction is checked.
3917
3918 </Para>
3919 </ListItem>
3920 <ListItem>
3921
3922 <Para>
3923  Pattern type signatures, including the result part, can be used
3924 in <Literal>case</Literal> expressions:
3925
3926
3927 <ProgramListing>
3928   case e of { (x::a, y) :: a -> x }
3929 </ProgramListing>
3930
3931
3932 The pattern-bound type variables must, as usual,
3933 be polymorphic in the following sense: each case alternative,
3934 considered as a lambda abstraction, must be polymorphic.
3935 Thus this is OK:
3936
3937
3938 <ProgramListing>
3939   case (True,False) of { (x::a, y) -> x }
3940 </ProgramListing>
3941
3942
3943 Even though the context is that of a pair of booleans,
3944 the alternative itself is polymorphic.  Of course, it is
3945 also OK to say:
3946
3947
3948 <ProgramListing>
3949   case (True,False) of { (x::Bool, y) -> x }
3950 </ProgramListing>
3951
3952
3953 </Para>
3954 </ListItem>
3955 <ListItem>
3956
3957 <Para>
3958 To avoid ambiguity, the type after the &ldquo;<Literal>::</Literal>&rdquo; in a result
3959 pattern signature on a lambda or <Literal>case</Literal> must be atomic (i.e. a single
3960 token or a parenthesised type of some sort).  To see why,
3961 consider how one would parse this:
3962
3963
3964 <ProgramListing>
3965   \ x :: a -> b -> x
3966 </ProgramListing>
3967
3968
3969 </Para>
3970 </ListItem>
3971 <ListItem>
3972
3973 <Para>
3974  Pattern type signatures that bind new type variables
3975 may not be used in pattern bindings at all.
3976 So this is illegal:
3977
3978
3979 <ProgramListing>
3980   f x = let (y, z::a) = x in ...
3981 </ProgramListing>
3982
3983
3984 But these are OK, because they do not bind fresh type variables:
3985
3986
3987 <ProgramListing>
3988   f1 x            = let (y, z::Int) = x in ...
3989   f2 (x::(Int,a)) = let (y, z::a)   = x in ...
3990 </ProgramListing>
3991
3992
3993 However a single variable is considered a degenerate function binding,
3994 rather than a degerate pattern binding, so this is permitted, even
3995 though it binds a type variable:
3996
3997
3998 <ProgramListing>
3999   f :: (b->b) = \(x::b) -> x
4000 </ProgramListing>
4001
4002
4003 </Para>
4004 </ListItem>
4005
4006 </ItemizedList>
4007
4008 Such degnerate function bindings do not fall under the monomorphism
4009 restriction.  Thus:
4010 </Para>
4011
4012 <Para>
4013
4014 <ProgramListing>
4015   g :: a -> a -> Bool = \x y. x==y
4016 </ProgramListing>
4017
4018 </Para>
4019
4020 <Para>
4021 Here <Function>g</Function> has type <Literal>forall a. Eq a =&gt; a -&gt; a -&gt; Bool</Literal>, just as if
4022 <Function>g</Function> had a separate type signature.  Lacking a type signature, <Function>g</Function>
4023 would get a monomorphic type.
4024 </Para>
4025
4026 </Sect2>
4027
4028 <Sect2>
4029 <Title>Existentials</Title>
4030
4031 <Para>
4032
4033 <ItemizedList>
4034 <ListItem>
4035
4036 <Para>
4037  Pattern type signatures can bind existential type variables.
4038 For example:
4039
4040
4041 <ProgramListing>
4042   data T = forall a. MkT [a]
4043
4044   f :: T -> T
4045   f (MkT [t::a]) = MkT t3
4046                  where
4047                    t3::[a] = [t,t,t]
4048 </ProgramListing>
4049
4050
4051 </Para>
4052 </ListItem>
4053
4054 </ItemizedList>
4055
4056 </Para>
4057
4058 </Sect2>
4059
4060 </Sect1>
4061
4062 <Sect1 id="pragmas">
4063 <Title>Pragmas
4064 </Title>
4065
4066 <Para>
4067 GHC supports several pragmas, or instructions to the compiler placed
4068 in the source code.  Pragmas don't affect the meaning of the program,
4069 but they might affect the efficiency of the generated code.
4070 </Para>
4071
4072 <Sect2 id="inline-pragma">
4073 <Title>INLINE pragma
4074
4075 <IndexTerm><Primary>INLINE pragma</Primary></IndexTerm>
4076 <IndexTerm><Primary>pragma, INLINE</Primary></IndexTerm></Title>
4077
4078 <Para>
4079 GHC (with <Option>-O</Option>, as always) tries to inline (or &ldquo;unfold&rdquo;)
4080 functions/values that are &ldquo;small enough,&rdquo; thus avoiding the call
4081 overhead and possibly exposing other more-wonderful optimisations.
4082 </Para>
4083
4084 <Para>
4085 You will probably see these unfoldings (in Core syntax) in your
4086 interface files.
4087 </Para>
4088
4089 <Para>
4090 Normally, if GHC decides a function is &ldquo;too expensive&rdquo; to inline, it
4091 will not do so, nor will it export that unfolding for other modules to
4092 use.
4093 </Para>
4094
4095 <Para>
4096 The sledgehammer you can bring to bear is the
4097 <Literal>INLINE</Literal><IndexTerm><Primary>INLINE pragma</Primary></IndexTerm> pragma, used thusly:
4098
4099 <ProgramListing>
4100 key_function :: Int -> String -> (Bool, Double)
4101
4102 #ifdef __GLASGOW_HASKELL__
4103 {-# INLINE key_function #-}
4104 #endif
4105 </ProgramListing>
4106
4107 (You don't need to do the C pre-processor carry-on unless you're going
4108 to stick the code through HBC&mdash;it doesn't like <Literal>INLINE</Literal> pragmas.)
4109 </Para>
4110
4111 <Para>
4112 The major effect of an <Literal>INLINE</Literal> pragma is to declare a function's
4113 &ldquo;cost&rdquo; to be very low.  The normal unfolding machinery will then be
4114 very keen to inline it.
4115 </Para>
4116
4117 <Para>
4118 An <Literal>INLINE</Literal> pragma for a function can be put anywhere its type
4119 signature could be put.
4120 </Para>
4121
4122 <Para>
4123 <Literal>INLINE</Literal> pragmas are a particularly good idea for the
4124 <Literal>then</Literal>/<Literal>return</Literal> (or <Literal>bind</Literal>/<Literal>unit</Literal>) functions in a monad.
4125 For example, in GHC's own <Literal>UniqueSupply</Literal> monad code, we have:
4126
4127 <ProgramListing>
4128 #ifdef __GLASGOW_HASKELL__
4129 {-# INLINE thenUs #-}
4130 {-# INLINE returnUs #-}
4131 #endif
4132 </ProgramListing>
4133
4134 </Para>
4135
4136 </Sect2>
4137
4138 <Sect2 id="noinline-pragma">
4139 <Title>NOINLINE pragma
4140 </Title>
4141
4142 <Para>
4143 <IndexTerm><Primary>NOINLINE pragma</Primary></IndexTerm>
4144 <IndexTerm><Primary>pragma, NOINLINE</Primary></IndexTerm>
4145 </Para>
4146
4147 <Para>
4148 The <Literal>NOINLINE</Literal> pragma does exactly what you'd expect: it stops the
4149 named function from being inlined by the compiler.  You shouldn't ever
4150 need to do this, unless you're very cautious about code size.
4151 </Para>
4152
4153 </Sect2>
4154
4155 <Sect2 id="specialize-pragma">
4156 <Title>SPECIALIZE pragma
4157 </Title>
4158
4159 <Para>
4160 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
4161 <IndexTerm><Primary>pragma, SPECIALIZE</Primary></IndexTerm>
4162 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
4163 </Para>
4164
4165 <Para>
4166 (UK spelling also accepted.)  For key overloaded functions, you can
4167 create extra versions (NB: more code space) specialised to particular
4168 types.  Thus, if you have an overloaded function:
4169 </Para>
4170
4171 <Para>
4172
4173 <ProgramListing>
4174 hammeredLookup :: Ord key => [(key, value)] -> key -> value
4175 </ProgramListing>
4176
4177 </Para>
4178
4179 <Para>
4180 If it is heavily used on lists with <Literal>Widget</Literal> keys, you could
4181 specialise it as follows:
4182
4183 <ProgramListing>
4184 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
4185 </ProgramListing>
4186
4187 </Para>
4188
4189 <Para>
4190 To get very fancy, you can also specify a named function to use for
4191 the specialised value, by adding <Literal>= blah</Literal>, as in:
4192
4193 <ProgramListing>
4194 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
4195 </ProgramListing>
4196
4197 It's <Emphasis>Your Responsibility</Emphasis> to make sure that <Function>blah</Function> really
4198 behaves as a specialised version of <Function>hammeredLookup</Function>!!!
4199 </Para>
4200
4201 <Para>
4202 NOTE: the <Literal>=blah</Literal> feature isn't implemented in GHC 4.xx.
4203 </Para>
4204
4205 <Para>
4206 An example in which the <Literal>= blah</Literal> form will Win Big:
4207
4208 <ProgramListing>
4209 toDouble :: Real a => a -> Double
4210 toDouble = fromRational . toRational
4211
4212 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
4213 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
4214 </ProgramListing>
4215
4216 The <Function>i2d</Function> function is virtually one machine instruction; the
4217 default conversion&mdash;via an intermediate <Literal>Rational</Literal>&mdash;is obscenely
4218 expensive by comparison.
4219 </Para>
4220
4221 <Para>
4222 By using the US spelling, your <Literal>SPECIALIZE</Literal> pragma will work with
4223 HBC, too.  Note that HBC doesn't support the <Literal>= blah</Literal> form.
4224 </Para>
4225
4226 <Para>
4227 A <Literal>SPECIALIZE</Literal> pragma for a function can be put anywhere its type
4228 signature could be put.
4229 </Para>
4230
4231 </Sect2>
4232
4233 <Sect2 id="specialize-instance-pragma">
4234 <Title>SPECIALIZE instance pragma
4235 </Title>
4236
4237 <Para>
4238 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
4239 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
4240 Same idea, except for instance declarations.  For example:
4241
4242 <ProgramListing>
4243 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
4244
4245 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
4246 </ProgramListing>
4247
4248 Compatible with HBC, by the way.
4249 </Para>
4250
4251 </Sect2>
4252
4253 <Sect2 id="line-pragma">
4254 <Title>LINE pragma
4255 </Title>
4256
4257 <Para>
4258 <IndexTerm><Primary>LINE pragma</Primary></IndexTerm>
4259 <IndexTerm><Primary>pragma, LINE</Primary></IndexTerm>
4260 </Para>
4261
4262 <Para>
4263 This pragma is similar to C's <Literal>&num;line</Literal> pragma, and is mainly for use in
4264 automatically generated Haskell code.  It lets you specify the line
4265 number and filename of the original code; for example
4266 </Para>
4267
4268 <Para>
4269
4270 <ProgramListing>
4271 {-# LINE 42 "Foo.vhs" #-}
4272 </ProgramListing>
4273
4274 </Para>
4275
4276 <Para>
4277 if you'd generated the current file from something called <Filename>Foo.vhs</Filename>
4278 and this line corresponds to line 42 in the original.  GHC will adjust
4279 its error messages to refer to the line/file named in the <Literal>LINE</Literal>
4280 pragma.
4281 </Para>
4282
4283 </Sect2>
4284
4285 <Sect2>
4286 <Title>RULES pragma</Title>
4287
4288 <Para>
4289 The RULES pragma lets you specify rewrite rules.  It is described in
4290 <XRef LinkEnd="rewrite-rules">.
4291 </Para>
4292
4293 </Sect2>
4294
4295 </Sect1>
4296
4297 <Sect1 id="rewrite-rules">
4298 <Title>Rewrite rules
4299
4300 <IndexTerm><Primary>RULES pagma</Primary></IndexTerm>
4301 <IndexTerm><Primary>pragma, RULES</Primary></IndexTerm>
4302 <IndexTerm><Primary>rewrite rules</Primary></IndexTerm></Title>
4303
4304 <Para>
4305 The programmer can specify rewrite rules as part of the source program
4306 (in a pragma).  GHC applies these rewrite rules wherever it can.
4307 </Para>
4308
4309 <Para>
4310 Here is an example:
4311
4312 <ProgramListing>
4313   {-# RULES
4314         "map/map"       forall f g xs. map f (map g xs) = map (f.g) xs
4315   #-}
4316 </ProgramListing>
4317
4318 </Para>
4319
4320 <Sect2>
4321 <Title>Syntax</Title>
4322
4323 <Para>
4324 From a syntactic point of view:
4325
4326 <ItemizedList>
4327 <ListItem>
4328
4329 <Para>
4330  Each rule has a name, enclosed in double quotes.  The name itself has
4331 no significance at all.  It is only used when reporting how many times the rule fired.
4332 </Para>
4333 </ListItem>
4334 <ListItem>
4335
4336 <Para>
4337  There may be zero or more rules in a <Literal>RULES</Literal> pragma.
4338 </Para>
4339 </ListItem>
4340 <ListItem>
4341
4342 <Para>
4343  Layout applies in a <Literal>RULES</Literal> pragma.  Currently no new indentation level
4344 is set, so you must lay out your rules starting in the same column as the
4345 enclosing definitions.
4346 </Para>
4347 </ListItem>
4348 <ListItem>
4349
4350 <Para>
4351  Each variable mentioned in a rule must either be in scope (e.g. <Function>map</Function>),
4352 or bound by the <Literal>forall</Literal> (e.g. <Function>f</Function>, <Function>g</Function>, <Function>xs</Function>).  The variables bound by
4353 the <Literal>forall</Literal> are called the <Emphasis>pattern</Emphasis> variables.  They are separated
4354 by spaces, just like in a type <Literal>forall</Literal>.
4355 </Para>
4356 </ListItem>
4357 <ListItem>
4358
4359 <Para>
4360  A pattern variable may optionally have a type signature.
4361 If the type of the pattern variable is polymorphic, it <Emphasis>must</Emphasis> have a type signature.
4362 For example, here is the <Literal>foldr/build</Literal> rule:
4363
4364 <ProgramListing>
4365 "fold/build"  forall k z (g::forall b. (a->b->b) -> b -> b) .
4366               foldr k z (build g) = g k z
4367 </ProgramListing>
4368
4369 Since <Function>g</Function> has a polymorphic type, it must have a type signature.
4370
4371 </Para>
4372 </ListItem>
4373 <ListItem>
4374
4375 <Para>
4376 The left hand side of a rule must consist of a top-level variable applied
4377 to arbitrary expressions.  For example, this is <Emphasis>not</Emphasis> OK:
4378
4379 <ProgramListing>
4380 "wrong1"   forall e1 e2.  case True of { True -> e1; False -> e2 } = e1
4381 "wrong2"   forall f.      f True = True
4382 </ProgramListing>
4383
4384 In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong1"</Literal>, the LHS has a pattern variable
4385 in the head.
4386 </Para>
4387 </ListItem>
4388 <ListItem>
4389
4390 <Para>
4391  A rule does not need to be in the same module as (any of) the
4392 variables it mentions, though of course they need to be in scope.
4393 </Para>
4394 </ListItem>
4395 <ListItem>
4396
4397 <Para>
4398  Rules are automatically exported from a module, just as instance declarations are.
4399 </Para>
4400 </ListItem>
4401
4402 </ItemizedList>
4403
4404 </Para>
4405
4406 </Sect2>
4407
4408 <Sect2>
4409 <Title>Semantics</Title>
4410
4411 <Para>
4412 From a semantic point of view:
4413
4414 <ItemizedList>
4415 <ListItem>
4416
4417 <Para>
4418 Rules are only applied if you use the <Option>-O</Option> flag.
4419 </Para>
4420 </ListItem>
4421
4422 <ListItem>
4423 <Para>
4424  Rules are regarded as left-to-right rewrite rules.
4425 When GHC finds an expression that is a substitution instance of the LHS
4426 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
4427 By "a substitution instance" we mean that the LHS can be made equal to the
4428 expression by substituting for the pattern variables.
4429
4430 </Para>
4431 </ListItem>
4432 <ListItem>
4433
4434 <Para>
4435  The LHS and RHS of a rule are typechecked, and must have the
4436 same type.
4437
4438 </Para>
4439 </ListItem>
4440 <ListItem>
4441
4442 <Para>
4443  GHC makes absolutely no attempt to verify that the LHS and RHS
4444 of a rule have the same meaning.  That is undecideable in general, and
4445 infeasible in most interesting cases.  The responsibility is entirely the programmer's!
4446
4447 </Para>
4448 </ListItem>
4449 <ListItem>
4450
4451 <Para>
4452  GHC makes no attempt to make sure that the rules are confluent or
4453 terminating.  For example:
4454
4455 <ProgramListing>
4456   "loop"        forall x,y.  f x y = f y x
4457 </ProgramListing>
4458
4459 This rule will cause the compiler to go into an infinite loop.
4460
4461 </Para>
4462 </ListItem>
4463 <ListItem>
4464
4465 <Para>
4466  If more than one rule matches a call, GHC will choose one arbitrarily to apply.
4467
4468 </Para>
4469 </ListItem>
4470 <ListItem>
4471 <Para>
4472  GHC currently uses a very simple, syntactic, matching algorithm
4473 for matching a rule LHS with an expression.  It seeks a substitution
4474 which makes the LHS and expression syntactically equal modulo alpha
4475 conversion.  The pattern (rule), but not the expression, is eta-expanded if
4476 necessary.  (Eta-expanding the epression can lead to laziness bugs.)
4477 But not beta conversion (that's called higher-order matching).
4478 </Para>
4479
4480 <Para>
4481 Matching is carried out on GHC's intermediate language, which includes
4482 type abstractions and applications.  So a rule only matches if the
4483 types match too.  See <XRef LinkEnd="rule-spec"> below.
4484 </Para>
4485 </ListItem>
4486 <ListItem>
4487
4488 <Para>
4489  GHC keeps trying to apply the rules as it optimises the program.
4490 For example, consider:
4491
4492 <ProgramListing>
4493   let s = map f
4494       t = map g
4495   in
4496   s (t xs)
4497 </ProgramListing>
4498
4499 The expression <Literal>s (t xs)</Literal> does not match the rule <Literal>"map/map"</Literal>, but GHC
4500 will substitute for <VarName>s</VarName> and <VarName>t</VarName>, giving an expression which does match.
4501 If <VarName>s</VarName> or <VarName>t</VarName> was (a) used more than once, and (b) large or a redex, then it would
4502 not be substituted, and the rule would not fire.
4503
4504 </Para>
4505 </ListItem>
4506 <ListItem>
4507
4508 <Para>
4509  In the earlier phases of compilation, GHC inlines <Emphasis>nothing
4510 that appears on the LHS of a rule</Emphasis>, because once you have substituted
4511 for something you can't match against it (given the simple minded
4512 matching).  So if you write the rule
4513
4514 <ProgramListing>
4515         "map/map"       forall f,g.  map f . map g = map (f.g)
4516 </ProgramListing>
4517
4518 this <Emphasis>won't</Emphasis> match the expression <Literal>map f (map g xs)</Literal>.
4519 It will only match something written with explicit use of ".".
4520 Well, not quite.  It <Emphasis>will</Emphasis> match the expression
4521
4522 <ProgramListing>
4523 wibble f g xs
4524 </ProgramListing>
4525
4526 where <Function>wibble</Function> is defined:
4527
4528 <ProgramListing>
4529 wibble f g = map f . map g
4530 </ProgramListing>
4531
4532 because <Function>wibble</Function> will be inlined (it's small).
4533
4534 Later on in compilation, GHC starts inlining even things on the
4535 LHS of rules, but still leaves the rules enabled.  This inlining
4536 policy is controlled by the per-simplification-pass flag <Option>-finline-phase</Option><Emphasis>n</Emphasis>.
4537
4538 </Para>
4539 </ListItem>
4540 <ListItem>
4541
4542 <Para>
4543  All rules are implicitly exported from the module, and are therefore
4544 in force in any module that imports the module that defined the rule, directly
4545 or indirectly.  (That is, if A imports B, which imports C, then C's rules are
4546 in force when compiling A.)  The situation is very similar to that for instance
4547 declarations.
4548 </Para>
4549 </ListItem>
4550
4551 </ItemizedList>
4552
4553 </Para>
4554
4555 </Sect2>
4556
4557 <Sect2>
4558 <Title>List fusion</Title>
4559
4560 <Para>
4561 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
4562 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
4563 intermediate list should be eliminated entirely.
4564 </Para>
4565
4566 <Para>
4567 The following are good producers:
4568
4569 <ItemizedList>
4570 <ListItem>
4571
4572 <Para>
4573  List comprehensions
4574 </Para>
4575 </ListItem>
4576 <ListItem>
4577
4578 <Para>
4579  Enumerations of <Literal>Int</Literal> and <Literal>Char</Literal> (e.g. <Literal>['a'..'z']</Literal>).
4580 </Para>
4581 </ListItem>
4582 <ListItem>
4583
4584 <Para>
4585  Explicit lists (e.g. <Literal>[True, False]</Literal>)
4586 </Para>
4587 </ListItem>
4588 <ListItem>
4589
4590 <Para>
4591  The cons constructor (e.g <Literal>3:4:[]</Literal>)
4592 </Para>
4593 </ListItem>
4594 <ListItem>
4595
4596 <Para>
4597  <Function>++</Function>
4598 </Para>
4599 </ListItem>
4600 <ListItem>
4601
4602 <Para>
4603  <Function>map</Function>
4604 </Para>
4605 </ListItem>
4606 <ListItem>
4607
4608 <Para>
4609  <Function>filter</Function>
4610 </Para>
4611 </ListItem>
4612 <ListItem>
4613
4614 <Para>
4615  <Function>iterate</Function>, <Function>repeat</Function>
4616 </Para>
4617 </ListItem>
4618 <ListItem>
4619
4620 <Para>
4621  <Function>zip</Function>, <Function>zipWith</Function>
4622 </Para>
4623 </ListItem>
4624
4625 </ItemizedList>
4626
4627 </Para>
4628
4629 <Para>
4630 The following are good consumers:
4631
4632 <ItemizedList>
4633 <ListItem>
4634
4635 <Para>
4636  List comprehensions
4637 </Para>
4638 </ListItem>
4639 <ListItem>
4640
4641 <Para>
4642  <Function>array</Function> (on its second argument)
4643 </Para>
4644 </ListItem>
4645 <ListItem>
4646
4647 <Para>
4648  <Function>length</Function>
4649 </Para>
4650 </ListItem>
4651 <ListItem>
4652
4653 <Para>
4654  <Function>++</Function> (on its first argument)
4655 </Para>
4656 </ListItem>
4657 <ListItem>
4658
4659 <Para>
4660  <Function>map</Function>
4661 </Para>
4662 </ListItem>
4663 <ListItem>
4664
4665 <Para>
4666  <Function>filter</Function>
4667 </Para>
4668 </ListItem>
4669 <ListItem>
4670
4671 <Para>
4672  <Function>concat</Function>
4673 </Para>
4674 </ListItem>
4675 <ListItem>
4676
4677 <Para>
4678  <Function>unzip</Function>, <Function>unzip2</Function>, <Function>unzip3</Function>, <Function>unzip4</Function>
4679 </Para>
4680 </ListItem>
4681 <ListItem>
4682
4683 <Para>
4684  <Function>zip</Function>, <Function>zipWith</Function> (but on one argument only; if both are good producers, <Function>zip</Function>
4685 will fuse with one but not the other)
4686 </Para>
4687 </ListItem>
4688 <ListItem>
4689
4690 <Para>
4691  <Function>partition</Function>
4692 </Para>
4693 </ListItem>
4694 <ListItem>
4695
4696 <Para>
4697  <Function>head</Function>
4698 </Para>
4699 </ListItem>
4700 <ListItem>
4701
4702 <Para>
4703  <Function>and</Function>, <Function>or</Function>, <Function>any</Function>, <Function>all</Function>
4704 </Para>
4705 </ListItem>
4706 <ListItem>
4707
4708 <Para>
4709  <Function>sequence&lowbar;</Function>
4710 </Para>
4711 </ListItem>
4712 <ListItem>
4713
4714 <Para>
4715  <Function>msum</Function>
4716 </Para>
4717 </ListItem>
4718 <ListItem>
4719
4720 <Para>
4721  <Function>sortBy</Function>
4722 </Para>
4723 </ListItem>
4724
4725 </ItemizedList>
4726
4727 </Para>
4728
4729 <Para>
4730 So, for example, the following should generate no intermediate lists:
4731
4732 <ProgramListing>
4733 array (1,10) [(i,i*i) | i &#60;- map (+ 1) [0..9]]
4734 </ProgramListing>
4735
4736 </Para>
4737
4738 <Para>
4739 This list could readily be extended; if there are Prelude functions that you use
4740 a lot which are not included, please tell us.
4741 </Para>
4742
4743 <Para>
4744 If you want to write your own good consumers or producers, look at the
4745 Prelude definitions of the above functions to see how to do so.
4746 </Para>
4747
4748 </Sect2>
4749
4750 <Sect2 id="rule-spec">
4751 <Title>Specialisation
4752 </Title>
4753
4754 <Para>
4755 Rewrite rules can be used to get the same effect as a feature
4756 present in earlier version of GHC:
4757
4758 <ProgramListing>
4759   {-# SPECIALIZE fromIntegral :: Int8 -> Int16 = int8ToInt16 #-}
4760 </ProgramListing>
4761
4762 This told GHC to use <Function>int8ToInt16</Function> instead of <Function>fromIntegral</Function> whenever
4763 the latter was called with type <Literal>Int8 -&gt; Int16</Literal>.  That is, rather than
4764 specialising the original definition of <Function>fromIntegral</Function> the programmer is
4765 promising that it is safe to use <Function>int8ToInt16</Function> instead.
4766 </Para>
4767
4768 <Para>
4769 This feature is no longer in GHC.  But rewrite rules let you do the
4770 same thing:
4771
4772 <ProgramListing>
4773 {-# RULES
4774   "fromIntegral/Int8/Int16" fromIntegral = int8ToInt16
4775 #-}
4776 </ProgramListing>
4777
4778 This slightly odd-looking rule instructs GHC to replace <Function>fromIntegral</Function>
4779 by <Function>int8ToInt16</Function> <Emphasis>whenever the types match</Emphasis>.  Speaking more operationally,
4780 GHC adds the type and dictionary applications to get the typed rule
4781
4782 <ProgramListing>
4783 forall (d1::Integral Int8) (d2::Num Int16) .
4784         fromIntegral Int8 Int16 d1 d2 = int8ToInt16
4785 </ProgramListing>
4786
4787 What is more,
4788 this rule does not need to be in the same file as fromIntegral,
4789 unlike the <Literal>SPECIALISE</Literal> pragmas which currently do (so that they
4790 have an original definition available to specialise).
4791 </Para>
4792
4793 </Sect2>
4794
4795 <Sect2>
4796 <Title>Controlling what's going on</Title>
4797
4798 <Para>
4799
4800 <ItemizedList>
4801 <ListItem>
4802
4803 <Para>
4804  Use <Option>-ddump-rules</Option> to see what transformation rules GHC is using.
4805 </Para>
4806 </ListItem>
4807 <ListItem>
4808
4809 <Para>
4810  Use <Option>-ddump-simpl-stats</Option> to see what rules are being fired.
4811 If you add <Option>-dppr-debug</Option> you get a more detailed listing.
4812 </Para>
4813 </ListItem>
4814 <ListItem>
4815
4816 <Para>
4817  The defintion of (say) <Function>build</Function> in <FileName>PrelBase.lhs</FileName> looks llike this:
4818
4819 <ProgramListing>
4820         build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
4821         {-# INLINE build #-}
4822         build g = g (:) []
4823 </ProgramListing>
4824
4825 Notice the <Literal>INLINE</Literal>!  That prevents <Literal>(:)</Literal> from being inlined when compiling
4826 <Literal>PrelBase</Literal>, so that an importing module will &ldquo;see&rdquo; the <Literal>(:)</Literal>, and can
4827 match it on the LHS of a rule.  <Literal>INLINE</Literal> prevents any inlining happening
4828 in the RHS of the <Literal>INLINE</Literal> thing.  I regret the delicacy of this.
4829
4830 </Para>
4831 </ListItem>
4832 <ListItem>
4833
4834 <Para>
4835  In <Filename>ghc/lib/std/PrelBase.lhs</Filename> look at the rules for <Function>map</Function> to
4836 see how to write rules that will do fusion and yet give an efficient
4837 program even if fusion doesn't happen.  More rules in <Filename>PrelList.lhs</Filename>.
4838 </Para>
4839 </ListItem>
4840
4841 </ItemizedList>
4842
4843 </Para>
4844
4845 </Sect2>
4846
4847 </Sect1>