[project @ 2000-04-07 13:40:15 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
118 <xref linkend="book-hslibs">.
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
1243 <Function>ST</Function> monad, is described in <xref
1244 linkend="sec-ST">.
1245 </Para>
1246
1247 </Sect1>
1248
1249 <Sect1 id="glasgow-prim-arrays">
1250 <Title>Primitive arrays, mutable and otherwise
1251 </Title>
1252
1253 <Para>
1254 <IndexTerm><Primary>primitive arrays (Glasgow extension)</Primary></IndexTerm>
1255 <IndexTerm><Primary>arrays, primitive (Glasgow extension)</Primary></IndexTerm>
1256 </Para>
1257
1258 <Para>
1259 GHC knows about quite a few flavours of Large Swathes of Bytes.
1260 </Para>
1261
1262 <Para>
1263 First, GHC distinguishes between primitive arrays of (boxed) Haskell
1264 objects (type <Literal>Array&num; obj</Literal>) and primitive arrays of bytes (type
1265 <Literal>ByteArray&num;</Literal>).
1266 </Para>
1267
1268 <Para>
1269 Second, it distinguishes between&hellip;
1270 <VariableList>
1271
1272 <VarListEntry>
1273 <Term>Immutable:</Term>
1274 <ListItem>
1275 <Para>
1276 Arrays that do not change (as with &ldquo;standard&rdquo; Haskell arrays); you
1277 can only read from them.  Obviously, they do not need the care and
1278 attention of the state-transformer monad.
1279 </Para>
1280 </ListItem>
1281 </VarListEntry>
1282 <VarListEntry>
1283 <Term>Mutable:</Term>
1284 <ListItem>
1285 <Para>
1286 Arrays that may be changed or &ldquo;mutated.&rdquo;  All the operations on them
1287 live within the state-transformer monad and the updates happen
1288 <Emphasis>in-place</Emphasis>.
1289 </Para>
1290 </ListItem>
1291 </VarListEntry>
1292 <VarListEntry>
1293 <Term>&ldquo;Static&rdquo; (in C land):</Term>
1294 <ListItem>
1295 <Para>
1296 A C routine may pass an <Literal>Addr&num;</Literal> pointer back into Haskell land.  There
1297 are then primitive operations with which you may merrily grab values
1298 over in C land, by indexing off the &ldquo;static&rdquo; pointer.
1299 </Para>
1300 </ListItem>
1301 </VarListEntry>
1302 <VarListEntry>
1303 <Term>&ldquo;Stable&rdquo; pointers:</Term>
1304 <ListItem>
1305 <Para>
1306 If, for some reason, you wish to hand a Haskell pointer (i.e.,
1307 <Emphasis>not</Emphasis> an unboxed value) to a C routine, you first make the
1308 pointer &ldquo;stable,&rdquo; so that the garbage collector won't forget that it
1309 exists.  That is, GHC provides a safe way to pass Haskell pointers to
1310 C.
1311 </Para>
1312
1313 <Para>
1314 Please see <XRef LinkEnd="glasgow-stablePtrs"> for more details.
1315 </Para>
1316 </ListItem>
1317 </VarListEntry>
1318 <VarListEntry>
1319 <Term>&ldquo;Foreign objects&rdquo;:</Term>
1320 <ListItem>
1321 <Para>
1322 A &ldquo;foreign object&rdquo; is a safe way to pass an external object (a
1323 C-allocated pointer, say) to Haskell and have Haskell do the Right
1324 Thing when it no longer references the object.  So, for example, C
1325 could pass a large bitmap over to Haskell and say &ldquo;please free this
1326 memory when you're done with it.&rdquo;
1327 </Para>
1328
1329 <Para>
1330 Please see <XRef LinkEnd="glasgow-foreignObjs"> for more details.
1331 </Para>
1332 </ListItem>
1333 </VarListEntry>
1334 </VariableList>
1335 </Para>
1336
1337 <Para>
1338 The libraries documentatation gives more details on all these
1339 &ldquo;primitive array&rdquo; types and the operations on them.
1340 </Para>
1341
1342 </Sect1>
1343
1344 <Sect1 id="glasgow-ccalls">
1345 <Title>Calling&nbsp;C directly from Haskell
1346 </Title>
1347
1348 <Para>
1349 <IndexTerm><Primary>C calls (Glasgow extension)</Primary></IndexTerm>
1350 <IndexTerm><Primary>&lowbar;ccall&lowbar; (Glasgow extension)</Primary></IndexTerm>
1351 <IndexTerm><Primary>&lowbar;casm&lowbar; (Glasgow extension)</Primary></IndexTerm>
1352 </Para>
1353
1354 <Para>
1355 GOOD ADVICE: Because this stuff is not Entirely Stable as far as names
1356 and things go, you would be well-advised to keep your C-callery
1357 corraled in a few modules, rather than sprinkled all over your code.
1358 It will then be quite easy to update later on.
1359 </Para>
1360
1361 <Sect2 id="ccall-intro">
1362 <Title><Function>&lowbar;ccall&lowbar;</Function> and <Function>&lowbar;casm&lowbar;</Function>: an introduction
1363 </Title>
1364
1365 <Para>
1366 The simplest way to use a simple C function
1367 </Para>
1368
1369 <Para>
1370
1371 <ProgramListing>
1372 double fooC( FILE *in, char c, int i, double d, unsigned int u )
1373 </ProgramListing>
1374
1375 </Para>
1376
1377 <Para>
1378 is to provide a Haskell wrapper:
1379 </Para>
1380
1381 <Para>
1382
1383 <ProgramListing>
1384 fooH :: Char -> Int -> Double -> Word -> IO Double
1385 fooH c i d w = _ccall_ fooC (&ldquo;stdin&rdquo;::Addr) c i d w
1386 </ProgramListing>
1387
1388 </Para>
1389
1390 <Para>
1391 The function <Function>fooH</Function> unbox all of its arguments, call the C
1392 function <Function>fooC</Function> and box the corresponding arguments.
1393 </Para>
1394
1395 <Para>
1396 One of the annoyances about <Function>&lowbar;ccall&lowbar;</Function>s is when the C types don't quite
1397 match the Haskell compiler's ideas.  For this, the <Function>&lowbar;casm&lowbar;</Function> variant
1398 may be just the ticket (NB: <Emphasis>no chance</Emphasis> of such code going
1399 through a native-code generator):
1400 </Para>
1401
1402 <Para>
1403
1404 <ProgramListing>
1405 import Addr
1406 import CString
1407
1408 oldGetEnv name
1409   = _casm_ &ldquo;%r = getenv((char *) %0);&rdquo; name >>= \ litstring ->
1410     return (
1411         if (litstring == nullAddr) then
1412             Left ("Fail:oldGetEnv:"++name)
1413         else
1414             Right (unpackCString litstring)
1415     )
1416 </ProgramListing>
1417
1418 </Para>
1419
1420 <Para>
1421 The first literal-literal argument to a <Function>&lowbar;casm&lowbar;</Function> is like a <Function>printf</Function>
1422 format: <Literal>&percnt;r</Literal> is replaced with the &ldquo;result,&rdquo; <Literal>&percnt;0</Literal>&ndash;<Literal>&percnt;n-1</Literal> are
1423 replaced with the 1st&ndash;nth arguments.  As you can see above, it is an
1424 easy way to do simple C&nbsp;casting.  Everything said about <Function>&lowbar;ccall&lowbar;</Function> goes
1425 for <Function>&lowbar;casm&lowbar;</Function> as well.
1426 </Para>
1427
1428 <Para>
1429 The use of <Function>&lowbar;casm&lowbar;</Function> in your code does pose a problem to the compiler
1430 when it comes to generating an interface file for a freshly compiled
1431 module. Included in an interface file is the unfolding (if any) of a
1432 declaration. However, if a declaration's unfolding happens to contain
1433 a <Function>&lowbar;casm&lowbar;</Function>, its unfolding will <Emphasis>not</Emphasis> be emitted into the interface
1434 file even if it qualifies by all the other criteria. The reason why
1435 the compiler prevents this from happening is that unfolding <Function>&lowbar;casm&lowbar;</Function>s
1436 into an interface file unduly constrains how code that import your
1437 module have to be compiled. If an imported declaration is unfolded and
1438 it contains a <Function>&lowbar;casm&lowbar;</Function>, you now have to be using a compiler backend
1439 capable of dealing with it (i.e., the C compiler backend). If you are
1440 using the C compiler backend, the unfolded <Function>&lowbar;casm&lowbar;</Function> may still cause you
1441 problems since the C code snippet it contains may mention CPP symbols
1442 that were in scope when compiling the original module are not when
1443 compiling the importing module.
1444 </Para>
1445
1446 <Para>
1447 If you're willing to put up with the drawbacks of doing cross-module
1448 inlining of C code (GHC - A Better C Compiler :-), the option
1449 <Option>-funfold-casms-in-hi-file</Option> will turn off the default behaviour.
1450 <IndexTerm><Primary>-funfold-casms-in-hi-file option</Primary></IndexTerm>
1451 </Para>
1452
1453 </Sect2>
1454
1455 <Sect2 id="glasgow-literal-literals">
1456 <Title>Literal-literals</Title>
1457
1458 <Para>
1459 <IndexTerm><Primary>Literal-literals</Primary></IndexTerm>
1460 The literal-literal argument to <Function>&lowbar;casm&lowbar;</Function> can be made use of separately
1461 from the <Function>&lowbar;casm&lowbar;</Function> construct itself. Indeed, we've already used it:
1462 </Para>
1463
1464 <Para>
1465
1466 <ProgramListing>
1467 fooH :: Char -> Int -> Double -> Word -> IO Double
1468 fooH c i d w = _ccall_ fooC (&ldquo;stdin&rdquo;::Addr) c i d w
1469 </ProgramListing>
1470
1471 </Para>
1472
1473 <Para>
1474 The first argument that's passed to <Function>fooC</Function> is given as a literal-literal,
1475 that is, a literal chunk of C code that will be inserted into the generated
1476 <Filename>.hc</Filename> code at the right place.
1477 </Para>
1478
1479 <Para>
1480 A literal-literal is restricted to having a type that's an instance of
1481 the <Literal>CCallable</Literal> class, see <XRef LinkEnd="ccall-gotchas">
1482 for more information.
1483 </Para>
1484
1485 <Para>
1486 Notice that literal-literals are by their very nature unfriendly to
1487 native code generators, so exercise judgement about whether or not to
1488 make use of them in your code.
1489 </Para>
1490
1491 </Sect2>
1492
1493 <Sect2 id="glasgow-foreign-headers">
1494 <Title>Using function headers
1495 </Title>
1496
1497 <Para>
1498 <IndexTerm><Primary>C calls, function headers</Primary></IndexTerm>
1499 </Para>
1500
1501 <Para>
1502 When generating C (using the <Option>-fvia-C</Option> directive), one can assist the
1503 C compiler in detecting type errors by using the <Command>-&num;include</Command> directive
1504 to provide <Filename>.h</Filename> files containing function headers.
1505 </Para>
1506
1507 <Para>
1508 For example,
1509 </Para>
1510
1511 <Para>
1512
1513 <ProgramListing>
1514 typedef unsigned long *StgForeignObj;
1515 typedef long StgInt;
1516
1517 void          initialiseEFS (StgInt size);
1518 StgInt        terminateEFS (void);
1519 StgForeignObj emptyEFS(void);
1520 StgForeignObj updateEFS (StgForeignObj a, StgInt i, StgInt x);
1521 StgInt        lookupEFS (StgForeignObj a, StgInt i);
1522 </ProgramListing>
1523
1524 </Para>
1525
1526 <Para>
1527 You can find appropriate definitions for <Literal>StgInt</Literal>, <Literal>StgForeignObj</Literal>,
1528 etc using <Command>gcc</Command> on your architecture by consulting
1529 <Filename>ghc/includes/StgTypes.h</Filename>.  The following table summarises the
1530 relationship between Haskell types and C types.
1531 </Para>
1532
1533 <Para>
1534
1535 <InformalTable>
1536 <TGroup Cols="2">
1537 <ColSpec Align="Left" Colsep="0">
1538 <ColSpec Align="Left" Colsep="0">
1539 <TBody>
1540 <Row>
1541 <Entry><Emphasis>C type name</Emphasis> </Entry>
1542 <Entry> <Emphasis>Haskell Type</Emphasis> </Entry>
1543 </Row>
1544
1545 <Row>
1546 <Entry>
1547 <Literal>StgChar</Literal> </Entry>
1548 <Entry> <Literal>Char&num;</Literal> </Entry>
1549 </Row>
1550 <Row>
1551 <Entry>
1552 <Literal>StgInt</Literal> </Entry>
1553 <Entry> <Literal>Int&num;</Literal> </Entry>
1554 </Row>
1555 <Row>
1556 <Entry>
1557 <Literal>StgWord</Literal> </Entry>
1558 <Entry> <Literal>Word&num;</Literal> </Entry>
1559 </Row>
1560 <Row>
1561 <Entry>
1562 <Literal>StgAddr</Literal> </Entry>
1563 <Entry> <Literal>Addr&num;</Literal> </Entry>
1564 </Row>
1565 <Row>
1566 <Entry>
1567 <Literal>StgFloat</Literal> </Entry>
1568 <Entry> <Literal>Float&num;</Literal> </Entry>
1569 </Row>
1570 <Row>
1571 <Entry>
1572 <Literal>StgDouble</Literal> </Entry>
1573 <Entry> <Literal>Double&num;</Literal> </Entry>
1574 </Row>
1575 <Row>
1576 <Entry>
1577 <Literal>StgArray</Literal> </Entry>
1578 <Entry> <Literal>Array&num;</Literal> </Entry>
1579 </Row>
1580 <Row>
1581 <Entry>
1582 <Literal>StgByteArray</Literal> </Entry>
1583 <Entry> <Literal>ByteArray&num;</Literal> </Entry>
1584 </Row>
1585 <Row>
1586 <Entry>
1587 <Literal>StgArray</Literal> </Entry>
1588 <Entry> <Literal>MutableArray&num;</Literal> </Entry>
1589 </Row>
1590 <Row>
1591 <Entry>
1592 <Literal>StgByteArray</Literal> </Entry>
1593 <Entry> <Literal>MutableByteArray&num;</Literal> </Entry>
1594 </Row>
1595 <Row>
1596 <Entry>
1597 <Literal>StgStablePtr</Literal> </Entry>
1598 <Entry> <Literal>StablePtr&num;</Literal> </Entry>
1599 </Row>
1600 <Row>
1601 <Entry>
1602 <Literal>StgForeignObj</Literal> </Entry>
1603 <Entry> <Literal>ForeignObj&num;</Literal></Entry>
1604 </Row>
1605 </TBody>
1606
1607 </TGroup>
1608 </InformalTable>
1609 </Para>
1610
1611 <Para>
1612 Note that this approach is only <Emphasis>essential</Emphasis> for returning
1613 <Literal>float</Literal>s (or if <Literal>sizeof(int) != sizeof(int *)</Literal> on your
1614 architecture) but is a Good Thing for anyone who cares about writing
1615 solid code.  You're crazy not to do it.
1616 </Para>
1617
1618 </Sect2>
1619
1620 <Sect2 id="glasgow-stablePtrs">
1621 <Title>Subverting automatic unboxing with &ldquo;stable pointers&rdquo;
1622 </Title>
1623
1624 <Para>
1625 <IndexTerm><Primary>stable pointers (Glasgow extension)</Primary></IndexTerm>
1626 </Para>
1627
1628 <Para>
1629 The arguments of a <Function>&lowbar;ccall&lowbar;</Function> automatically unboxed before the
1630 call.  There are two reasons why this is usually the Right Thing to
1631 do:
1632 </Para>
1633
1634 <Para>
1635
1636 <ItemizedList>
1637 <ListItem>
1638
1639 <Para>
1640 C is a strict language: it would be excessively tedious to pass
1641 unevaluated arguments and require the C programmer to force their
1642 evaluation before using them.
1643
1644 </Para>
1645 </ListItem>
1646 <ListItem>
1647
1648 <Para>
1649  Boxed values are stored on the Haskell heap and may be moved
1650 within the heap if a garbage collection occurs&mdash;that is, pointers
1651 to boxed objects are not <Emphasis>stable</Emphasis>.
1652 </Para>
1653 </ListItem>
1654
1655 </ItemizedList>
1656
1657 </Para>
1658
1659 <Para>
1660 It is possible to subvert the unboxing process by creating a &ldquo;stable
1661 pointer&rdquo; to a value and passing the stable pointer instead.  For
1662 example, to pass/return an integer lazily to C functions <Function>storeC</Function> and
1663 <Function>fetchC</Function> might write:
1664 </Para>
1665
1666 <Para>
1667
1668 <ProgramListing>
1669 storeH :: Int -> IO ()
1670 storeH x = makeStablePtr x              >>= \ stable_x ->
1671            _ccall_ storeC stable_x
1672
1673 fetchH :: IO Int
1674 fetchH x = _ccall_ fetchC               >>= \ stable_x ->
1675            deRefStablePtr stable_x      >>= \ x ->
1676            freeStablePtr stable_x       >>
1677            return x
1678 </ProgramListing>
1679
1680 </Para>
1681
1682 <Para>
1683 The garbage collector will refrain from throwing a stable pointer away
1684 until you explicitly call one of the following from C or Haskell.
1685 </Para>
1686
1687 <Para>
1688
1689 <ProgramListing>
1690 void freeStablePointer( StgStablePtr stablePtrToToss )
1691 freeStablePtr :: StablePtr a -> IO ()
1692 </ProgramListing>
1693
1694 </Para>
1695
1696 <Para>
1697 As with the use of <Function>free</Function> in C programs, GREAT CARE SHOULD BE
1698 EXERCISED to ensure these functions are called at the right time: too
1699 early and you get dangling references (and, if you're lucky, an error
1700 message from the runtime system); too late and you get space leaks.
1701 </Para>
1702
1703 <Para>
1704 And to force evaluation of the argument within <Function>fooC</Function>, one would
1705 call one of the following C functions (according to type of argument).
1706 </Para>
1707
1708 <Para>
1709
1710 <ProgramListing>
1711 void     performIO  ( StgStablePtr stableIndex /* StablePtr s (IO ()) */ );
1712 StgInt   enterInt   ( StgStablePtr stableIndex /* StablePtr s Int */ );
1713 StgFloat enterFloat ( StgStablePtr stableIndex /* StablePtr s Float */ );
1714 </ProgramListing>
1715
1716 </Para>
1717
1718 <Para>
1719 <IndexTerm><Primary>performIO</Primary></IndexTerm>
1720 <IndexTerm><Primary>enterInt</Primary></IndexTerm>
1721 <IndexTerm><Primary>enterFloat</Primary></IndexTerm>
1722 </Para>
1723
1724 <Para>
1725 Nota Bene: <Function>&lowbar;ccall&lowbar;GC&lowbar;</Function><IndexTerm><Primary>&lowbar;ccall&lowbar;GC&lowbar;</Primary></IndexTerm> must be used if any of
1726 these functions are used.
1727 </Para>
1728
1729 </Sect2>
1730
1731 <Sect2 id="glasgow-foreignObjs">
1732 <Title>Foreign objects: pointing outside the Haskell heap
1733 </Title>
1734
1735 <Para>
1736 <IndexTerm><Primary>foreign objects (Glasgow extension)</Primary></IndexTerm>
1737 </Para>
1738
1739 <Para>
1740 There are two types that GHC programs can use to reference
1741 (heap-allocated) objects outside the Haskell world: <Literal>Addr</Literal> and
1742 <Literal>ForeignObj</Literal>.
1743 </Para>
1744
1745 <Para>
1746 If you use <Literal>Addr</Literal>, it is up to you to the programmer to arrange
1747 allocation and deallocation of the objects.
1748 </Para>
1749
1750 <Para>
1751 If you use <Literal>ForeignObj</Literal>, GHC's garbage collector will call upon the
1752 user-supplied <Emphasis>finaliser</Emphasis> function to free the object when the
1753 Haskell world no longer can access the object.  (An object is
1754 associated with a finaliser function when the abstract
1755 Haskell type <Literal>ForeignObj</Literal> is created). The finaliser function is
1756 expressed in C, and is passed as argument the object:
1757 </Para>
1758
1759 <Para>
1760
1761 <ProgramListing>
1762 void foreignFinaliser ( StgForeignObj fo )
1763 </ProgramListing>
1764
1765 </Para>
1766
1767 <Para>
1768 when the Haskell world can no longer access the object.  Since
1769 <Literal>ForeignObj</Literal>s only get released when a garbage collection occurs, we
1770 provide ways of triggering a garbage collection from within C and from
1771 within Haskell.
1772 </Para>
1773
1774 <Para>
1775
1776 <ProgramListing>
1777 void GarbageCollect()
1778 performGC :: IO ()
1779 </ProgramListing>
1780
1781 </Para>
1782
1783 <Para>
1784 More information on the programmers' interface to <Literal>ForeignObj</Literal> can be
1785 found in the library documentation.
1786 </Para>
1787
1788 </Sect2>
1789
1790 <Sect2 id="glasgow-avoiding-monads">
1791 <Title>Avoiding monads
1792 </Title>
1793
1794 <Para>
1795 <IndexTerm><Primary>C calls to `pure C'</Primary></IndexTerm>
1796 <IndexTerm><Primary>unsafePerformIO</Primary></IndexTerm>
1797 </Para>
1798
1799 <Para>
1800 The <Function>&lowbar;ccall&lowbar;</Function> construct is part of the <Literal>IO</Literal> monad because 9 out of 10
1801 uses will be to call imperative functions with side effects such as
1802 <Function>printf</Function>.  Use of the monad ensures that these operations happen in a
1803 predictable order in spite of laziness and compiler optimisations.
1804 </Para>
1805
1806 <Para>
1807 To avoid having to be in the monad to call a C function, it is
1808 possible to use <Function>unsafePerformIO</Function>, which is available from the
1809 <Literal>IOExts</Literal> module.  There are three situations where one might like to
1810 call a C function from outside the IO world:
1811 </Para>
1812
1813 <Para>
1814
1815 <ItemizedList>
1816 <ListItem>
1817
1818 <Para>
1819 Calling a function with no side-effects:
1820
1821 <ProgramListing>
1822 atan2d :: Double -> Double -> Double
1823 atan2d y x = unsafePerformIO (_ccall_ atan2d y x)
1824
1825 sincosd :: Double -> (Double, Double)
1826 sincosd x = unsafePerformIO $ do
1827         da &#60;- newDoubleArray (0, 1)
1828         _casm_ &ldquo;sincosd( %0, &amp;((double *)%1[0]), &amp;((double *)%1[1]) );&rdquo; x da
1829         s &#60;- readDoubleArray da 0
1830         c &#60;- readDoubleArray da 1
1831         return (s, c)
1832 </ProgramListing>
1833
1834
1835 </Para>
1836 </ListItem>
1837 <ListItem>
1838
1839 <Para>
1840  Calling a set of functions which have side-effects but which can
1841 be used in a purely functional manner.
1842
1843 For example, an imperative implementation of a purely functional
1844 lookup-table might be accessed using the following functions.
1845
1846
1847 <ProgramListing>
1848 empty  :: EFS x
1849 update :: EFS x -> Int -> x -> EFS x
1850 lookup :: EFS a -> Int -> a
1851
1852 empty = unsafePerformIO (_ccall_ emptyEFS)
1853
1854 update a i x = unsafePerformIO $
1855         makeStablePtr x         >>= \ stable_x ->
1856         _ccall_ updateEFS a i stable_x
1857
1858 lookup a i = unsafePerformIO $
1859         _ccall_ lookupEFS a i   >>= \ stable_x ->
1860         deRefStablePtr stable_x
1861 </ProgramListing>
1862
1863
1864 You will almost always want to use <Literal>ForeignObj</Literal>s with this.
1865
1866 </Para>
1867 </ListItem>
1868 <ListItem>
1869
1870 <Para>
1871  Calling a side-effecting function even though the results will
1872 be unpredictable.  For example the <Function>trace</Function> function is defined by:
1873
1874
1875 <ProgramListing>
1876 trace :: String -> a -> a
1877 trace string expr
1878   = unsafePerformIO (
1879         ((_ccall_ PreTraceHook sTDERR{-msg-}):: IO ())  >>
1880         fputs sTDERR string                             >>
1881         ((_ccall_ PostTraceHook sTDERR{-msg-}):: IO ()) >>
1882         return expr )
1883   where
1884     sTDERR = (&ldquo;stderr&rdquo; :: Addr)
1885 </ProgramListing>
1886
1887
1888 (This kind of use is not highly recommended&mdash;it is only really
1889 useful in debugging code.)
1890 </Para>
1891 </ListItem>
1892
1893 </ItemizedList>
1894
1895 </Para>
1896
1897 </Sect2>
1898
1899 <Sect2 id="ccall-gotchas">
1900 <Title>C-calling &ldquo;gotchas&rdquo; checklist
1901 </Title>
1902
1903 <Para>
1904 <IndexTerm><Primary>C call dangers</Primary></IndexTerm>
1905 <IndexTerm><Primary>CCallable</Primary></IndexTerm>
1906 <IndexTerm><Primary>CReturnable</Primary></IndexTerm>
1907 </Para>
1908
1909 <Para>
1910 And some advice, too.
1911 </Para>
1912
1913 <Para>
1914
1915 <ItemizedList>
1916 <ListItem>
1917
1918 <Para>
1919  For modules that use <Function>&lowbar;ccall&lowbar;</Function>s, etc., compile with
1920 <Option>-fvia-C</Option>.<IndexTerm><Primary>-fvia-C option</Primary></IndexTerm> You don't have to, but you should.
1921
1922 Also, use the <Option>-&num;include "prototypes.h"</Option> flag (hack) to inform the C
1923 compiler of the fully-prototyped types of all the C functions you
1924 call.  (<XRef LinkEnd="glasgow-foreign-headers"> says more about this&hellip;)
1925
1926 This scheme is the <Emphasis>only</Emphasis> way that you will get <Emphasis>any</Emphasis>
1927 typechecking of your <Function>&lowbar;ccall&lowbar;</Function>s.  (It shouldn't be that way, but&hellip;).
1928 GHC will pass the flag <Option>-Wimplicit</Option> to <Command>gcc</Command> so that you'll get warnings
1929 if any <Function>&lowbar;ccall&lowbar;</Function>ed functions have no prototypes.
1930
1931 </Para>
1932 </ListItem>
1933 <ListItem>
1934
1935 <Para>
1936 Try to avoid <Function>&lowbar;ccall&lowbar;</Function>s to C&nbsp;functions that take <Literal>float</Literal>
1937 arguments or return <Literal>float</Literal> results.  Reason: if you do, you will
1938 become entangled in (ANSI?) C's rules for when arguments/results are
1939 promoted to <Literal>doubles</Literal>.  It's a nightmare and just not worth it.
1940 Use <Literal>doubles</Literal> if possible.
1941
1942 If you do use <Literal>floats</Literal>, check and re-check that the right thing is
1943 happening.  Perhaps compile with <Option>-keep-hc-file-too</Option> and look at
1944 the intermediate C (<Function>.hc</Function>).
1945
1946 </Para>
1947 </ListItem>
1948 <ListItem>
1949
1950 <Para>
1951  The compiler uses two non-standard type-classes when
1952 type-checking the arguments and results of <Function>&lowbar;ccall&lowbar;</Function>: the arguments
1953 (respectively result) of <Function>&lowbar;ccall&lowbar;</Function> must be instances of the class
1954 <Literal>CCallable</Literal> (respectively <Literal>CReturnable</Literal>).  Both classes may be
1955 imported from the module <Literal>CCall</Literal>, but this should only be
1956 necessary if you want to define a new instance.  (Neither class
1957 defines any methods&mdash;their only function is to keep the
1958 type-checker happy.)
1959
1960 The type checker must be able to figure out just which of the
1961 C-callable/returnable types is being used.  If it can't, you have to
1962 add type signatures. For example,
1963
1964
1965 <ProgramListing>
1966 f x = _ccall_ foo x
1967 </ProgramListing>
1968
1969
1970 is not good enough, because the compiler can't work out what type <VarName>x</VarName>
1971 is, nor what type the <Function>&lowbar;ccall&lowbar;</Function> returns.  You have to write, say:
1972
1973
1974 <ProgramListing>
1975 f :: Int -> IO Double
1976 f x = _ccall_ foo x
1977 </ProgramListing>
1978
1979
1980 This table summarises the standard instances of these classes.
1981
1982 <InformalTable>
1983 <TGroup Cols="4">
1984 <ColSpec Align="Left" Colsep="0">
1985 <ColSpec Align="Left" Colsep="0">
1986 <ColSpec Align="Left" Colsep="0">
1987 <ColSpec Align="Left" Colsep="0">
1988 <TBody>
1989 <Row>
1990 <Entry><Emphasis>Type</Emphasis> </Entry>
1991 <Entry><Emphasis>CCallable</Emphasis></Entry>
1992 <Entry><Emphasis>CReturnable</Emphasis> </Entry>
1993 <Entry><Emphasis>Which is probably&hellip;</Emphasis> </Entry>
1994 </Row>
1995 <Row>
1996 <Entry>
1997 <Literal>Char</Literal> </Entry>
1998 <Entry> Yes </Entry>
1999 <Entry> Yes </Entry>
2000 <Entry> <Literal>unsigned char</Literal> </Entry>
2001 </Row>
2002 <Row>
2003 <Entry>
2004 <Literal>Int</Literal> </Entry>
2005 <Entry> Yes </Entry>
2006 <Entry> Yes </Entry>
2007 <Entry> <Literal>long int</Literal> </Entry>
2008 </Row>
2009 <Row>
2010 <Entry>
2011 <Literal>Word</Literal> </Entry>
2012 <Entry> Yes </Entry>
2013 <Entry> Yes </Entry>
2014 <Entry> <Literal>unsigned long int</Literal> </Entry>
2015 </Row>
2016 <Row>
2017 <Entry>
2018 <Literal>Addr</Literal> </Entry>
2019 <Entry> Yes </Entry>
2020 <Entry> Yes </Entry>
2021 <Entry> <Literal>void *</Literal> </Entry>
2022 </Row>
2023 <Row>
2024 <Entry>
2025 <Literal>Float</Literal> </Entry>
2026 <Entry> Yes </Entry>
2027 <Entry> Yes </Entry>
2028 <Entry> <Literal>float</Literal> </Entry>
2029 </Row>
2030 <Row>
2031 <Entry>
2032 <Literal>Double</Literal> </Entry>
2033 <Entry> Yes </Entry>
2034 <Entry> Yes </Entry>
2035 <Entry> <Literal>double</Literal> </Entry>
2036 </Row>
2037 <Row>
2038 <Entry>
2039 <Literal>()</Literal> </Entry>
2040 <Entry> No </Entry>
2041 <Entry> Yes </Entry>
2042 <Entry> <Literal>void</Literal> </Entry>
2043 </Row>
2044 <Row>
2045 <Entry>
2046 <Literal>[Char]</Literal> </Entry>
2047 <Entry> Yes </Entry>
2048 <Entry> No </Entry>
2049 <Entry> <Literal>char *</Literal> (null-terminated) </Entry>
2050 </Row>
2051 <Row>
2052 <Entry>
2053 <Literal>Array</Literal> </Entry>
2054 <Entry> Yes </Entry>
2055 <Entry> No </Entry>
2056 <Entry> <Literal>unsigned long *</Literal> </Entry>
2057 </Row>
2058 <Row>
2059 <Entry>
2060 <Literal>ByteArray</Literal> </Entry>
2061 <Entry> Yes </Entry>
2062 <Entry> No </Entry>
2063 <Entry> <Literal>unsigned long *</Literal> </Entry>
2064 </Row>
2065 <Row>
2066 <Entry>
2067 <Literal>MutableArray</Literal> </Entry>
2068 <Entry> Yes </Entry>
2069 <Entry> No </Entry>
2070 <Entry> <Literal>unsigned long *</Literal> </Entry>
2071 </Row>
2072 <Row>
2073 <Entry>
2074 <Literal>MutableByteArray</Literal> </Entry>
2075 <Entry> Yes </Entry>
2076 <Entry> No </Entry>
2077 <Entry> <Literal>unsigned long *</Literal> </Entry>
2078 </Row>
2079 <Row>
2080 <Entry>
2081 <Literal>State</Literal> </Entry>
2082 <Entry> Yes </Entry>
2083 <Entry> Yes </Entry>
2084 <Entry> nothing!</Entry>
2085 </Row>
2086 <Row>
2087 <Entry>
2088 <Literal>StablePtr</Literal> </Entry>
2089 <Entry> Yes </Entry>
2090 <Entry> Yes </Entry>
2091 <Entry> <Literal>unsigned long *</Literal> </Entry>
2092 </Row>
2093 <Row>
2094 <Entry>
2095 <Literal>ForeignObjs</Literal> </Entry>
2096 <Entry> Yes </Entry>
2097 <Entry> Yes </Entry>
2098 <Entry> see later </Entry>
2099 </Row>
2100
2101 </TBody>
2102
2103 </TGroup>
2104 </InformalTable>
2105
2106 Actually, the <Literal>Word</Literal> type is defined as being the same size as a
2107 pointer on the target architecture, which is <Emphasis>probably</Emphasis>
2108 <Literal>unsigned long int</Literal>.
2109
2110 The brave and careful programmer can add their own instances of these
2111 classes for the following types:
2112
2113
2114 <ItemizedList>
2115 <ListItem>
2116
2117 <Para>
2118 A <Emphasis>boxed-primitive</Emphasis> type may be made an instance of both
2119 <Literal>CCallable</Literal> and <Literal>CReturnable</Literal>.
2120
2121 A boxed primitive type is any data type with a
2122 single unary constructor with a single primitive argument.  For
2123 example, the following are all boxed primitive types:
2124
2125
2126 <ProgramListing>
2127 Int
2128 Double
2129 data XDisplay = XDisplay Addr#
2130 data EFS a = EFS# ForeignObj#
2131 </ProgramListing>
2132
2133
2134
2135 <ProgramListing>
2136 instance CCallable   (EFS a)
2137 instance CReturnable (EFS a)
2138 </ProgramListing>
2139
2140
2141 </Para>
2142 </ListItem>
2143 <ListItem>
2144
2145 <Para>
2146  Any datatype with a single nullary constructor may be made an
2147 instance of <Literal>CReturnable</Literal>.  For example:
2148
2149
2150 <ProgramListing>
2151 data MyVoid = MyVoid
2152 instance CReturnable MyVoid
2153 </ProgramListing>
2154
2155
2156 </Para>
2157 </ListItem>
2158 <ListItem>
2159
2160 <Para>
2161  As at version 2.09, <Literal>String</Literal> (i.e., <Literal>[Char]</Literal>) is still
2162 not a <Literal>CReturnable</Literal> type.
2163
2164 Also, the now-builtin type <Literal>PackedString</Literal> is neither
2165 <Literal>CCallable</Literal> nor <Literal>CReturnable</Literal>.  (But there are functions in
2166 the PackedString interface to let you get at the necessary bits&hellip;)
2167 </Para>
2168 </ListItem>
2169
2170 </ItemizedList>
2171
2172
2173 </Para>
2174 </ListItem>
2175 <ListItem>
2176
2177 <Para>
2178  The code-generator will complain if you attempt to use <Literal>&percnt;r</Literal> in
2179 a <Literal>&lowbar;casm&lowbar;</Literal> whose result type is <Literal>IO ()</Literal>; or if you don't use <Literal>&percnt;r</Literal>
2180 <Emphasis>precisely</Emphasis> once for any other result type.  These messages are
2181 supposed to be helpful and catch bugs&mdash;please tell us if they wreck
2182 your life.
2183
2184 </Para>
2185 </ListItem>
2186 <ListItem>
2187
2188 <Para>
2189  If you call out to C code which may trigger the Haskell garbage
2190 collector or create new threads (examples of this later&hellip;), then you
2191 must use the <Function>&lowbar;ccall&lowbar;GC&lowbar;</Function><IndexTerm><Primary>&lowbar;ccall&lowbar;GC&lowbar; primitive</Primary></IndexTerm> or
2192 <Function>&lowbar;casm&lowbar;GC&lowbar;</Function><IndexTerm><Primary>&lowbar;casm&lowbar;GC&lowbar; primitive</Primary></IndexTerm> variant of C-calls.  (This
2193 does not work with the native code generator&mdash;use <Option>-fvia-C</Option>.) This
2194 stuff is hairy with a capital H!
2195 </Para>
2196 </ListItem>
2197
2198 </ItemizedList>
2199
2200 </Para>
2201
2202 </Sect2>
2203
2204 </Sect1>
2205
2206 <Sect1 id="multi-param-type-classes">
2207 <Title>Multi-parameter type classes
2208 </Title>
2209
2210 <Para>
2211 This section documents GHC's implementation of multi-paramter type
2212 classes.  There's lots of background in the paper <ULink
2213 URL="http://research.microsoft.com/~simonpj/multi.ps.gz" >Type
2214 classes: exploring the design space</ULink > (Simon Peyton Jones, Mark
2215 Jones, Erik Meijer).
2216 </Para>
2217
2218 <Para>
2219 I'd like to thank people who reported shorcomings in the GHC 3.02
2220 implementation.  Our default decisions were all conservative ones, and
2221 the experience of these heroic pioneers has given useful concrete
2222 examples to support several generalisations.  (These appear below as
2223 design choices not implemented in 3.02.)
2224 </Para>
2225
2226 <Para>
2227 I've discussed these notes with Mark Jones, and I believe that Hugs
2228 will migrate towards the same design choices as I outline here.
2229 Thanks to him, and to many others who have offered very useful
2230 feedback.
2231 </Para>
2232
2233 <Sect2>
2234 <Title>Types</Title>
2235
2236 <Para>
2237 There are the following restrictions on the form of a qualified
2238 type:
2239 </Para>
2240
2241 <Para>
2242
2243 <ProgramListing>
2244   forall tv1..tvn (c1, ...,cn) => type
2245 </ProgramListing>
2246
2247 </Para>
2248
2249 <Para>
2250 (Here, I write the "foralls" explicitly, although the Haskell source
2251 language omits them; in Haskell 1.4, all the free type variables of an
2252 explicit source-language type signature are universally quantified,
2253 except for the class type variables in a class declaration.  However,
2254 in GHC, you can give the foralls if you want.  See <XRef LinkEnd="universal-quantification">).
2255 </Para>
2256
2257 <Para>
2258
2259 <OrderedList>
2260 <ListItem>
2261
2262 <Para>
2263  <Emphasis>Each universally quantified type variable
2264 <Literal>tvi</Literal> must be mentioned (i.e. appear free) in <Literal>type</Literal></Emphasis>.
2265
2266 The reason for this is that a value with a type that does not obey
2267 this restriction could not be used without introducing
2268 ambiguity. Here, for example, is an illegal type:
2269
2270
2271 <ProgramListing>
2272   forall a. Eq a => Int
2273 </ProgramListing>
2274
2275
2276 When a value with this type was used, the constraint <Literal>Eq tv</Literal>
2277 would be introduced where <Literal>tv</Literal> is a fresh type variable, and
2278 (in the dictionary-translation implementation) the value would be
2279 applied to a dictionary for <Literal>Eq tv</Literal>.  The difficulty is that we
2280 can never know which instance of <Literal>Eq</Literal> to use because we never
2281 get any more information about <Literal>tv</Literal>.
2282
2283 </Para>
2284 </ListItem>
2285 <ListItem>
2286
2287 <Para>
2288  <Emphasis>Every constraint <Literal>ci</Literal> must mention at least one of the
2289 universally quantified type variables <Literal>tvi</Literal></Emphasis>.
2290
2291 For example, this type is OK because <Literal>C a b</Literal> mentions the
2292 universally quantified type variable <Literal>b</Literal>:
2293
2294
2295 <ProgramListing>
2296   forall a. C a b => burble
2297 </ProgramListing>
2298
2299
2300 The next type is illegal because the constraint <Literal>Eq b</Literal> does not
2301 mention <Literal>a</Literal>:
2302
2303
2304 <ProgramListing>
2305   forall a. Eq b => burble
2306 </ProgramListing>
2307
2308
2309 The reason for this restriction is milder than the other one.  The
2310 excluded types are never useful or necessary (because the offending
2311 context doesn't need to be witnessed at this point; it can be floated
2312 out).  Furthermore, floating them out increases sharing. Lastly,
2313 excluding them is a conservative choice; it leaves a patch of
2314 territory free in case we need it later.
2315
2316 </Para>
2317 </ListItem>
2318
2319 </OrderedList>
2320
2321 </Para>
2322
2323 <Para>
2324 These restrictions apply to all types, whether declared in a type signature
2325 or inferred.
2326 </Para>
2327
2328 <Para>
2329 Unlike Haskell 1.4, constraints in types do <Emphasis>not</Emphasis> have to be of
2330 the form <Emphasis>(class type-variables)</Emphasis>.  Thus, these type signatures
2331 are perfectly OK
2332 </Para>
2333
2334 <Para>
2335
2336 <ProgramListing>
2337   f :: Eq (m a) => [m a] -> [m a]
2338   g :: Eq [a] => ...
2339 </ProgramListing>
2340
2341 </Para>
2342
2343 <Para>
2344 This choice recovers principal types, a property that Haskell 1.4 does not have.
2345 </Para>
2346
2347 </Sect2>
2348
2349 <Sect2>
2350 <Title>Class declarations</Title>
2351
2352 <Para>
2353
2354 <OrderedList>
2355 <ListItem>
2356
2357 <Para>
2358  <Emphasis>Multi-parameter type classes are permitted</Emphasis>. For example:
2359
2360
2361 <ProgramListing>
2362   class Collection c a where
2363     union :: c a -> c a -> c a
2364     ...etc.
2365 </ProgramListing>
2366
2367
2368
2369 </Para>
2370 </ListItem>
2371 <ListItem>
2372
2373 <Para>
2374  <Emphasis>The class hierarchy must be acyclic</Emphasis>.  However, the definition
2375 of "acyclic" involves only the superclass relationships.  For example,
2376 this is OK:
2377
2378
2379 <ProgramListing>
2380   class C a where {
2381     op :: D b => a -> b -> b
2382   }
2383
2384   class C a => D a where { ... }
2385 </ProgramListing>
2386
2387
2388 Here, <Literal>C</Literal> is a superclass of <Literal>D</Literal>, but it's OK for a
2389 class operation <Literal>op</Literal> of <Literal>C</Literal> to mention <Literal>D</Literal>.  (It
2390 would not be OK for <Literal>D</Literal> to be a superclass of <Literal>C</Literal>.)
2391
2392 </Para>
2393 </ListItem>
2394 <ListItem>
2395
2396 <Para>
2397  <Emphasis>There are no restrictions on the context in a class declaration
2398 (which introduces superclasses), except that the class hierarchy must
2399 be acyclic</Emphasis>.  So these class declarations are OK:
2400
2401
2402 <ProgramListing>
2403   class Functor (m k) => FiniteMap m k where
2404     ...
2405
2406   class (Monad m, Monad (t m)) => Transform t m where
2407     lift :: m a -> (t m) a
2408 </ProgramListing>
2409
2410
2411 </Para>
2412 </ListItem>
2413 <ListItem>
2414
2415 <Para>
2416  <Emphasis>In the signature of a class operation, every constraint
2417 must mention at least one type variable that is not a class type
2418 variable</Emphasis>.
2419
2420 Thus:
2421
2422
2423 <ProgramListing>
2424   class Collection c a where
2425     mapC :: Collection c b => (a->b) -> c a -> c b
2426 </ProgramListing>
2427
2428
2429 is OK because the constraint <Literal>(Collection a b)</Literal> mentions
2430 <Literal>b</Literal>, even though it also mentions the class variable
2431 <Literal>a</Literal>.  On the other hand:
2432
2433
2434 <ProgramListing>
2435   class C a where
2436     op :: Eq a => (a,b) -> (a,b)
2437 </ProgramListing>
2438
2439
2440 is not OK because the constraint <Literal>(Eq a)</Literal> mentions on the class
2441 type variable <Literal>a</Literal>, but not <Literal>b</Literal>.  However, any such
2442 example is easily fixed by moving the offending context up to the
2443 superclass context:
2444
2445
2446 <ProgramListing>
2447   class Eq a => C a where
2448     op ::(a,b) -> (a,b)
2449 </ProgramListing>
2450
2451
2452 A yet more relaxed rule would allow the context of a class-op signature
2453 to mention only class type variables.  However, that conflicts with
2454 Rule 1(b) for types above.
2455
2456 </Para>
2457 </ListItem>
2458 <ListItem>
2459
2460 <Para>
2461  <Emphasis>The type of each class operation must mention <Emphasis>all</Emphasis> of
2462 the class type variables</Emphasis>.  For example:
2463
2464
2465 <ProgramListing>
2466   class Coll s a where
2467     empty  :: s
2468     insert :: s -> a -> s
2469 </ProgramListing>
2470
2471
2472 is not OK, because the type of <Literal>empty</Literal> doesn't mention
2473 <Literal>a</Literal>.  This rule is a consequence of Rule 1(a), above, for
2474 types, and has the same motivation.
2475
2476 Sometimes, offending class declarations exhibit misunderstandings.  For
2477 example, <Literal>Coll</Literal> might be rewritten
2478
2479
2480 <ProgramListing>
2481   class Coll s a where
2482     empty  :: s a
2483     insert :: s a -> a -> s a
2484 </ProgramListing>
2485
2486
2487 which makes the connection between the type of a collection of
2488 <Literal>a</Literal>'s (namely <Literal>(s a)</Literal>) and the element type <Literal>a</Literal>.
2489 Occasionally this really doesn't work, in which case you can split the
2490 class like this:
2491
2492
2493 <ProgramListing>
2494   class CollE s where
2495     empty  :: s
2496
2497   class CollE s => Coll s a where
2498     insert :: s -> a -> s
2499 </ProgramListing>
2500
2501
2502 </Para>
2503 </ListItem>
2504
2505 </OrderedList>
2506
2507 </Para>
2508
2509 </Sect2>
2510
2511 <Sect2>
2512 <Title>Instance declarations</Title>
2513
2514 <Para>
2515
2516 <OrderedList>
2517 <ListItem>
2518
2519 <Para>
2520  <Emphasis>Instance declarations may not overlap</Emphasis>.  The two instance
2521 declarations
2522
2523
2524 <ProgramListing>
2525   instance context1 => C type1 where ...
2526   instance context2 => C type2 where ...
2527 </ProgramListing>
2528
2529
2530 "overlap" if <Literal>type1</Literal> and <Literal>type2</Literal> unify
2531
2532 However, if you give the command line option
2533 <Option>-fallow-overlapping-instances</Option><IndexTerm><Primary>-fallow-overlapping-instances
2534 option</Primary></IndexTerm> then two overlapping instance declarations are permitted
2535 iff
2536
2537
2538 <ItemizedList>
2539 <ListItem>
2540
2541 <Para>
2542  EITHER <Literal>type1</Literal> and <Literal>type2</Literal> do not unify
2543 </Para>
2544 </ListItem>
2545 <ListItem>
2546
2547 <Para>
2548  OR <Literal>type2</Literal> is a substitution instance of <Literal>type1</Literal>
2549 (but not identical to <Literal>type1</Literal>)
2550 </Para>
2551 </ListItem>
2552 <ListItem>
2553
2554 <Para>
2555  OR vice versa
2556 </Para>
2557 </ListItem>
2558
2559 </ItemizedList>
2560
2561
2562 Notice that these rules
2563
2564
2565 <ItemizedList>
2566 <ListItem>
2567
2568 <Para>
2569  make it clear which instance decl to use
2570 (pick the most specific one that matches)
2571
2572 </Para>
2573 </ListItem>
2574 <ListItem>
2575
2576 <Para>
2577  do not mention the contexts <Literal>context1</Literal>, <Literal>context2</Literal>
2578 Reason: you can pick which instance decl
2579 "matches" based on the type.
2580 </Para>
2581 </ListItem>
2582
2583 </ItemizedList>
2584
2585
2586 Regrettably, GHC doesn't guarantee to detect overlapping instance
2587 declarations if they appear in different modules.  GHC can "see" the
2588 instance declarations in the transitive closure of all the modules
2589 imported by the one being compiled, so it can "see" all instance decls
2590 when it is compiling <Literal>Main</Literal>.  However, it currently chooses not
2591 to look at ones that can't possibly be of use in the module currently
2592 being compiled, in the interests of efficiency.  (Perhaps we should
2593 change that decision, at least for <Literal>Main</Literal>.)
2594
2595 </Para>
2596 </ListItem>
2597 <ListItem>
2598
2599 <Para>
2600  <Emphasis>There are no restrictions on the type in an instance
2601 <Emphasis>head</Emphasis>, except that at least one must not be a type variable</Emphasis>.
2602 The instance "head" is the bit after the "=>" in an instance decl. For
2603 example, these are OK:
2604
2605
2606 <ProgramListing>
2607   instance C Int a where ...
2608
2609   instance D (Int, Int) where ...
2610
2611   instance E [[a]] where ...
2612 </ProgramListing>
2613
2614
2615 Note that instance heads <Emphasis>may</Emphasis> contain repeated type variables.
2616 For example, this is OK:
2617
2618
2619 <ProgramListing>
2620   instance Stateful (ST s) (MutVar s) where ...
2621 </ProgramListing>
2622
2623
2624 The "at least one not a type variable" restriction is to ensure that
2625 context reduction terminates: each reduction step removes one type
2626 constructor.  For example, the following would make the type checker
2627 loop if it wasn't excluded:
2628
2629
2630 <ProgramListing>
2631   instance C a => C a where ...
2632 </ProgramListing>
2633
2634
2635 There are two situations in which the rule is a bit of a pain. First,
2636 if one allows overlapping instance declarations then it's quite
2637 convenient to have a "default instance" declaration that applies if
2638 something more specific does not:
2639
2640
2641 <ProgramListing>
2642   instance C a where
2643     op = ... -- Default
2644 </ProgramListing>
2645
2646
2647 Second, sometimes you might want to use the following to get the
2648 effect of a "class synonym":
2649
2650
2651 <ProgramListing>
2652   class (C1 a, C2 a, C3 a) => C a where { }
2653
2654   instance (C1 a, C2 a, C3 a) => C a where { }
2655 </ProgramListing>
2656
2657
2658 This allows you to write shorter signatures:
2659
2660
2661 <ProgramListing>
2662   f :: C a => ...
2663 </ProgramListing>
2664
2665
2666 instead of
2667
2668
2669 <ProgramListing>
2670   f :: (C1 a, C2 a, C3 a) => ...
2671 </ProgramListing>
2672
2673
2674 I'm on the lookout for a simple rule that preserves decidability while
2675 allowing these idioms.  The experimental flag
2676 <Option>-fallow-undecidable-instances</Option><IndexTerm><Primary>-fallow-undecidable-instances
2677 option</Primary></IndexTerm> lifts this restriction, allowing all the types in an
2678 instance head to be type variables.
2679
2680 </Para>
2681 </ListItem>
2682 <ListItem>
2683
2684 <Para>
2685  <Emphasis>Unlike Haskell 1.4, instance heads may use type
2686 synonyms</Emphasis>.  As always, using a type synonym is just shorthand for
2687 writing the RHS of the type synonym definition.  For example:
2688
2689
2690 <ProgramListing>
2691   type Point = (Int,Int)
2692   instance C Point   where ...
2693   instance C [Point] where ...
2694 </ProgramListing>
2695
2696
2697 is legal.  However, if you added
2698
2699
2700 <ProgramListing>
2701   instance C (Int,Int) where ...
2702 </ProgramListing>
2703
2704
2705 as well, then the compiler will complain about the overlapping
2706 (actually, identical) instance declarations.  As always, type synonyms
2707 must be fully applied.  You cannot, for example, write:
2708
2709
2710 <ProgramListing>
2711   type P a = [[a]]
2712   instance Monad P where ...
2713 </ProgramListing>
2714
2715
2716 This design decision is independent of all the others, and easily
2717 reversed, but it makes sense to me.
2718
2719 </Para>
2720 </ListItem>
2721 <ListItem>
2722
2723 <Para>
2724 <Emphasis>The types in an instance-declaration <Emphasis>context</Emphasis> must all
2725 be type variables</Emphasis>. Thus
2726
2727
2728 <ProgramListing>
2729 instance C a b => Eq (a,b) where ...
2730 </ProgramListing>
2731
2732
2733 is OK, but
2734
2735
2736 <ProgramListing>
2737 instance C Int b => Foo b where ...
2738 </ProgramListing>
2739
2740
2741 is not OK.  Again, the intent here is to make sure that context
2742 reduction terminates.
2743
2744 Voluminous correspondence on the Haskell mailing list has convinced me
2745 that it's worth experimenting with a more liberal rule.  If you use
2746 the flag <Option>-fallow-undecidable-instances</Option> can use arbitrary
2747 types in an instance context.  Termination is ensured by having a
2748 fixed-depth recursion stack.  If you exceed the stack depth you get a
2749 sort of backtrace, and the opportunity to increase the stack depth
2750 with <Option>-fcontext-stack</Option><Emphasis>N</Emphasis>.
2751
2752 </Para>
2753 </ListItem>
2754
2755 </OrderedList>
2756
2757 </Para>
2758
2759 </Sect2>
2760
2761 </Sect1>
2762
2763 <Sect1 id="universal-quantification">
2764 <Title>Explicit universal quantification
2765 </Title>
2766
2767 <Para>
2768 GHC now allows you to write explicitly quantified types.  GHC's
2769 syntax for this now agrees with Hugs's, namely:
2770 </Para>
2771
2772 <Para>
2773
2774 <ProgramListing>
2775         forall a b. (Ord a, Eq  b) => a -> b -> a
2776 </ProgramListing>
2777
2778 </Para>
2779
2780 <Para>
2781 The context is, of course, optional.  You can't use <Literal>forall</Literal> as
2782 a type variable any more!
2783 </Para>
2784
2785 <Para>
2786 Haskell type signatures are implicitly quantified.  The <Literal>forall</Literal>
2787 allows us to say exactly what this means.  For example:
2788 </Para>
2789
2790 <Para>
2791
2792 <ProgramListing>
2793         g :: b -> b
2794 </ProgramListing>
2795
2796 </Para>
2797
2798 <Para>
2799 means this:
2800 </Para>
2801
2802 <Para>
2803
2804 <ProgramListing>
2805         g :: forall b. (b -> b)
2806 </ProgramListing>
2807
2808 </Para>
2809
2810 <Para>
2811 The two are treated identically.
2812 </Para>
2813
2814 <Sect2 id="univ">
2815 <Title>Universally-quantified data type fields
2816 </Title>
2817
2818 <Para>
2819 In a <Literal>data</Literal> or <Literal>newtype</Literal> declaration one can quantify
2820 the types of the constructor arguments.  Here are several examples:
2821 </Para>
2822
2823 <Para>
2824
2825 <ProgramListing>
2826 data T a = T1 (forall b. b -> b -> b) a
2827
2828 data MonadT m = MkMonad { return :: forall a. a -> m a,
2829                           bind   :: forall a b. m a -> (a -> m b) -> m b
2830                         }
2831
2832 newtype Swizzle = MkSwizzle (Ord a => [a] -> [a])
2833 </ProgramListing>
2834
2835 </Para>
2836
2837 <Para>
2838 The constructors now have so-called <Emphasis>rank 2</Emphasis> polymorphic
2839 types, in which there is a for-all in the argument types.:
2840 </Para>
2841
2842 <Para>
2843
2844 <ProgramListing>
2845 T1 :: forall a. (forall b. b -> b -> b) -> a -> T a
2846 MkMonad :: forall m. (forall a. a -> m a)
2847                   -> (forall a b. m a -> (a -> m b) -> m b)
2848                   -> MonadT m
2849 MkSwizzle :: (Ord a => [a] -> [a]) -> Swizzle
2850 </ProgramListing>
2851
2852 </Para>
2853
2854 <Para>
2855 Notice that you don't need to use a <Literal>forall</Literal> if there's an
2856 explicit context.  For example in the first argument of the
2857 constructor <Function>MkSwizzle</Function>, an implicit "<Literal>forall a.</Literal>" is
2858 prefixed to the argument type.  The implicit <Literal>forall</Literal>
2859 quantifies all type variables that are not already in scope, and are
2860 mentioned in the type quantified over.
2861 </Para>
2862
2863 <Para>
2864 As for type signatures, implicit quantification happens for non-overloaded
2865 types too.  So if you write this:
2866
2867 <ProgramListing>
2868   data T a = MkT (Either a b) (b -> b)
2869 </ProgramListing>
2870
2871 it's just as if you had written this:
2872
2873 <ProgramListing>
2874   data T a = MkT (forall b. Either a b) (forall b. b -> b)
2875 </ProgramListing>
2876
2877 That is, since the type variable <Literal>b</Literal> isn't in scope, it's
2878 implicitly universally quantified.  (Arguably, it would be better
2879 to <Emphasis>require</Emphasis> explicit quantification on constructor arguments
2880 where that is what is wanted.  Feedback welcomed.)
2881 </Para>
2882
2883 </Sect2>
2884
2885 <Sect2>
2886 <Title>Construction </Title>
2887
2888 <Para>
2889 You construct values of types <Literal>T1, MonadT, Swizzle</Literal> by applying
2890 the constructor to suitable values, just as usual.  For example,
2891 </Para>
2892
2893 <Para>
2894
2895 <ProgramListing>
2896 (T1 (\xy->x) 3) :: T Int
2897
2898 (MkSwizzle sort)    :: Swizzle
2899 (MkSwizzle reverse) :: Swizzle
2900
2901 (let r x = Just x
2902      b m k = case m of
2903                 Just y -> k y
2904                 Nothing -> Nothing
2905   in
2906   MkMonad r b) :: MonadT Maybe
2907 </ProgramListing>
2908
2909 </Para>
2910
2911 <Para>
2912 The type of the argument can, as usual, be more general than the type
2913 required, as <Literal>(MkSwizzle reverse)</Literal> shows.  (<Function>reverse</Function>
2914 does not need the <Literal>Ord</Literal> constraint.)
2915 </Para>
2916
2917 </Sect2>
2918
2919 <Sect2>
2920 <Title>Pattern matching</Title>
2921
2922 <Para>
2923 When you use pattern matching, the bound variables may now have
2924 polymorphic types.  For example:
2925 </Para>
2926
2927 <Para>
2928
2929 <ProgramListing>
2930         f :: T a -> a -> (a, Char)
2931         f (T1 f k) x = (f k x, f 'c' 'd')
2932
2933         g :: (Ord a, Ord b) => Swizzle -> [a] -> (a -> b) -> [b]
2934         g (MkSwizzle s) xs f = s (map f (s xs))
2935
2936         h :: MonadT m -> [m a] -> m [a]
2937         h m [] = return m []
2938         h m (x:xs) = bind m x           $ \y ->
2939                       bind m (h m xs)   $ \ys ->
2940                       return m (y:ys)
2941 </ProgramListing>
2942
2943 </Para>
2944
2945 <Para>
2946 In the function <Function>h</Function> we use the record selectors <Literal>return</Literal>
2947 and <Literal>bind</Literal> to extract the polymorphic bind and return functions
2948 from the <Literal>MonadT</Literal> data structure, rather than using pattern
2949 matching.
2950 </Para>
2951
2952 <Para>
2953 You cannot pattern-match against an argument that is polymorphic.
2954 For example:
2955
2956 <ProgramListing>
2957         newtype TIM s a = TIM (ST s (Maybe a))
2958
2959         runTIM :: (forall s. TIM s a) -> Maybe a
2960         runTIM (TIM m) = runST m
2961 </ProgramListing>
2962
2963 </Para>
2964
2965 <Para>
2966 Here the pattern-match fails, because you can't pattern-match against
2967 an argument of type <Literal>(forall s. TIM s a)</Literal>.  Instead you
2968 must bind the variable and pattern match in the right hand side:
2969
2970 <ProgramListing>
2971         runTIM :: (forall s. TIM s a) -> Maybe a
2972         runTIM tm = case tm of { TIM m -> runST m }
2973 </ProgramListing>
2974
2975 The <Literal>tm</Literal> on the right hand side is (invisibly) instantiated, like
2976 any polymorphic value at its occurrence site, and now you can pattern-match
2977 against it.
2978 </Para>
2979
2980 </Sect2>
2981
2982 <Sect2>
2983 <Title>The partial-application restriction</Title>
2984
2985 <Para>
2986 There is really only one way in which data structures with polymorphic
2987 components might surprise you: you must not partially apply them.
2988 For example, this is illegal:
2989 </Para>
2990
2991 <Para>
2992
2993 <ProgramListing>
2994         map MkSwizzle [sort, reverse]
2995 </ProgramListing>
2996
2997 </Para>
2998
2999 <Para>
3000 The restriction is this: <Emphasis>every subexpression of the program must
3001 have a type that has no for-alls, except that in a function
3002 application (f e1&hellip;en) the partial applications are not subject to
3003 this rule</Emphasis>.  The restriction makes type inference feasible.
3004 </Para>
3005
3006 <Para>
3007 In the illegal example, the sub-expression <Literal>MkSwizzle</Literal> has the
3008 polymorphic type <Literal>(Ord b => [b] -> [b]) -> Swizzle</Literal> and is not
3009 a sub-expression of an enclosing application.  On the other hand, this
3010 expression is OK:
3011 </Para>
3012
3013 <Para>
3014
3015 <ProgramListing>
3016         map (T1 (\a b -> a)) [1,2,3]
3017 </ProgramListing>
3018
3019 </Para>
3020
3021 <Para>
3022 even though it involves a partial application of <Function>T1</Function>, because
3023 the sub-expression <Literal>T1 (\a b -> a)</Literal> has type <Literal>Int -> T
3024 Int</Literal>.
3025 </Para>
3026
3027 </Sect2>
3028
3029 <Sect2 id="sigs">
3030 <Title>Type signatures
3031 </Title>
3032
3033 <Para>
3034 Once you have data constructors with universally-quantified fields, or
3035 constants such as <Constant>runST</Constant> that have rank-2 types, it isn't long
3036 before you discover that you need more!  Consider:
3037 </Para>
3038
3039 <Para>
3040
3041 <ProgramListing>
3042   mkTs f x y = [T1 f x, T1 f y]
3043 </ProgramListing>
3044
3045 </Para>
3046
3047 <Para>
3048 <Function>mkTs</Function> is a fuction that constructs some values of type
3049 <Literal>T</Literal>, using some pieces passed to it.  The trouble is that since
3050 <Literal>f</Literal> is a function argument, Haskell assumes that it is
3051 monomorphic, so we'll get a type error when applying <Function>T1</Function> to
3052 it.  This is a rather silly example, but the problem really bites in
3053 practice.  Lots of people trip over the fact that you can't make
3054 "wrappers functions" for <Constant>runST</Constant> for exactly the same reason.
3055 In short, it is impossible to build abstractions around functions with
3056 rank-2 types.
3057 </Para>
3058
3059 <Para>
3060 The solution is fairly clear.  We provide the ability to give a rank-2
3061 type signature for <Emphasis>ordinary</Emphasis> functions (not only data
3062 constructors), thus:
3063 </Para>
3064
3065 <Para>
3066
3067 <ProgramListing>
3068   mkTs :: (forall b. b -> b -> b) -> a -> [T a]
3069   mkTs f x y = [T1 f x, T1 f y]
3070 </ProgramListing>
3071
3072 </Para>
3073
3074 <Para>
3075 This type signature tells the compiler to attribute <Literal>f</Literal> with
3076 the polymorphic type <Literal>(forall b. b -> b -> b)</Literal> when type
3077 checking the body of <Function>mkTs</Function>, so now the application of
3078 <Function>T1</Function> is fine.
3079 </Para>
3080
3081 <Para>
3082 There are two restrictions:
3083 </Para>
3084
3085 <Para>
3086
3087 <ItemizedList>
3088 <ListItem>
3089
3090 <Para>
3091  You can only define a rank 2 type, specified by the following
3092 grammar:
3093
3094
3095 <ProgramListing>
3096 rank2type ::= [forall tyvars .] [context =>] funty
3097 funty     ::= ([forall tyvars .] [context =>] ty) -> funty
3098             | ty
3099 ty        ::= ...current Haskell monotype syntax...
3100 </ProgramListing>
3101
3102
3103 Informally, the universal quantification must all be right at the beginning,
3104 or at the top level of a function argument.
3105
3106 </Para>
3107 </ListItem>
3108 <ListItem>
3109
3110 <Para>
3111  There is a restriction on the definition of a function whose
3112 type signature is a rank-2 type: the polymorphic arguments must be
3113 matched on the left hand side of the "<Literal>=</Literal>" sign.  You can't
3114 define <Function>mkTs</Function> like this:
3115
3116
3117 <ProgramListing>
3118 mkTs :: (forall b. b -> b -> b) -> a -> [T a]
3119 mkTs = \ f x y -> [T1 f x, T1 f y]
3120 </ProgramListing>
3121
3122
3123
3124 The same partial-application rule applies to ordinary functions with
3125 rank-2 types as applied to data constructors.
3126
3127 </Para>
3128 </ListItem>
3129
3130 </ItemizedList>
3131
3132 </Para>
3133
3134 </Sect2>
3135
3136
3137 <Sect2 id="hoist">
3138 <Title>Type synonyms and hoisting
3139 </Title>
3140
3141 <Para>
3142 GHC also allows you to write a <Literal>forall</Literal> in a type synonym, thus:
3143 <ProgramListing>
3144   type Discard a = forall b. a -> b -> a
3145
3146   f :: Discard a
3147   f x y = x
3148 </ProgramListing>
3149 However, it is often convenient to use these sort of synonyms at the right hand
3150 end of an arrow, thus:
3151 <ProgramListing>
3152   type Discard a = forall b. a -> b -> a
3153
3154   g :: Int -> Discard Int
3155   g x y z = x+y
3156 </ProgramListing>
3157 Simply expanding the type synonym would give
3158 <ProgramListing>
3159   g :: Int -> (forall b. Int -> b -> Int)
3160 </ProgramListing>
3161 but GHC "hoists" the <Literal>forall</Literal> to give the isomorphic type
3162 <ProgramListing>
3163   g :: forall b. Int -> Int -> b -> Int
3164 </ProgramListing>
3165 In general, the rule is this: <Emphasis>to determine the type specified by any explicit
3166 user-written type (e.g. in a type signature), GHC expands type synonyms and then repeatedly
3167 performs the transformation:</Emphasis>
3168 <ProgramListing>
3169   <Emphasis>type1</Emphasis> -> forall a. <Emphasis>type2</Emphasis>
3170 ==>
3171   forall a. <Emphasis>type1</Emphasis> -> <Emphasis>type2</Emphasis>
3172 </ProgramListing>
3173 (In fact, GHC tries to retain as much synonym information as possible for use in
3174 error messages, but that is a usability issue.)  This rule applies, of course, whether
3175 or not the <Literal>forall</Literal> comes from a synonym. For example, here is another
3176 valid way to write <Literal>g</Literal>'s type signature:
3177 <ProgramListing>
3178   g :: Int -> Int -> forall b. b -> Int
3179 </ProgramListing>
3180 </Para>
3181 </Sect2>
3182
3183 </Sect1>
3184
3185 <Sect1 id="existential-quantification">
3186 <Title>Existentially quantified data constructors
3187 </Title>
3188
3189 <Para>
3190 The idea of using existential quantification in data type declarations
3191 was suggested by Laufer (I believe, thought doubtless someone will
3192 correct me), and implemented in Hope+. It's been in Lennart
3193 Augustsson's <Command>hbc</Command> Haskell compiler for several years, and
3194 proved very useful.  Here's the idea.  Consider the declaration:
3195 </Para>
3196
3197 <Para>
3198
3199 <ProgramListing>
3200   data Foo = forall a. MkFoo a (a -> Bool)
3201            | Nil
3202 </ProgramListing>
3203
3204 </Para>
3205
3206 <Para>
3207 The data type <Literal>Foo</Literal> has two constructors with types:
3208 </Para>
3209
3210 <Para>
3211
3212 <ProgramListing>
3213   MkFoo :: forall a. a -> (a -> Bool) -> Foo
3214   Nil   :: Foo
3215 </ProgramListing>
3216
3217 </Para>
3218
3219 <Para>
3220 Notice that the type variable <Literal>a</Literal> in the type of <Function>MkFoo</Function>
3221 does not appear in the data type itself, which is plain <Literal>Foo</Literal>.
3222 For example, the following expression is fine:
3223 </Para>
3224
3225 <Para>
3226
3227 <ProgramListing>
3228   [MkFoo 3 even, MkFoo 'c' isUpper] :: [Foo]
3229 </ProgramListing>
3230
3231 </Para>
3232
3233 <Para>
3234 Here, <Literal>(MkFoo 3 even)</Literal> packages an integer with a function
3235 <Function>even</Function> that maps an integer to <Literal>Bool</Literal>; and <Function>MkFoo 'c'
3236 isUpper</Function> packages a character with a compatible function.  These
3237 two things are each of type <Literal>Foo</Literal> and can be put in a list.
3238 </Para>
3239
3240 <Para>
3241 What can we do with a value of type <Literal>Foo</Literal>?.  In particular,
3242 what happens when we pattern-match on <Function>MkFoo</Function>?
3243 </Para>
3244
3245 <Para>
3246
3247 <ProgramListing>
3248   f (MkFoo val fn) = ???
3249 </ProgramListing>
3250
3251 </Para>
3252
3253 <Para>
3254 Since all we know about <Literal>val</Literal> and <Function>fn</Function> is that they
3255 are compatible, the only (useful) thing we can do with them is to
3256 apply <Function>fn</Function> to <Literal>val</Literal> to get a boolean.  For example:
3257 </Para>
3258
3259 <Para>
3260
3261 <ProgramListing>
3262   f :: Foo -> Bool
3263   f (MkFoo val fn) = fn val
3264 </ProgramListing>
3265
3266 </Para>
3267
3268 <Para>
3269 What this allows us to do is to package heterogenous values
3270 together with a bunch of functions that manipulate them, and then treat
3271 that collection of packages in a uniform manner.  You can express
3272 quite a bit of object-oriented-like programming this way.
3273 </Para>
3274
3275 <Sect2 id="existential">
3276 <Title>Why existential?
3277 </Title>
3278
3279 <Para>
3280 What has this to do with <Emphasis>existential</Emphasis> quantification?
3281 Simply that <Function>MkFoo</Function> has the (nearly) isomorphic type
3282 </Para>
3283
3284 <Para>
3285
3286 <ProgramListing>
3287   MkFoo :: (exists a . (a, a -> Bool)) -> Foo
3288 </ProgramListing>
3289
3290 </Para>
3291
3292 <Para>
3293 But Haskell programmers can safely think of the ordinary
3294 <Emphasis>universally</Emphasis> quantified type given above, thereby avoiding
3295 adding a new existential quantification construct.
3296 </Para>
3297
3298 </Sect2>
3299
3300 <Sect2>
3301 <Title>Type classes</Title>
3302
3303 <Para>
3304 An easy extension (implemented in <Command>hbc</Command>) is to allow
3305 arbitrary contexts before the constructor.  For example:
3306 </Para>
3307
3308 <Para>
3309
3310 <ProgramListing>
3311 data Baz = forall a. Eq a => Baz1 a a
3312          | forall b. Show b => Baz2 b (b -> b)
3313 </ProgramListing>
3314
3315 </Para>
3316
3317 <Para>
3318 The two constructors have the types you'd expect:
3319 </Para>
3320
3321 <Para>
3322
3323 <ProgramListing>
3324 Baz1 :: forall a. Eq a => a -> a -> Baz
3325 Baz2 :: forall b. Show b => b -> (b -> b) -> Baz
3326 </ProgramListing>
3327
3328 </Para>
3329
3330 <Para>
3331 But when pattern matching on <Function>Baz1</Function> the matched values can be compared
3332 for equality, and when pattern matching on <Function>Baz2</Function> the first matched
3333 value can be converted to a string (as well as applying the function to it).
3334 So this program is legal:
3335 </Para>
3336
3337 <Para>
3338
3339 <ProgramListing>
3340   f :: Baz -> String
3341   f (Baz1 p q) | p == q    = "Yes"
3342                | otherwise = "No"
3343   f (Baz1 v fn)            = show (fn v)
3344 </ProgramListing>
3345
3346 </Para>
3347
3348 <Para>
3349 Operationally, in a dictionary-passing implementation, the
3350 constructors <Function>Baz1</Function> and <Function>Baz2</Function> must store the
3351 dictionaries for <Literal>Eq</Literal> and <Literal>Show</Literal> respectively, and
3352 extract it on pattern matching.
3353 </Para>
3354
3355 <Para>
3356 Notice the way that the syntax fits smoothly with that used for
3357 universal quantification earlier.
3358 </Para>
3359
3360 </Sect2>
3361
3362 <Sect2>
3363 <Title>Restrictions</Title>
3364
3365 <Para>
3366 There are several restrictions on the ways in which existentially-quantified
3367 constructors can be use.
3368 </Para>
3369
3370 <Para>
3371
3372 <ItemizedList>
3373 <ListItem>
3374
3375 <Para>
3376  When pattern matching, each pattern match introduces a new,
3377 distinct, type for each existential type variable.  These types cannot
3378 be unified with any other type, nor can they escape from the scope of
3379 the pattern match.  For example, these fragments are incorrect:
3380
3381
3382 <ProgramListing>
3383 f1 (MkFoo a f) = a
3384 </ProgramListing>
3385
3386
3387 Here, the type bound by <Function>MkFoo</Function> "escapes", because <Literal>a</Literal>
3388 is the result of <Function>f1</Function>.  One way to see why this is wrong is to
3389 ask what type <Function>f1</Function> has:
3390
3391
3392 <ProgramListing>
3393   f1 :: Foo -> a             -- Weird!
3394 </ProgramListing>
3395
3396
3397 What is this "<Literal>a</Literal>" in the result type? Clearly we don't mean
3398 this:
3399
3400
3401 <ProgramListing>
3402   f1 :: forall a. Foo -> a   -- Wrong!
3403 </ProgramListing>
3404
3405
3406 The original program is just plain wrong.  Here's another sort of error
3407
3408
3409 <ProgramListing>
3410   f2 (Baz1 a b) (Baz1 p q) = a==q
3411 </ProgramListing>
3412
3413
3414 It's ok to say <Literal>a==b</Literal> or <Literal>p==q</Literal>, but
3415 <Literal>a==q</Literal> is wrong because it equates the two distinct types arising
3416 from the two <Function>Baz1</Function> constructors.
3417
3418
3419 </Para>
3420 </ListItem>
3421 <ListItem>
3422
3423 <Para>
3424 You can't pattern-match on an existentially quantified
3425 constructor in a <Literal>let</Literal> or <Literal>where</Literal> group of
3426 bindings. So this is illegal:
3427
3428
3429 <ProgramListing>
3430   f3 x = a==b where { Baz1 a b = x }
3431 </ProgramListing>
3432
3433
3434 You can only pattern-match
3435 on an existentially-quantified constructor in a <Literal>case</Literal> expression or
3436 in the patterns of a function definition.
3437
3438 The reason for this restriction is really an implementation one.
3439 Type-checking binding groups is already a nightmare without
3440 existentials complicating the picture.  Also an existential pattern
3441 binding at the top level of a module doesn't make sense, because it's
3442 not clear how to prevent the existentially-quantified type "escaping".
3443 So for now, there's a simple-to-state restriction.  We'll see how
3444 annoying it is.
3445
3446 </Para>
3447 </ListItem>
3448 <ListItem>
3449
3450 <Para>
3451 You can't use existential quantification for <Literal>newtype</Literal>
3452 declarations.  So this is illegal:
3453
3454
3455 <ProgramListing>
3456   newtype T = forall a. Ord a => MkT a
3457 </ProgramListing>
3458
3459
3460 Reason: a value of type <Literal>T</Literal> must be represented as a pair
3461 of a dictionary for <Literal>Ord t</Literal> and a value of type <Literal>t</Literal>.
3462 That contradicts the idea that <Literal>newtype</Literal> should have no
3463 concrete representation.  You can get just the same efficiency and effect
3464 by using <Literal>data</Literal> instead of <Literal>newtype</Literal>.  If there is no
3465 overloading involved, then there is more of a case for allowing
3466 an existentially-quantified <Literal>newtype</Literal>, because the <Literal>data</Literal>
3467 because the <Literal>data</Literal> version does carry an implementation cost,
3468 but single-field existentially quantified constructors aren't much
3469 use.  So the simple restriction (no existential stuff on <Literal>newtype</Literal>)
3470 stands, unless there are convincing reasons to change it.
3471
3472
3473 </Para>
3474 </ListItem>
3475 <ListItem>
3476
3477 <Para>
3478  You can't use <Literal>deriving</Literal> to define instances of a
3479 data type with existentially quantified data constructors.
3480
3481 Reason: in most cases it would not make sense. For example:&num;
3482
3483 <ProgramListing>
3484 data T = forall a. MkT [a] deriving( Eq )
3485 </ProgramListing>
3486
3487 To derive <Literal>Eq</Literal> in the standard way we would need to have equality
3488 between the single component of two <Function>MkT</Function> constructors:
3489
3490 <ProgramListing>
3491 instance Eq T where
3492   (MkT a) == (MkT b) = ???
3493 </ProgramListing>
3494
3495 But <VarName>a</VarName> and <VarName>b</VarName> have distinct types, and so can't be compared.
3496 It's just about possible to imagine examples in which the derived instance
3497 would make sense, but it seems altogether simpler simply to prohibit such
3498 declarations.  Define your own instances!
3499 </Para>
3500 </ListItem>
3501
3502 </ItemizedList>
3503
3504 </Para>
3505
3506 </Sect2>
3507
3508 </Sect1>
3509
3510 <Sect1 id="sec-assertions">
3511 <Title>Assertions
3512 <IndexTerm><Primary>Assertions</Primary></IndexTerm>
3513 </Title>
3514
3515 <Para>
3516 If you want to make use of assertions in your standard Haskell code, you
3517 could define a function like the following:
3518 </Para>
3519
3520 <Para>
3521
3522 <ProgramListing>
3523 assert :: Bool -> a -> a
3524 assert False x = error "assertion failed!"
3525 assert _     x = x
3526 </ProgramListing>
3527
3528 </Para>
3529
3530 <Para>
3531 which works, but gives you back a less than useful error message --
3532 an assertion failed, but which and where?
3533 </Para>
3534
3535 <Para>
3536 One way out is to define an extended <Function>assert</Function> function which also
3537 takes a descriptive string to include in the error message and
3538 perhaps combine this with the use of a pre-processor which inserts
3539 the source location where <Function>assert</Function> was used.
3540 </Para>
3541
3542 <Para>
3543 Ghc offers a helping hand here, doing all of this for you. For every
3544 use of <Function>assert</Function> in the user's source:
3545 </Para>
3546
3547 <Para>
3548
3549 <ProgramListing>
3550 kelvinToC :: Double -> Double
3551 kelvinToC k = assert (k &amp;gt;= 0.0) (k+273.15)
3552 </ProgramListing>
3553
3554 </Para>
3555
3556 <Para>
3557 Ghc will rewrite this to also include the source location where the
3558 assertion was made,
3559 </Para>
3560
3561 <Para>
3562
3563 <ProgramListing>
3564 assert pred val ==> assertError "Main.hs|15" pred val
3565 </ProgramListing>
3566
3567 </Para>
3568
3569 <Para>
3570 The rewrite is only performed by the compiler when it spots
3571 applications of <Function>Exception.assert</Function>, so you can still define and
3572 use your own versions of <Function>assert</Function>, should you so wish. If not,
3573 import <Literal>Exception</Literal> to make use <Function>assert</Function> in your code.
3574 </Para>
3575
3576 <Para>
3577 To have the compiler ignore uses of assert, use the compiler option
3578 <Option>-fignore-asserts</Option>. <IndexTerm><Primary>-fignore-asserts option</Primary></IndexTerm> That is,
3579 expressions of the form <Literal>assert pred e</Literal> will be rewritten to <Literal>e</Literal>.
3580 </Para>
3581
3582 <Para>
3583 Assertion failures can be caught, see the documentation for the
3584 <literal>Exception</literal> library (<xref linkend="sec-Exception">)
3585 for the details.
3586 </Para>
3587
3588 </Sect1>
3589
3590 <Sect1 id="scoped-type-variables">
3591 <Title>Scoped Type Variables
3592 </Title>
3593
3594 <Para>
3595 A <Emphasis>pattern type signature</Emphasis> can introduce a <Emphasis>scoped type
3596 variable</Emphasis>.  For example
3597 </Para>
3598
3599 <Para>
3600
3601 <ProgramListing>
3602 f (xs::[a]) = ys ++ ys
3603            where
3604               ys :: [a]
3605               ys = reverse xs
3606 </ProgramListing>
3607
3608 </Para>
3609
3610 <Para>
3611 The pattern <Literal>(xs::[a])</Literal> includes a type signature for <VarName>xs</VarName>.
3612 This brings the type variable <Literal>a</Literal> into scope; it scopes over
3613 all the patterns and right hand sides for this equation for <Function>f</Function>.
3614 In particular, it is in scope at the type signature for <VarName>y</VarName>.
3615 </Para>
3616
3617 <Para>
3618 At ordinary type signatures, such as that for <VarName>ys</VarName>, any type variables
3619 mentioned in the type signature <Emphasis>that are not in scope</Emphasis> are
3620 implicitly universally quantified.  (If there are no type variables in
3621 scope, all type variables mentioned in the signature are universally
3622 quantified, which is just as in Haskell 98.)  In this case, since <VarName>a</VarName>
3623 is in scope, it is not universally quantified, so the type of <VarName>ys</VarName> is
3624 the same as that of <VarName>xs</VarName>.  In Haskell 98 it is not possible to declare
3625 a type for <VarName>ys</VarName>; a major benefit of scoped type variables is that
3626 it becomes possible to do so.
3627 </Para>
3628
3629 <Para>
3630 Scoped type variables are implemented in both GHC and Hugs.  Where the
3631 implementations differ from the specification below, those differences
3632 are noted.
3633 </Para>
3634
3635 <Para>
3636 So much for the basic idea.  Here are the details.
3637 </Para>
3638
3639 <Sect2>
3640 <Title>Scope and implicit quantification</Title>
3641
3642 <Para>
3643
3644 <ItemizedList>
3645 <ListItem>
3646
3647 <Para>
3648  All the type variables mentioned in the patterns for a single
3649 function definition equation, that are not already in scope,
3650 are brought into scope by the patterns.  We describe this set as
3651 the <Emphasis>type variables bound by the equation</Emphasis>.
3652
3653 </Para>
3654 </ListItem>
3655 <ListItem>
3656
3657 <Para>
3658  The type variables thus brought into scope may be mentioned
3659 in ordinary type signatures or pattern type signatures anywhere within
3660 their scope.
3661
3662 </Para>
3663 </ListItem>
3664 <ListItem>
3665
3666 <Para>
3667  In ordinary type signatures, any type variable mentioned in the
3668 signature that is in scope is <Emphasis>not</Emphasis> universally quantified.
3669
3670 </Para>
3671 </ListItem>
3672 <ListItem>
3673
3674 <Para>
3675  Ordinary type signatures do not bring any new type variables
3676 into scope (except in the type signature itself!). So this is illegal:
3677
3678
3679 <ProgramListing>
3680   f :: a -> a
3681   f x = x::a
3682 </ProgramListing>
3683
3684
3685 It's illegal because <VarName>a</VarName> is not in scope in the body of <Function>f</Function>,
3686 so the ordinary signature <Literal>x::a</Literal> is equivalent to <Literal>x::forall a.a</Literal>;
3687 and that is an incorrect typing.
3688
3689 </Para>
3690 </ListItem>
3691 <ListItem>
3692
3693 <Para>
3694  There is no implicit universal quantification on pattern type
3695 signatures, nor may one write an explicit <Literal>forall</Literal> type in a pattern
3696 type signature.  The pattern type signature is a monotype.
3697
3698 </Para>
3699 </ListItem>
3700 <ListItem>
3701
3702 <Para>
3703
3704 The type variables in the head of a <Literal>class</Literal> or <Literal>instance</Literal> declaration
3705 scope over the methods defined in the <Literal>where</Literal> part.  For example:
3706
3707
3708 <ProgramListing>
3709   class C a where
3710     op :: [a] -> a
3711
3712     op xs = let ys::[a]
3713                 ys = reverse xs
3714             in
3715             head ys
3716 </ProgramListing>
3717
3718
3719 (Not implemented in Hugs yet, Dec 98).
3720 </Para>
3721 </ListItem>
3722
3723 </ItemizedList>
3724
3725 </Para>
3726
3727 </Sect2>
3728
3729 <Sect2>
3730 <Title>Polymorphism</Title>
3731
3732 <Para>
3733
3734 <ItemizedList>
3735 <ListItem>
3736
3737 <Para>
3738  Pattern type signatures are completely orthogonal to ordinary, separate
3739 type signatures.  The two can be used independently or together.  There is
3740 no scoping associated with the names of the type variables in a separate type signature.
3741
3742
3743 <ProgramListing>
3744    f :: [a] -> [a]
3745    f (xs::[b]) = reverse xs
3746 </ProgramListing>
3747
3748
3749 </Para>
3750 </ListItem>
3751 <ListItem>
3752
3753 <Para>
3754  The function must be polymorphic in the type variables
3755 bound by all its equations.  Operationally, the type variables bound
3756 by one equation must not:
3757
3758
3759 <ItemizedList>
3760 <ListItem>
3761
3762 <Para>
3763  Be unified with a type (such as <Literal>Int</Literal>, or <Literal>[a]</Literal>).
3764 </Para>
3765 </ListItem>
3766 <ListItem>
3767
3768 <Para>
3769  Be unified with a type variable free in the environment.
3770 </Para>
3771 </ListItem>
3772 <ListItem>
3773
3774 <Para>
3775  Be unified with each other.  (They may unify with the type variables
3776 bound by another equation for the same function, of course.)
3777 </Para>
3778 </ListItem>
3779
3780 </ItemizedList>
3781
3782
3783 For example, the following all fail to type check:
3784
3785
3786 <ProgramListing>
3787   f (x::a) (y::b) = [x,y]       -- a unifies with b
3788
3789   g (x::a) = x + 1::Int         -- a unifies with Int
3790
3791   h x = let k (y::a) = [x,y]    -- a is free in the
3792         in k x                  -- environment
3793
3794   k (x::a) True    = ...        -- a unifies with Int
3795   k (x::Int) False = ...
3796
3797   w :: [b] -> [b]
3798   w (x::a) = x                  -- a unifies with [b]
3799 </ProgramListing>
3800
3801
3802 </Para>
3803 </ListItem>
3804 <ListItem>
3805
3806 <Para>
3807  The pattern-bound type variable may, however, be constrained
3808 by the context of the principal type, thus:
3809
3810
3811 <ProgramListing>
3812   f (x::a) (y::a) = x+y*2
3813 </ProgramListing>
3814
3815
3816 gets the inferred type: <Literal>forall a. Num a =&gt; a -&gt; a -&gt; a</Literal>.
3817 </Para>
3818 </ListItem>
3819
3820 </ItemizedList>
3821
3822 </Para>
3823
3824 </Sect2>
3825
3826 <Sect2>
3827 <Title>Result type signatures</Title>
3828
3829 <Para>
3830
3831 <ItemizedList>
3832 <ListItem>
3833
3834 <Para>
3835  The result type of a function can be given a signature,
3836 thus:
3837
3838
3839 <ProgramListing>
3840   f (x::a) :: [a] = [x,x,x]
3841 </ProgramListing>
3842
3843
3844 The final <Literal>:: [a]</Literal> after all the patterns gives a signature to the
3845 result type.  Sometimes this is the only way of naming the type variable
3846 you want:
3847
3848
3849 <ProgramListing>
3850   f :: Int -> [a] -> [a]
3851   f n :: ([a] -> [a]) = let g (x::a, y::a) = (y,x)
3852                         in \xs -> map g (reverse xs `zip` xs)
3853 </ProgramListing>
3854
3855
3856 </Para>
3857 </ListItem>
3858
3859 </ItemizedList>
3860
3861 </Para>
3862
3863 <Para>
3864 Result type signatures are not yet implemented in Hugs.
3865 </Para>
3866
3867 </Sect2>
3868
3869 <Sect2>
3870 <Title>Pattern signatures on other constructs</Title>
3871
3872 <Para>
3873
3874 <ItemizedList>
3875 <ListItem>
3876
3877 <Para>
3878  A pattern type signature can be on an arbitrary sub-pattern, not
3879 just on a variable:
3880
3881
3882 <ProgramListing>
3883   f ((x,y)::(a,b)) = (y,x) :: (b,a)
3884 </ProgramListing>
3885
3886
3887 </Para>
3888 </ListItem>
3889 <ListItem>
3890
3891 <Para>
3892  Pattern type signatures, including the result part, can be used
3893 in lambda abstractions:
3894
3895
3896 <ProgramListing>
3897   (\ (x::a, y) :: a -> x)
3898 </ProgramListing>
3899
3900
3901 Type variables bound by these patterns must be polymorphic in
3902 the sense defined above.
3903 For example:
3904
3905
3906 <ProgramListing>
3907   f1 (x::c) = f1 x      -- ok
3908   f2 = \(x::c) -> f2 x  -- not ok
3909 </ProgramListing>
3910
3911
3912 Here, <Function>f1</Function> is OK, but <Function>f2</Function> is not, because <VarName>c</VarName> gets unified
3913 with a type variable free in the environment, in this
3914 case, the type of <Function>f2</Function>, which is in the environment when
3915 the lambda abstraction is checked.
3916
3917 </Para>
3918 </ListItem>
3919 <ListItem>
3920
3921 <Para>
3922  Pattern type signatures, including the result part, can be used
3923 in <Literal>case</Literal> expressions:
3924
3925
3926 <ProgramListing>
3927   case e of { (x::a, y) :: a -> x }
3928 </ProgramListing>
3929
3930
3931 The pattern-bound type variables must, as usual,
3932 be polymorphic in the following sense: each case alternative,
3933 considered as a lambda abstraction, must be polymorphic.
3934 Thus this is OK:
3935
3936
3937 <ProgramListing>
3938   case (True,False) of { (x::a, y) -> x }
3939 </ProgramListing>
3940
3941
3942 Even though the context is that of a pair of booleans,
3943 the alternative itself is polymorphic.  Of course, it is
3944 also OK to say:
3945
3946
3947 <ProgramListing>
3948   case (True,False) of { (x::Bool, y) -> x }
3949 </ProgramListing>
3950
3951
3952 </Para>
3953 </ListItem>
3954 <ListItem>
3955
3956 <Para>
3957 To avoid ambiguity, the type after the &ldquo;<Literal>::</Literal>&rdquo; in a result
3958 pattern signature on a lambda or <Literal>case</Literal> must be atomic (i.e. a single
3959 token or a parenthesised type of some sort).  To see why,
3960 consider how one would parse this:
3961
3962
3963 <ProgramListing>
3964   \ x :: a -> b -> x
3965 </ProgramListing>
3966
3967
3968 </Para>
3969 </ListItem>
3970 <ListItem>
3971
3972 <Para>
3973  Pattern type signatures that bind new type variables
3974 may not be used in pattern bindings at all.
3975 So this is illegal:
3976
3977
3978 <ProgramListing>
3979   f x = let (y, z::a) = x in ...
3980 </ProgramListing>
3981
3982
3983 But these are OK, because they do not bind fresh type variables:
3984
3985
3986 <ProgramListing>
3987   f1 x            = let (y, z::Int) = x in ...
3988   f2 (x::(Int,a)) = let (y, z::a)   = x in ...
3989 </ProgramListing>
3990
3991
3992 However a single variable is considered a degenerate function binding,
3993 rather than a degerate pattern binding, so this is permitted, even
3994 though it binds a type variable:
3995
3996
3997 <ProgramListing>
3998   f :: (b->b) = \(x::b) -> x
3999 </ProgramListing>
4000
4001
4002 </Para>
4003 </ListItem>
4004
4005 </ItemizedList>
4006
4007 Such degnerate function bindings do not fall under the monomorphism
4008 restriction.  Thus:
4009 </Para>
4010
4011 <Para>
4012
4013 <ProgramListing>
4014   g :: a -> a -> Bool = \x y. x==y
4015 </ProgramListing>
4016
4017 </Para>
4018
4019 <Para>
4020 Here <Function>g</Function> has type <Literal>forall a. Eq a =&gt; a -&gt; a -&gt; Bool</Literal>, just as if
4021 <Function>g</Function> had a separate type signature.  Lacking a type signature, <Function>g</Function>
4022 would get a monomorphic type.
4023 </Para>
4024
4025 </Sect2>
4026
4027 <Sect2>
4028 <Title>Existentials</Title>
4029
4030 <Para>
4031
4032 <ItemizedList>
4033 <ListItem>
4034
4035 <Para>
4036  Pattern type signatures can bind existential type variables.
4037 For example:
4038
4039
4040 <ProgramListing>
4041   data T = forall a. MkT [a]
4042
4043   f :: T -> T
4044   f (MkT [t::a]) = MkT t3
4045                  where
4046                    t3::[a] = [t,t,t]
4047 </ProgramListing>
4048
4049
4050 </Para>
4051 </ListItem>
4052
4053 </ItemizedList>
4054
4055 </Para>
4056
4057 </Sect2>
4058
4059 </Sect1>
4060
4061 <Sect1 id="pragmas">
4062 <Title>Pragmas
4063 </Title>
4064
4065 <Para>
4066 GHC supports several pragmas, or instructions to the compiler placed
4067 in the source code.  Pragmas don't affect the meaning of the program,
4068 but they might affect the efficiency of the generated code.
4069 </Para>
4070
4071 <Sect2 id="inline-pragma">
4072 <Title>INLINE pragma
4073
4074 <IndexTerm><Primary>INLINE pragma</Primary></IndexTerm>
4075 <IndexTerm><Primary>pragma, INLINE</Primary></IndexTerm></Title>
4076
4077 <Para>
4078 GHC (with <Option>-O</Option>, as always) tries to inline (or &ldquo;unfold&rdquo;)
4079 functions/values that are &ldquo;small enough,&rdquo; thus avoiding the call
4080 overhead and possibly exposing other more-wonderful optimisations.
4081 </Para>
4082
4083 <Para>
4084 You will probably see these unfoldings (in Core syntax) in your
4085 interface files.
4086 </Para>
4087
4088 <Para>
4089 Normally, if GHC decides a function is &ldquo;too expensive&rdquo; to inline, it
4090 will not do so, nor will it export that unfolding for other modules to
4091 use.
4092 </Para>
4093
4094 <Para>
4095 The sledgehammer you can bring to bear is the
4096 <Literal>INLINE</Literal><IndexTerm><Primary>INLINE pragma</Primary></IndexTerm> pragma, used thusly:
4097
4098 <ProgramListing>
4099 key_function :: Int -> String -> (Bool, Double)
4100
4101 #ifdef __GLASGOW_HASKELL__
4102 {-# INLINE key_function #-}
4103 #endif
4104 </ProgramListing>
4105
4106 (You don't need to do the C pre-processor carry-on unless you're going
4107 to stick the code through HBC&mdash;it doesn't like <Literal>INLINE</Literal> pragmas.)
4108 </Para>
4109
4110 <Para>
4111 The major effect of an <Literal>INLINE</Literal> pragma is to declare a function's
4112 &ldquo;cost&rdquo; to be very low.  The normal unfolding machinery will then be
4113 very keen to inline it.
4114 </Para>
4115
4116 <Para>
4117 An <Literal>INLINE</Literal> pragma for a function can be put anywhere its type
4118 signature could be put.
4119 </Para>
4120
4121 <Para>
4122 <Literal>INLINE</Literal> pragmas are a particularly good idea for the
4123 <Literal>then</Literal>/<Literal>return</Literal> (or <Literal>bind</Literal>/<Literal>unit</Literal>) functions in a monad.
4124 For example, in GHC's own <Literal>UniqueSupply</Literal> monad code, we have:
4125
4126 <ProgramListing>
4127 #ifdef __GLASGOW_HASKELL__
4128 {-# INLINE thenUs #-}
4129 {-# INLINE returnUs #-}
4130 #endif
4131 </ProgramListing>
4132
4133 </Para>
4134
4135 </Sect2>
4136
4137 <Sect2 id="noinline-pragma">
4138 <Title>NOINLINE pragma
4139 </Title>
4140
4141 <Para>
4142 <IndexTerm><Primary>NOINLINE pragma</Primary></IndexTerm>
4143 <IndexTerm><Primary>pragma, NOINLINE</Primary></IndexTerm>
4144 </Para>
4145
4146 <Para>
4147 The <Literal>NOINLINE</Literal> pragma does exactly what you'd expect: it stops the
4148 named function from being inlined by the compiler.  You shouldn't ever
4149 need to do this, unless you're very cautious about code size.
4150 </Para>
4151
4152 </Sect2>
4153
4154 <Sect2 id="specialize-pragma">
4155 <Title>SPECIALIZE pragma
4156 </Title>
4157
4158 <Para>
4159 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
4160 <IndexTerm><Primary>pragma, SPECIALIZE</Primary></IndexTerm>
4161 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
4162 </Para>
4163
4164 <Para>
4165 (UK spelling also accepted.)  For key overloaded functions, you can
4166 create extra versions (NB: more code space) specialised to particular
4167 types.  Thus, if you have an overloaded function:
4168 </Para>
4169
4170 <Para>
4171
4172 <ProgramListing>
4173 hammeredLookup :: Ord key => [(key, value)] -> key -> value
4174 </ProgramListing>
4175
4176 </Para>
4177
4178 <Para>
4179 If it is heavily used on lists with <Literal>Widget</Literal> keys, you could
4180 specialise it as follows:
4181
4182 <ProgramListing>
4183 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
4184 </ProgramListing>
4185
4186 </Para>
4187
4188 <Para>
4189 To get very fancy, you can also specify a named function to use for
4190 the specialised value, by adding <Literal>= blah</Literal>, as in:
4191
4192 <ProgramListing>
4193 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
4194 </ProgramListing>
4195
4196 It's <Emphasis>Your Responsibility</Emphasis> to make sure that <Function>blah</Function> really
4197 behaves as a specialised version of <Function>hammeredLookup</Function>!!!
4198 </Para>
4199
4200 <Para>
4201 NOTE: the <Literal>=blah</Literal> feature isn't implemented in GHC 4.xx.
4202 </Para>
4203
4204 <Para>
4205 An example in which the <Literal>= blah</Literal> form will Win Big:
4206
4207 <ProgramListing>
4208 toDouble :: Real a => a -> Double
4209 toDouble = fromRational . toRational
4210
4211 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
4212 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
4213 </ProgramListing>
4214
4215 The <Function>i2d</Function> function is virtually one machine instruction; the
4216 default conversion&mdash;via an intermediate <Literal>Rational</Literal>&mdash;is obscenely
4217 expensive by comparison.
4218 </Para>
4219
4220 <Para>
4221 By using the US spelling, your <Literal>SPECIALIZE</Literal> pragma will work with
4222 HBC, too.  Note that HBC doesn't support the <Literal>= blah</Literal> form.
4223 </Para>
4224
4225 <Para>
4226 A <Literal>SPECIALIZE</Literal> pragma for a function can be put anywhere its type
4227 signature could be put.
4228 </Para>
4229
4230 </Sect2>
4231
4232 <Sect2 id="specialize-instance-pragma">
4233 <Title>SPECIALIZE instance pragma
4234 </Title>
4235
4236 <Para>
4237 <IndexTerm><Primary>SPECIALIZE pragma</Primary></IndexTerm>
4238 <IndexTerm><Primary>overloading, death to</Primary></IndexTerm>
4239 Same idea, except for instance declarations.  For example:
4240
4241 <ProgramListing>
4242 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
4243
4244 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
4245 </ProgramListing>
4246
4247 Compatible with HBC, by the way.
4248 </Para>
4249
4250 </Sect2>
4251
4252 <Sect2 id="line-pragma">
4253 <Title>LINE pragma
4254 </Title>
4255
4256 <Para>
4257 <IndexTerm><Primary>LINE pragma</Primary></IndexTerm>
4258 <IndexTerm><Primary>pragma, LINE</Primary></IndexTerm>
4259 </Para>
4260
4261 <Para>
4262 This pragma is similar to C's <Literal>&num;line</Literal> pragma, and is mainly for use in
4263 automatically generated Haskell code.  It lets you specify the line
4264 number and filename of the original code; for example
4265 </Para>
4266
4267 <Para>
4268
4269 <ProgramListing>
4270 {-# LINE 42 "Foo.vhs" #-}
4271 </ProgramListing>
4272
4273 </Para>
4274
4275 <Para>
4276 if you'd generated the current file from something called <Filename>Foo.vhs</Filename>
4277 and this line corresponds to line 42 in the original.  GHC will adjust
4278 its error messages to refer to the line/file named in the <Literal>LINE</Literal>
4279 pragma.
4280 </Para>
4281
4282 </Sect2>
4283
4284 <Sect2>
4285 <Title>RULES pragma</Title>
4286
4287 <Para>
4288 The RULES pragma lets you specify rewrite rules.  It is described in
4289 <XRef LinkEnd="rewrite-rules">.
4290 </Para>
4291
4292 </Sect2>
4293
4294 </Sect1>
4295
4296 <Sect1 id="rewrite-rules">
4297 <Title>Rewrite rules
4298
4299 <IndexTerm><Primary>RULES pagma</Primary></IndexTerm>
4300 <IndexTerm><Primary>pragma, RULES</Primary></IndexTerm>
4301 <IndexTerm><Primary>rewrite rules</Primary></IndexTerm></Title>
4302
4303 <Para>
4304 The programmer can specify rewrite rules as part of the source program
4305 (in a pragma).  GHC applies these rewrite rules wherever it can.
4306 </Para>
4307
4308 <Para>
4309 Here is an example:
4310
4311 <ProgramListing>
4312   {-# RULES
4313         "map/map"       forall f g xs. map f (map g xs) = map (f.g) xs
4314   #-}
4315 </ProgramListing>
4316
4317 </Para>
4318
4319 <Sect2>
4320 <Title>Syntax</Title>
4321
4322 <Para>
4323 From a syntactic point of view:
4324
4325 <ItemizedList>
4326 <ListItem>
4327
4328 <Para>
4329  Each rule has a name, enclosed in double quotes.  The name itself has
4330 no significance at all.  It is only used when reporting how many times the rule fired.
4331 </Para>
4332 </ListItem>
4333 <ListItem>
4334
4335 <Para>
4336  There may be zero or more rules in a <Literal>RULES</Literal> pragma.
4337 </Para>
4338 </ListItem>
4339 <ListItem>
4340
4341 <Para>
4342  Layout applies in a <Literal>RULES</Literal> pragma.  Currently no new indentation level
4343 is set, so you must lay out your rules starting in the same column as the
4344 enclosing definitions.
4345 </Para>
4346 </ListItem>
4347 <ListItem>
4348
4349 <Para>
4350  Each variable mentioned in a rule must either be in scope (e.g. <Function>map</Function>),
4351 or bound by the <Literal>forall</Literal> (e.g. <Function>f</Function>, <Function>g</Function>, <Function>xs</Function>).  The variables bound by
4352 the <Literal>forall</Literal> are called the <Emphasis>pattern</Emphasis> variables.  They are separated
4353 by spaces, just like in a type <Literal>forall</Literal>.
4354 </Para>
4355 </ListItem>
4356 <ListItem>
4357
4358 <Para>
4359  A pattern variable may optionally have a type signature.
4360 If the type of the pattern variable is polymorphic, it <Emphasis>must</Emphasis> have a type signature.
4361 For example, here is the <Literal>foldr/build</Literal> rule:
4362
4363 <ProgramListing>
4364 "fold/build"  forall k z (g::forall b. (a->b->b) -> b -> b) .
4365               foldr k z (build g) = g k z
4366 </ProgramListing>
4367
4368 Since <Function>g</Function> has a polymorphic type, it must have a type signature.
4369
4370 </Para>
4371 </ListItem>
4372 <ListItem>
4373
4374 <Para>
4375 The left hand side of a rule must consist of a top-level variable applied
4376 to arbitrary expressions.  For example, this is <Emphasis>not</Emphasis> OK:
4377
4378 <ProgramListing>
4379 "wrong1"   forall e1 e2.  case True of { True -> e1; False -> e2 } = e1
4380 "wrong2"   forall f.      f True = True
4381 </ProgramListing>
4382
4383 In <Literal>"wrong1"</Literal>, the LHS is not an application; in <Literal>"wrong1"</Literal>, the LHS has a pattern variable
4384 in the head.
4385 </Para>
4386 </ListItem>
4387 <ListItem>
4388
4389 <Para>
4390  A rule does not need to be in the same module as (any of) the
4391 variables it mentions, though of course they need to be in scope.
4392 </Para>
4393 </ListItem>
4394 <ListItem>
4395
4396 <Para>
4397  Rules are automatically exported from a module, just as instance declarations are.
4398 </Para>
4399 </ListItem>
4400
4401 </ItemizedList>
4402
4403 </Para>
4404
4405 </Sect2>
4406
4407 <Sect2>
4408 <Title>Semantics</Title>
4409
4410 <Para>
4411 From a semantic point of view:
4412
4413 <ItemizedList>
4414 <ListItem>
4415
4416 <Para>
4417 Rules are only applied if you use the <Option>-O</Option> flag.
4418 </Para>
4419 </ListItem>
4420
4421 <ListItem>
4422 <Para>
4423  Rules are regarded as left-to-right rewrite rules.
4424 When GHC finds an expression that is a substitution instance of the LHS
4425 of a rule, it replaces the expression by the (appropriately-substituted) RHS.
4426 By "a substitution instance" we mean that the LHS can be made equal to the
4427 expression by substituting for the pattern variables.
4428
4429 </Para>
4430 </ListItem>
4431 <ListItem>
4432
4433 <Para>
4434  The LHS and RHS of a rule are typechecked, and must have the
4435 same type.
4436
4437 </Para>
4438 </ListItem>
4439 <ListItem>
4440
4441 <Para>
4442  GHC makes absolutely no attempt to verify that the LHS and RHS
4443 of a rule have the same meaning.  That is undecideable in general, and
4444 infeasible in most interesting cases.  The responsibility is entirely the programmer's!
4445
4446 </Para>
4447 </ListItem>
4448 <ListItem>
4449
4450 <Para>
4451  GHC makes no attempt to make sure that the rules are confluent or
4452 terminating.  For example:
4453
4454 <ProgramListing>
4455   "loop"        forall x,y.  f x y = f y x
4456 </ProgramListing>
4457
4458 This rule will cause the compiler to go into an infinite loop.
4459
4460 </Para>
4461 </ListItem>
4462 <ListItem>
4463
4464 <Para>
4465  If more than one rule matches a call, GHC will choose one arbitrarily to apply.
4466
4467 </Para>
4468 </ListItem>
4469 <ListItem>
4470 <Para>
4471  GHC currently uses a very simple, syntactic, matching algorithm
4472 for matching a rule LHS with an expression.  It seeks a substitution
4473 which makes the LHS and expression syntactically equal modulo alpha
4474 conversion.  The pattern (rule), but not the expression, is eta-expanded if
4475 necessary.  (Eta-expanding the epression can lead to laziness bugs.)
4476 But not beta conversion (that's called higher-order matching).
4477 </Para>
4478
4479 <Para>
4480 Matching is carried out on GHC's intermediate language, which includes
4481 type abstractions and applications.  So a rule only matches if the
4482 types match too.  See <XRef LinkEnd="rule-spec"> below.
4483 </Para>
4484 </ListItem>
4485 <ListItem>
4486
4487 <Para>
4488  GHC keeps trying to apply the rules as it optimises the program.
4489 For example, consider:
4490
4491 <ProgramListing>
4492   let s = map f
4493       t = map g
4494   in
4495   s (t xs)
4496 </ProgramListing>
4497
4498 The expression <Literal>s (t xs)</Literal> does not match the rule <Literal>"map/map"</Literal>, but GHC
4499 will substitute for <VarName>s</VarName> and <VarName>t</VarName>, giving an expression which does match.
4500 If <VarName>s</VarName> or <VarName>t</VarName> was (a) used more than once, and (b) large or a redex, then it would
4501 not be substituted, and the rule would not fire.
4502
4503 </Para>
4504 </ListItem>
4505 <ListItem>
4506
4507 <Para>
4508  In the earlier phases of compilation, GHC inlines <Emphasis>nothing
4509 that appears on the LHS of a rule</Emphasis>, because once you have substituted
4510 for something you can't match against it (given the simple minded
4511 matching).  So if you write the rule
4512
4513 <ProgramListing>
4514         "map/map"       forall f,g.  map f . map g = map (f.g)
4515 </ProgramListing>
4516
4517 this <Emphasis>won't</Emphasis> match the expression <Literal>map f (map g xs)</Literal>.
4518 It will only match something written with explicit use of ".".
4519 Well, not quite.  It <Emphasis>will</Emphasis> match the expression
4520
4521 <ProgramListing>
4522 wibble f g xs
4523 </ProgramListing>
4524
4525 where <Function>wibble</Function> is defined:
4526
4527 <ProgramListing>
4528 wibble f g = map f . map g
4529 </ProgramListing>
4530
4531 because <Function>wibble</Function> will be inlined (it's small).
4532
4533 Later on in compilation, GHC starts inlining even things on the
4534 LHS of rules, but still leaves the rules enabled.  This inlining
4535 policy is controlled by the per-simplification-pass flag <Option>-finline-phase</Option><Emphasis>n</Emphasis>.
4536
4537 </Para>
4538 </ListItem>
4539 <ListItem>
4540
4541 <Para>
4542  All rules are implicitly exported from the module, and are therefore
4543 in force in any module that imports the module that defined the rule, directly
4544 or indirectly.  (That is, if A imports B, which imports C, then C's rules are
4545 in force when compiling A.)  The situation is very similar to that for instance
4546 declarations.
4547 </Para>
4548 </ListItem>
4549
4550 </ItemizedList>
4551
4552 </Para>
4553
4554 </Sect2>
4555
4556 <Sect2>
4557 <Title>List fusion</Title>
4558
4559 <Para>
4560 The RULES mechanism is used to implement fusion (deforestation) of common list functions.
4561 If a "good consumer" consumes an intermediate list constructed by a "good producer", the
4562 intermediate list should be eliminated entirely.
4563 </Para>
4564
4565 <Para>
4566 The following are good producers:
4567
4568 <ItemizedList>
4569 <ListItem>
4570
4571 <Para>
4572  List comprehensions
4573 </Para>
4574 </ListItem>
4575 <ListItem>
4576
4577 <Para>
4578  Enumerations of <Literal>Int</Literal> and <Literal>Char</Literal> (e.g. <Literal>['a'..'z']</Literal>).
4579 </Para>
4580 </ListItem>
4581 <ListItem>
4582
4583 <Para>
4584  Explicit lists (e.g. <Literal>[True, False]</Literal>)
4585 </Para>
4586 </ListItem>
4587 <ListItem>
4588
4589 <Para>
4590  The cons constructor (e.g <Literal>3:4:[]</Literal>)
4591 </Para>
4592 </ListItem>
4593 <ListItem>
4594
4595 <Para>
4596  <Function>++</Function>
4597 </Para>
4598 </ListItem>
4599 <ListItem>
4600
4601 <Para>
4602  <Function>map</Function>
4603 </Para>
4604 </ListItem>
4605 <ListItem>
4606
4607 <Para>
4608  <Function>filter</Function>
4609 </Para>
4610 </ListItem>
4611 <ListItem>
4612
4613 <Para>
4614  <Function>iterate</Function>, <Function>repeat</Function>
4615 </Para>
4616 </ListItem>
4617 <ListItem>
4618
4619 <Para>
4620  <Function>zip</Function>, <Function>zipWith</Function>
4621 </Para>
4622 </ListItem>
4623
4624 </ItemizedList>
4625
4626 </Para>
4627
4628 <Para>
4629 The following are good consumers:
4630
4631 <ItemizedList>
4632 <ListItem>
4633
4634 <Para>
4635  List comprehensions
4636 </Para>
4637 </ListItem>
4638 <ListItem>
4639
4640 <Para>
4641  <Function>array</Function> (on its second argument)
4642 </Para>
4643 </ListItem>
4644 <ListItem>
4645
4646 <Para>
4647  <Function>length</Function>
4648 </Para>
4649 </ListItem>
4650 <ListItem>
4651
4652 <Para>
4653  <Function>++</Function> (on its first argument)
4654 </Para>
4655 </ListItem>
4656 <ListItem>
4657
4658 <Para>
4659  <Function>map</Function>
4660 </Para>
4661 </ListItem>
4662 <ListItem>
4663
4664 <Para>
4665  <Function>filter</Function>
4666 </Para>
4667 </ListItem>
4668 <ListItem>
4669
4670 <Para>
4671  <Function>concat</Function>
4672 </Para>
4673 </ListItem>
4674 <ListItem>
4675
4676 <Para>
4677  <Function>unzip</Function>, <Function>unzip2</Function>, <Function>unzip3</Function>, <Function>unzip4</Function>
4678 </Para>
4679 </ListItem>
4680 <ListItem>
4681
4682 <Para>
4683  <Function>zip</Function>, <Function>zipWith</Function> (but on one argument only; if both are good producers, <Function>zip</Function>
4684 will fuse with one but not the other)
4685 </Para>
4686 </ListItem>
4687 <ListItem>
4688
4689 <Para>
4690  <Function>partition</Function>
4691 </Para>
4692 </ListItem>
4693 <ListItem>
4694
4695 <Para>
4696  <Function>head</Function>
4697 </Para>
4698 </ListItem>
4699 <ListItem>
4700
4701 <Para>
4702  <Function>and</Function>, <Function>or</Function>, <Function>any</Function>, <Function>all</Function>
4703 </Para>
4704 </ListItem>
4705 <ListItem>
4706
4707 <Para>
4708  <Function>sequence&lowbar;</Function>
4709 </Para>
4710 </ListItem>
4711 <ListItem>
4712
4713 <Para>
4714  <Function>msum</Function>
4715 </Para>
4716 </ListItem>
4717 <ListItem>
4718
4719 <Para>
4720  <Function>sortBy</Function>
4721 </Para>
4722 </ListItem>
4723
4724 </ItemizedList>
4725
4726 </Para>
4727
4728 <Para>
4729 So, for example, the following should generate no intermediate lists:
4730
4731 <ProgramListing>
4732 array (1,10) [(i,i*i) | i &#60;- map (+ 1) [0..9]]
4733 </ProgramListing>
4734
4735 </Para>
4736
4737 <Para>
4738 This list could readily be extended; if there are Prelude functions that you use
4739 a lot which are not included, please tell us.
4740 </Para>
4741
4742 <Para>
4743 If you want to write your own good consumers or producers, look at the
4744 Prelude definitions of the above functions to see how to do so.
4745 </Para>
4746
4747 </Sect2>
4748
4749 <Sect2 id="rule-spec">
4750 <Title>Specialisation
4751 </Title>
4752
4753 <Para>
4754 Rewrite rules can be used to get the same effect as a feature
4755 present in earlier version of GHC:
4756
4757 <ProgramListing>
4758   {-# SPECIALIZE fromIntegral :: Int8 -> Int16 = int8ToInt16 #-}
4759 </ProgramListing>
4760
4761 This told GHC to use <Function>int8ToInt16</Function> instead of <Function>fromIntegral</Function> whenever
4762 the latter was called with type <Literal>Int8 -&gt; Int16</Literal>.  That is, rather than
4763 specialising the original definition of <Function>fromIntegral</Function> the programmer is
4764 promising that it is safe to use <Function>int8ToInt16</Function> instead.
4765 </Para>
4766
4767 <Para>
4768 This feature is no longer in GHC.  But rewrite rules let you do the
4769 same thing:
4770
4771 <ProgramListing>
4772 {-# RULES
4773   "fromIntegral/Int8/Int16" fromIntegral = int8ToInt16
4774 #-}
4775 </ProgramListing>
4776
4777 This slightly odd-looking rule instructs GHC to replace <Function>fromIntegral</Function>
4778 by <Function>int8ToInt16</Function> <Emphasis>whenever the types match</Emphasis>.  Speaking more operationally,
4779 GHC adds the type and dictionary applications to get the typed rule
4780
4781 <ProgramListing>
4782 forall (d1::Integral Int8) (d2::Num Int16) .
4783         fromIntegral Int8 Int16 d1 d2 = int8ToInt16
4784 </ProgramListing>
4785
4786 What is more,
4787 this rule does not need to be in the same file as fromIntegral,
4788 unlike the <Literal>SPECIALISE</Literal> pragmas which currently do (so that they
4789 have an original definition available to specialise).
4790 </Para>
4791
4792 </Sect2>
4793
4794 <Sect2>
4795 <Title>Controlling what's going on</Title>
4796
4797 <Para>
4798
4799 <ItemizedList>
4800 <ListItem>
4801
4802 <Para>
4803  Use <Option>-ddump-rules</Option> to see what transformation rules GHC is using.
4804 </Para>
4805 </ListItem>
4806 <ListItem>
4807
4808 <Para>
4809  Use <Option>-ddump-simpl-stats</Option> to see what rules are being fired.
4810 If you add <Option>-dppr-debug</Option> you get a more detailed listing.
4811 </Para>
4812 </ListItem>
4813 <ListItem>
4814
4815 <Para>
4816  The defintion of (say) <Function>build</Function> in <FileName>PrelBase.lhs</FileName> looks llike this:
4817
4818 <ProgramListing>
4819         build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
4820         {-# INLINE build #-}
4821         build g = g (:) []
4822 </ProgramListing>
4823
4824 Notice the <Literal>INLINE</Literal>!  That prevents <Literal>(:)</Literal> from being inlined when compiling
4825 <Literal>PrelBase</Literal>, so that an importing module will &ldquo;see&rdquo; the <Literal>(:)</Literal>, and can
4826 match it on the LHS of a rule.  <Literal>INLINE</Literal> prevents any inlining happening
4827 in the RHS of the <Literal>INLINE</Literal> thing.  I regret the delicacy of this.
4828
4829 </Para>
4830 </ListItem>
4831 <ListItem>
4832
4833 <Para>
4834  In <Filename>ghc/lib/std/PrelBase.lhs</Filename> look at the rules for <Function>map</Function> to
4835 see how to write rules that will do fusion and yet give an efficient
4836 program even if fusion doesn't happen.  More rules in <Filename>PrelList.lhs</Filename>.
4837 </Para>
4838 </ListItem>
4839
4840 </ItemizedList>
4841
4842 </Para>
4843
4844 </Sect2>
4845
4846 </Sect1>