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