f909c59af2b4344a2653921b74fbdff036c24c0a
[ghc-hetmet.git] / ghc / docs / libraries / libs.sgml
1 <!doctype linuxdoc system>
2
3 <!-- ToDo:
4   o Add indexing support (to linuxdoc)
5   o Fix citations in html
6   -->
7
8 <article>
9
10 <title>The Hugs-GHC Extension Libraries
11 <author>The Hugs/GHC Team
12 <date>August 1998
13 <abstract>
14 Hugs and GHC provide a common set of libraries to aid portability.
15 This document specifies the interfaces to these libraries and documents
16 known differences.
17 </abstract>
18
19 <toc>
20
21 <sect> <idx/Naming conventions/ 
22 <label id="sec:Naming conventions">
23 <p>
24
25 The set of interfaces specified in this document try to adhere to the
26 following naming conventions: 
27
28 <itemize>
29 <item>
30 Actions that create a new values have the prefix <tt/new/ followed by
31 the name of the type of object they're creating, e.g., <tt/newIORef/,
32 <tt/newChan/ etc.
33 <item>
34 Operations that read a value from a mutable object are prefixed with
35 <tt/read/, and operations that update the contents have the prefix
36 <tt/write/, e.g., <tt/readChan/, <tt/readIOArray/.
37
38 Notes: 
39 <itemize>
40 <item>
41 This differs from the convention used to name the operations for
42 reading and writing to a file <tt/Handle/, where <tt/get/ and <tt/put/
43 are used instead.
44 <item>
45 Operations provided by various concurrency abstractions, e.g., <tt/MVar/,
46 <tt/CVar/ , also deviate from this naming scheme. This is perhaps
47 defensible, since the read and write operations have additional
48 behaviour, e.g., <tt/takeMVar/ tries to read the current value
49 of an <tt/MVar/, locking it if it succeeds.
50 </itemize>
51 <item>
52 Conversions operators have the form <tt/AToB/ where <tt/A/ and <tt/B/
53 are the types we're converting between.
54 <item>
55 Operations that lazily read values from a mutable object/handle, have
56 the form <tt/getXContents/, e.g., <tt/Channel.getChanContents/ and
57 <tt/IO.hGetContents/. (OK, so the latter isn't called
58 <tt/getHandleContents/, but you hopefully get the picture.)
59 <item>
60 Overloaded operators that convert values to some fixed type are named
61 <tt/toX/, where <tt/X/ is the type we're converting into, e.g.,
62 <tt/toInt/, <tt/toDyn/.
63 <p>
64 Similarly for overloaded coercion operations that go the other way,
65 from a known type to an overloaded one. These have the prefix
66 <tt/from/ followed by the name of the type we're converting from,
67 e.g., <tt/fromInteger/, <tt/fromDyn/, <tt/fromDynamic/.
68
69 </itemize>
70
71 <sect> <idx/ST/ 
72 <label id="sec:ST">
73 <p>
74
75 This library provides support for <em/strict/ state threads, as
76 described in the PLDI '94 paper by John Launchbury and Simon Peyton
77 Jones <cite id="LazyStateThreads">.  In addition to the monad <tt/ST/,
78 it also provides mutable variables <tt/STRef/ and mutable arrays
79 <tt/STArray/.
80
81 <tscreen><verb>
82 module ST( module ST, module Monad ) where
83 import Monad
84
85 data ST s a        -- abstract type
86 runST              :: forall a. (forall s. ST s a) -> a
87 fixST              :: (a -> ST s a) -> ST s a
88 unsafeInterleaveST :: ST s a -> ST s a
89 instance Functor (ST s)
90 instance Monad   (ST s)
91
92 data STRef s a     -- mutable variables in state thread s
93                    -- containing values of type a.
94 newSTRef           :: a -> ST s (STRef s a)
95 readSTRef          :: STRef s a -> ST s a
96 writeSTRef         :: STRef s a -> a -> ST s ()
97 instance Eq (STRef s a)
98
99 data STArray s ix elt -- mutable arrays in state thread s
100                       -- indexed by values of type ix
101                       -- containing values of type a.
102 newSTArray          :: Ix ix => (ix,ix) -> elt -> ST s (STArray s ix elt)
103 boundsSTArray       :: Ix ix => STArray s ix elt -> (ix, ix)
104 readSTArray         :: Ix ix => STArray s ix elt -> ix -> ST s elt
105 writeSTArray        :: Ix ix => STArray s ix elt -> ix -> elt -> ST s ()
106 thawSTArray         :: Ix ix => Array ix elt -> ST s (STArray s ix elt)
107 freezeSTArray       :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
108 unsafeFreezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)  
109 instance Eq (STArray s ix elt)
110 </verb></tscreen>
111
112 Notes:
113 <itemize>
114
115 <item> 
116 GHC also supports ByteArrays --- these aren't supported by Hugs yet.
117
118 <item> 
119 The operations <tt/freezeSTArray/ and <tt/thawSTArray/ convert mutable
120 arrays to and from immutable arrays.  Semantically, they are identical
121 to copying the array and they are usually implemented that way.  The
122 operation <tt/unsafeFreezeSTArray/ is a faster version of
123 <tt/freezeSTArray/ which omits the copying step.  It's a safe substitute for
124 <tt/freezeSTArray/ if you don't modify the mutable array after freezing it.
125
126 <item>
127 In the current version of Hugs, the <tt/<idx/runST// operation,
128 used to specify encapsulation, is implemented as a language construct,
129 and <tt/runST/ is treated as a keyword.  We plan to change this to match
130 GHC soon.
131
132 <!-- 
133   <item>
134      Note that it is possible to install Hugs 1.4 without support for lazy
135      state threads, and hence the primitives described here may not be
136      available in all implementations.  Also, in contrast with the
137      implementation of lazy state threads in previous releases of Hugs and
138      Gofer, there is no direct relationship between the
139      <tt/<idx/ST monad// and the <tt/<idx/IO monad//.
140   -->
141
142 <item>
143 Hugs provides <tt/thenLazyST/ and <tt/thenStrictST/ so that you can
144 import <tt/LazyST/ (say) and still use the strict instance in those
145 places where it matters.  GHC implements LazyST and ST using different
146 types, so this isn't possible.
147 </item>
148
149 </itemize>
150
151 <sect> <idx/LazyST/ 
152 <label id="sec:LazyST">
153 <p>
154
155 This library is identical to <tt/ST/ except that the <tt/ST/ monad
156 instance is <em/lazy/.  The lazy ST monad tends to be more prone to
157 space leaks than the strict version, so most programmers will use the
158 former unless laziness is explicitly required.  <tt/LazyST/ provides
159 two additional operations:
160
161 <tscreen> <verb>
162 lazyToStrictST :: LazyST.ST s a -> ST.ST s a
163 strictToLazyST :: ST.ST s a -> LazyST.ST s a
164 </verb> </tscreen>
165
166 These are used to convert between lazy and strict state threads.  The
167 semantics with respect to laziness are as you would expect: the strict
168 state thread passed to <tt/strictToLazyST/ is not performed until the
169 result of the lazy state thread it returns is demanded.
170
171 <sect> <idx/IOExts/
172 <label id="sec:IOExts">
173 <p>
174
175 This library provides the following extensions to the IO monad:
176
177 <tscreen><verb>
178 module IOExts where
179
180 fixIO               :: (a -> IO a) -> IO a
181 unsafePerformIO     :: IO a -> a
182 unsafeInterleaveIO  :: IO a -> IO a
183                     
184 data IORef a        -- mutable variables containing values of type a
185 newIORef            :: a -> IO (IORef a)
186 readIORef           :: IORef a -> IO a
187 writeIORef          :: IORef a -> a -> IO ()
188 instance Eq (IORef a)
189
190 data IOArray ix elt -- mutable arrays indexed by values of type ix
191                     -- containing values of type a.
192 newIOArray          :: Ix ix => (ix,ix) -> elt -> IO (IOArray ix elt)
193 boundsIOArray       :: Ix ix => IOArray ix elt -> (ix, ix)
194 readIOArray         :: Ix ix => IOArray ix elt -> ix -> IO elt
195 writeIOArray        :: Ix ix => IOArray ix elt -> ix -> elt -> IO ()
196 freezeIOArray       :: Ix ix => IOArray ix elt -> IO (Array ix elt)
197 instance Eq (IOArray ix elt)
198
199 openFileEx          :: FilePath -> IOModeEx -> IO Handle
200 data IOModeEx = BinaryMode IO.IOMode | TextMode IO.IOMode
201 instance Eq IOModeEx
202 instance Read IOModeEx
203 instance Show IOModeEx
204
205 performGC           :: IO ()
206 trace               :: String -> a -> a
207 unsafePtrEq         :: a -> a -> Bool
208
209 unsafeIOToST        :: IO a -> ST s a
210 </verb></tscreen>
211
212 <itemize>
213 <item>
214 The operations <tt/fixIO/, <tt/unsafePerformIO/ and <tt/unsafeInterleaveIO/
215 described in <cite id="ImperativeFP">
216
217 <item>
218 References (aka mutable variables) and mutable arrays (but no form of 
219 mutable byte arrays)
220
221 <item>
222 <tt/openFileEx/ extends the standard <tt/openFile/ action with support
223 for opening binary files. On platforms that make no distinction
224 between text and binary files, <tt/openFileEx/ is indistinguishable
225 from <tt/openFile/.
226
227 <item>
228 <tt/performGC/ triggers an immediate garbage collection
229
230 <item>
231 When called, <tt/trace/ prints the string in its first argument, and then
232 returns the second argument as its result.  The <tt/trace/ function is not
233 referentially transparent, and should only be used for debugging, or for
234 monitoring execution. 
235
236 <!--
237   You should also be warned that, unless you understand some of the
238   details about the way that Haskell programs are executed, results
239   obtained using <tt/trace/ can be rather confusing.  For example, the
240   messages may not appear in the order that you expect.  Even ignoring the
241   output that they produce, adding calls to <tt/trace/ can change the
242   semantics of your program.  Consider this a warning!
243   -->
244
245 <item>
246 <tt/unsafePtrEq/ compares two values for pointer equality without
247 evaluating them.  The results are not referentially transparent and
248 may vary significantly from one compiler to another or in the face of
249 semantics-preserving program changes.  However, pointer equality is useful
250 in creating a number of referentially transparent constructs such as this
251 simplified memoisation function:
252
253 <tscreen><verb>
254 > cache :: (a -> b) -> (a -> b)
255 > cache f = \x -> unsafePerformIO (check x)
256 >  where
257 >   ref = unsafePerformIO (newIORef (error "cache", error "cache"))
258 >   check x = readIORef ref >>= \ (x',a) ->
259 >              if x `unsafePtrEq` x' then
260 >                return a
261 >              else
262 >                let a = f x in
263 >                writeIORef ref (x, a) >>
264 >                return a
265 </verb></tscreen>
266
267 <item>
268 The <tt/unsafeIOToST/ action provides a loop hole for lifting an
269 <tt/IO/ action into the <tt/ST/ monad. This is a potentially unsafe
270 thing to do, so the onus is on the programmer to ensure that the
271 use of <tt/unsafeIOToST/ does not ruin underlying program properties
272 such as referential transparency.
273 </itemize>
274
275 <!--
276   <sect> <idx/GlaExts/ <p>
277   
278   This library provides a convenient bundle of most of the extensions
279   available in GHC and Hugs.  This module is generally more stable than
280   the other modules of non-standard extensions so you might choose to 
281   import them from here rather than going straight to the horses mouth.
282   
283   <tscreen><verb>
284   module GlaExts( module GlaExts, module IOExts, module ST, module Addr ) where
285   import IOExts
286   import ST
287   import Addr
288   trace              :: String -> a -> a
289   performGC          :: IO ()
290   </verb></tscreen>
291   
292   The GHC version also provides the types <tt/PrimIO/, <tt/RealWorld/,
293   <tt/ByteArray/, <tt/Lift/ and operations on these types. It also
294   provides the unboxed views of the types
295   <tt/Int/, 
296   <tt/Addr/, 
297   <tt/Word/, 
298   <tt/Float/, 
299   <tt/Double/, 
300   <tt/Integer/ and
301   <tt/Char/ 
302   and a number of ``primitive operations'' (<tt/+&num/,
303   <tt/plusFloat&num/, etc.).
304   
305   -->
306
307 <sect> <idx/Bits/
308 <label id="sec:Bits">
309 <p>
310
311 This library defines bitwise operations for signed and unsigned ints.
312
313 <tscreen><verb>
314 module Bits where
315 infixl 8 `shift`, `rotate`
316 infixl 7 .&.
317 infixl 6 `xor`
318 infixl 5 .|.
319
320 class Bits a where
321   (.&.), (.|.), xor :: a -> a -> a
322   complement        :: a -> a
323   shift             :: a -> Int -> a
324   rotate            :: a -> Int -> a
325   bit               :: Int -> a        
326   setBit            :: a -> Int -> a   
327   clearBit          :: a -> Int -> a   
328   complementBit     :: a -> Int -> a   
329   testBit           :: a -> Int -> Bool
330   bitSize           :: a -> Int
331   isSigned          :: a -> Bool
332
333 shiftL, shiftR   :: Bits a => a -> Int -> a
334 rotateL, rotateR :: Bits a => a -> Int -> a
335 shiftL  a i = shift  a i
336 shiftR  a i = shift  a (-i)
337 rotateL a i = rotate a i
338 rotateR a i = rotate a (-i)
339 </verb></tscreen>
340
341 Notes:
342 <itemize>
343 <item>
344   <tt/bitSize/ and <tt/isSigned/ are like <tt/floatRadix/ and <tt/floatDigits/
345   -- they return parameters of the <em/type/ of their argument rather than 
346   of the particular argument they are applied to.  <tt/bitSize/ returns
347   the number of bits in the type; and <tt/isSigned/ returns whether
348   the type is signed or not.
349 <item>
350   <tt/shift/ performs sign extension on signed number types.
351   That is, right shifts fill the top bits with 1 if the number is negative
352   and with 0 otherwise.
353 <item>
354   Bits are numbered from 0 with bit 0 being the least significant bit.
355 <item>
356   <tt/shift x i/ and <tt/rotate x i/ shift to the left if <tt/i/ is
357   positive and to the right otherwise.  
358 <!--
359   <item>
360     <tt/rotate/ is well defined only if bitSize returns a number.
361     (Maybe we should impose a Bounded constraint on it?)
362   -->
363 <item>
364   <tt/bit i/ is the value with the i'th bit set.
365 </itemize>
366
367 <sect> <idx/Word/
368 <label id="sec:Word">
369 <p>
370
371 This library provides unsigned integers of various sizes.
372 The types supported are as follows:
373
374 <tabular ca="ll">
375 type    | number of bits @
376 <!-- <hline>  -->
377 Word8    | 8  @
378 Word16   | 16 @
379 Word32   | 32 @
380 Word64   | 64 @
381 <!-- <hline>  -->
382 </tabular>
383
384 For each type <it/W/ above, we provide the following functions and
385 instances.  The type <it/I/ refers to the signed integer type of the
386 same size.
387
388 <tscreen><verb>
389 data W            -- Unsigned Ints
390 instance Eq       W
391 instance Ord      W
392 instance Show     W
393 instance Read     W
394 instance Bounded  W
395 instance Num      W
396 instance Real     W
397 instance Integral W
398 instance Enum     W
399 instance Ix       W
400 instance Bits     W
401 </verb></tscreen>
402 Plus
403 <tscreen><verb>
404 word8ToWord32  :: Word8  -> Word32
405 word32ToWord8  :: Word32 -> Word8
406 word16ToWord32 :: Word16 -> Word32
407 word32ToWord16 :: Word32 -> Word16
408
409 word8ToInt     :: Word8  -> Int
410 intToWord8     :: Int    -> Word8
411 word16ToInt    :: Word16 -> Int
412 intToWord16    :: Int    -> Word16
413 word32ToInt    :: Word32 -> Int
414 intToWord32    :: Int    -> Word32
415 </verb></tscreen>
416
417 Notes: 
418 <itemize>
419 <item>
420   All arithmetic is performed modulo 2^n
421
422   One non-obvious consequequence of this is that <tt/negate/
423   should <em/not/ raise an error on negative arguments.
424
425 <item>
426 The coercion <tt/wToI/ converts an unsigned n-bit value to the
427 signed n-bit value with the same representation.  For example,
428 <tt/word8ToInt8 0xff = -1/. 
429 Likewise, <tt/iToW/ converts signed n-bit values to the
430 corresponding unsigned n-bit value.
431
432 <item>
433 ToDo: complete the set of coercion functions.
434
435 <item>
436 Use <tt/Prelude.fromIntegral :: (Integral a, Num b) => a -> b/ to
437 coerce between different sizes or to preserve sign when converting
438 between values of the same size.
439
440 <item>
441 It would be very natural to add a type a type <tt/Natural/ providing
442 an unbounded size unsigned integer --- just as <tt/Integer/ provides
443 unbounded size signed integers.  We do not do that yet since there is
444 no demand for it.  Doing so would require <tt/Bits.bitSize/ to return
445 <tt/Maybe Int/.
446
447 <item>
448 The <tt/Enum/ instances stop when they reach their upper or lower
449 bound --- they don't overflow the way the <tt/Int/ and <tt/Float/
450 instances do.
451
452 <item>
453 It would be useful to provide a function (or a family of functions?)
454 which coerced between any two Word types (without going through
455 Integer).
456
457 </itemize>
458
459 Hugs only provides <tt/Eq/, <tt/Ord/, <tt/Read/ and <tt/Show/
460 instances for <tt/Word64/ at the moment.
461
462 <sect> <idx/Int/
463 <label id="sec:Int">
464 <p>
465
466 This library provides signed integers of various sizes.  The types
467 supported are as follows:
468
469 <tabular ca="ll">
470 type    | number of bits @ 
471 <!-- <hline>  -->
472 Int8    | 8  @
473 Int16   | 16 @
474 Int32   | 32 @
475 Int64   | 64 @
476 <!-- <hline>  -->
477 </tabular>
478
479 For each type <it/I/ above, we provide the following instances.
480
481 <tscreen><verb>
482 data I            -- Signed Ints
483 iToInt            :: I -> Int  -- not provided for Int64
484 intToi            :: Int -> I  -- not provided for Int64
485 instance Eq       I
486 instance Ord      I
487 instance Show     I
488 instance Read     I
489 instance Bounded  I
490 instance Num      I
491 instance Real     I
492 instance Integral I
493 instance Enum     I
494 instance Ix       I
495 instance Bits     I
496 </verb></tscreen>
497 Plus
498 <tscreen><verb>
499 int8ToInt  :: Int8  -> Int
500 intToInt8  :: Int   -> Int8
501 int16ToInt :: Int16 -> Int
502 intToInt16 :: Int   -> Int16
503 int32ToInt :: Int32 -> Int
504 intToInt32 :: Int   -> Int32
505 </verb></tscreen>
506
507 <itemize>
508 <item>
509 Hugs does not provide <tt/Int64/ at the moment.
510
511 <item>
512 ToDo: complete the set of coercion functions.
513
514 </itemize>
515
516 <sect> <idx/Addr/
517 <label id="sec:Addr">
518 <p>
519
520 This library provides machine addresses and is primarily intended for 
521 use in creating foreign function interfaces using GreenCard.
522
523 <tscreen><verb>
524 module Addr where
525 data Addr  -- Address type
526 instance Eq Addr
527
528 nullAddr           :: Addr
529 plusAddr           :: Addr -> Int -> Addr
530
531 -- read value out of _immutable_ memory
532 indexCharOffAddr   :: Addr -> Int -> Char
533 indexIntOffAddr    :: Addr -> Int -> Int     -- should we drop this?
534 indexAddrOffAddr   :: Addr -> Int -> Addr
535 indexFloatOffAddr  :: Addr -> Int -> Float
536 indexDoubleOffAddr :: Addr -> Int -> Double
537 indexWord8OffAddr  :: Addr -> Int -> Word8
538 indexWord16OffAddr :: Addr -> Int -> Word16
539 indexWord32OffAddr :: Addr -> Int -> Word32
540 indexWord64OffAddr :: Addr -> Int -> Word64
541 indexInt8OffAddr   :: Addr -> Int -> Int8
542 indexInt16OffAddr  :: Addr -> Int -> Int16
543 indexInt32OffAddr  :: Addr -> Int -> Int32
544 indexInt64OffAddr  :: Addr -> Int -> Int64
545
546 -- read value out of mutable memory
547 readCharOffAddr    :: Addr -> Int -> IO Char
548 readIntOffAddr     :: Addr -> Int -> IO Int  -- should we drop this?
549 readAddrOffAddr    :: Addr -> Int -> IO Addr
550 readFloatOffAddr   :: Addr -> Int -> IO Float
551 readDoubleOffAddr  :: Addr -> Int -> IO Double
552 readWord8OffAddr   :: Addr -> Int -> IO Word8
553 readWord16OffAddr  :: Addr -> Int -> IO Word16
554 readWord32OffAddr  :: Addr -> Int -> IO Word32
555 readWord64OffAddr  :: Addr -> Int -> IO Word64
556 readInt8OffAddr    :: Addr -> Int -> IO Int8
557 readInt16OffAddr   :: Addr -> Int -> IO Int16
558 readInt32OffAddr   :: Addr -> Int -> IO Int32
559 readInt64OffAddr   :: Addr -> Int -> IO Int64
560
561 -- write value into mutable memory
562 writeCharOffAddr   :: Addr -> Int -> Char   -> IO ()
563 writeIntOffAddr    :: Addr -> Int -> Int    -> IO ()  -- should we drop this?
564 writeAddrOffAddr   :: Addr -> Int -> Addr   -> IO ()
565 writeFloatOffAddr  :: Addr -> Int -> Float  -> IO ()
566 writeDoubleOffAddr :: Addr -> Int -> Double -> IO ()
567 writeWord8OffAddr  :: Addr -> Int -> Word8  -> IO ()
568 writeWord16OffAddr :: Addr -> Int -> Word16 -> IO ()
569 writeWord32OffAddr :: Addr -> Int -> Word32 -> IO ()
570 writeWord64OffAddr :: Addr -> Int -> Word64 -> IO ()
571 writeInt8OffAddr   :: Addr -> Int -> Int8   -> IO ()
572 writeInt16OffAddr  :: Addr -> Int -> Int16  -> IO ()
573 writeInt32OffAddr  :: Addr -> Int -> Int32  -> IO ()
574 writeInt64OffAddr  :: Addr -> Int -> Int64  -> IO ()
575 </verb></tscreen>
576
577 Hugs provides <tt/Addr/ and <tt/nullAddr/ but does not provide any of
578 the index, read or write functions.  They can be implemented using 
579 GreenCard if required.
580
581 <sect> <idx/NumExts/
582 <label id="sec:NumExts">
583 <p>
584
585 The <tt/NumExts/ interface collect together various numeric
586 operations that have proven to be commonly useful 
587
588 <tscreen> <verb>
589 -- Going between Doubles and Floats:
590 doubleToFloat :: Double -> Float
591 floatToDouble :: Float  -> Double
592
593 showHex       :: Integral a => a -> ShowS
594 showOct       :: Integral a => a -> ShowS
595 </verb> </tscreen>
596
597 Notes: 
598 <itemize>
599 <item>
600     If <tt/doubleToFloat/ is applied to a <tt/Double/ that is within
601     the representable range for <tt/Float/, the result may be the next
602     higher or lower representable <tt/Float/ value. If the <tt/Double/
603     is out of range, the result is undefined.
604 <item>
605     No loss of precision occurs in the other direction with
606     <tt/floatToDouble/, the floating value remains unchanged.
607 <item>
608     <tt/showOct/ and <tt/showHex/ will prefix <tt/0o/ and <tt/0x/
609     respectively. Like <tt/Numeric.showInt/, these show functions
610     work on positive numbers only.
611 </itemize>
612
613 <sect> <idx/Foreign/
614 <label id="sec:Foreign">
615 <p>
616
617 This module provides two types to better allow the Haskell world to
618 share its data with the outside world (and vice versa), <em/foreign
619 objects/ and <em/stable pointers/:
620
621 <tscreen><verb>
622 module Foreign where
623 data ForeignObj  -- abstract, instance of: Eq
624
625 makeForeignObj  :: Addr{-object-} -> Addr{-finaliser-} -> IO ForeignObj
626 writeForeignObj :: ForeignObj -> Addr{-new value-} -> IO ()
627
628 data StablePtr a  -- abstract, instance of: Eq.
629 makeStablePtr  :: a -> IO (StablePtr a)
630 deRefStablePtr :: StablePtr a -> IO a
631 freeStablePtr  :: StablePtr a -> IO ()
632 </verb> </tscreen>
633
634 <itemize>
635 <item>The <tt/ForeignObj/ type provides foreign objects, encapsulated
636 references to values outside the Haskell heap. Foreign objects are
637 finalised by the garbage collector when they become dead. The
638 finaliser to use is given as second argument to <tt/makeForeignOj/,
639 and is currently a function pointer to a C function with
640 the following signature
641
642 <tscreen><verb>
643 void finaliseFO(void* obj);
644 </verb></tscreen>
645
646 The finaliser is passed the reference to the external object (i.e.,
647 the first argument to <tt/makeForeignObj/.)
648
649 <item>
650 The <tt/writeForeignObj/ lets you overwrite the encapsulated foreign
651 reference with another.
652
653 <item>
654 Stable pointers allow you to hand out references to Haskell heap
655 objects to the outside world. <bf/ToDo:/ <em/say more./
656 </itemize>
657
658 In addition to the above, the following operations for indexing via
659 a <tt/ForeignObj/ are also, mirrored on the same operations provided
660 over <tt/Addr/s:
661
662 <tscreen><verb>
663 indexCharOffForeignObj   :: ForeignObj -> Int -> Char
664 indexIntOffForeignObj    :: ForeignObj -> Int -> Int
665 indexAddrOffForeignObj   :: ForeignObj -> Int -> Addr
666 indexFloatOffForeignObj  :: ForeignObj -> Int -> Float
667 indexDoubleOffForeignObj :: ForeignObj -> Int -> Double
668 indexWord8OffForeignObj  :: ForeignObj -> Int -> Word8
669 indexWord16OffForeignObj :: ForeignObj -> Int -> Word16
670 indexWord32OffForeignObj :: ForeignObj -> Int -> Word32
671 indexWord64OffForeignObj :: ForeignObj -> Int -> Word64
672
673 indexInt8OffForeignObj  :: ForeignObj -> Int -> Int8
674 indexInt16OffForeignObj :: ForeignObj -> Int -> Int16
675 indexInt32OffForeignObj :: ForeignObj -> Int -> Int32
676 indexInt64OffForeignObj :: ForeignObj -> Int -> Int64
677
678 -- read value out of mutable memory
679 readCharOffForeignObj    :: ForeignObj -> Int -> IO Char
680 readIntOffForeignObj     :: ForeignObj -> Int -> IO Int
681 readAddrOffForeignObj    :: ForeignObj -> Int -> IO Addr
682 readFloatOffForeignObj   :: ForeignObj -> Int -> IO Float
683 readDoubleOffForeignObj  :: ForeignObj -> Int -> IO Double
684 readWord8OffForeignObj   :: ForeignObj -> Int -> IO Word8
685 readWord16OffForeignObj  :: ForeignObj -> Int -> IO Word16
686 readWord32OffForeignObj  :: ForeignObj -> Int -> IO Word32
687 readWord64OffForeignObj  :: ForeignObj -> Int -> IO Word64
688 readInt8OffForeignObj    :: ForeignObj -> Int -> IO Int8
689 readInt16OffForeignObj   :: ForeignObj -> Int -> IO Int16
690 readInt32OffForeignObj   :: ForeignObj -> Int -> IO Int32
691 readInt64OffForeignObj   :: ForeignObj -> Int -> IO Int64
692
693 writeCharOffForeignObj   :: ForeignObj -> Int -> Char   -> IO ()
694 writeIntOffForeignObj    :: ForeignObj -> Int -> Int    -> IO ()
695 writeAddrOffForeignObj   :: ForeignObj -> Int -> Addr   -> IO ()
696 writeFloatOffForeignObj  :: ForeignObj -> Int -> Float  -> IO ()
697 writeDoubleOffForeignObj :: ForeignObj -> Int -> Double -> IO ()
698 writeWord8OffForeignObj  :: ForeignObj -> Int -> Word8  -> IO ()
699 writeWord16OffForeignObj :: ForeignObj -> Int -> Word16 -> IO ()
700 writeWord32OffForeignObj :: ForeignObj -> Int -> Word32 -> IO ()
701 writeWord64OffForeignObj :: ForeignObj -> Int -> Word64 -> IO ()
702 writeInt8OffForeignObj   :: ForeignObj -> Int -> Int8   -> IO ()
703 writeInt16OffForeignObj  :: ForeignObj -> Int -> Int16  -> IO ()
704 writeInt32OffForeignObj  :: ForeignObj -> Int -> Int32  -> IO ()
705 writeInt64OffForeignObj  :: ForeignObj -> Int -> Int64  -> IO ()
706 </verb></tscreen>
707
708 <sect> <idx/Concurrent/
709 <label id="sec:Concurrent">
710 <p>
711
712 This library provides the Concurrent Haskell extensions
713 <cite id="concurrentHaskell:popl96">.
714
715 We are grateful to the Glasgow Haskell Project for allowing us to
716 redistribute their implementation of this module.
717
718 <tscreen><verb>
719 module Concurrent where
720
721 data ThreadId    -- thread identifiers
722 instance Eq  ThreadId
723 instance Ord ThreadId
724
725 forkIO           :: IO () -> IO ThreadId
726 killThread       :: ThreadId -> IO ()
727
728 data MVar a      -- Synchronisation variables
729 newEmptyMVar     :: IO (MVar a)
730 newMVar          :: a -> IO (MVar a)
731 takeMVar         :: MVar a -> IO a
732 putMVar          :: MVar a -> a -> IO ()
733 swapMVar         :: MVar a -> a -> IO a
734 readMVar         :: MVar a -> IO a 
735 instance Eq (MVar a)
736
737 data Chan a      -- channels
738 newChan          :: IO (Chan a)
739 writeChan        :: Chan a -> a -> IO ()
740 readChan         :: Chan a -> IO a
741 dupChan          :: Chan a -> IO (Chan a)
742 unReadChan       :: Chan a -> a -> IO ()
743 getChanContents  :: Chan a -> IO [a]
744 writeList2Chan   :: Chan a -> [a] -> IO ()
745                       
746 data CVar a       -- one element channels
747 newCVar          :: IO (CVar a)
748 putCVar          :: CVar a -> a -> IO ()
749 getCVar          :: CVar a -> IO a
750                       
751 data QSem        -- General/quantity semaphores
752 newQSem          :: Int  -> IO QSem
753 waitQSem         :: QSem -> IO ()
754 signalQSem       :: QSem -> IO ()
755                       
756 data QSemN       -- General/quantity semaphores
757 newQSemN         :: Int   -> IO QSemN
758 waitQSemN        :: QSemN -> Int -> IO ()
759 signalQSemN      :: QSemN -> Int -> IO ()
760
761 type SampleVar a -- Sample variables 
762 newEmptySampleVar:: IO (SampleVar a)
763 newSampleVar     :: a -> IO (SampleVar a)
764 emptySampleVar   :: SampleVar a -> IO ()
765 readSampleVar    :: SampleVar a -> IO a
766 writeSampleVar   :: SampleVar a -> a -> IO ()
767 </verb></tscreen>
768
769 Notes:
770 <itemize>
771
772 <item> 
773   GHC uses preemptive multitasking:
774   Context switches can occur at any time, except if you call a C
775   function (like \verb"getchar") that blocks waiting for input.
776
777   Hugs uses cooperative multitasking:
778   Context switches only occur when you use one of the primitives
779   defined in this module.  This means that programs such as:
780
781 <tscreen><verb>
782 main = forkIO (write 'a') >> write 'b'
783  where write c = putChar c >> write c
784 </verb></tscreen>
785
786   will print either <tt/aaaaaaaaaaaaaa.../ or <tt/bbbbbbbbbbbb.../,
787   instead of some random interleaving of <tt/a/s and <tt/b/s.
788
789   In practice, cooperative multitasking is sufficient for writing 
790   simple graphical user interfaces.
791
792 <item>
793 Hugs does not provide the functions <tt/mergeIO/ or <tt/nmergeIO/ since these
794 require preemptive multitasking.
795
796 <item>
797 Thread identities and <tt/killThread/ has not been implemented yet on
798 either system. The plan is that <tt/killThread/ will raise an IO
799 exception in the killed thread which it can catch --- perhaps allowing -->
800 --it to kill its children before exiting.
801
802 <item>
803 The <tt/Ord/ instance for <tt/ThreadId/s provides an arbitrary total ordering
804 which might be used to build an ordered binary tree, say.  
805
806 </itemize>
807
808 <sect> <idx/Dynamic/ 
809 <label id="sec:Dynamic">
810 <p>
811
812 The <tt/Dynamic/ library provides cheap-and-cheerful dynamic types for
813 Haskell. A dynamically typed value is one which carries type
814 information with it at run-time, and is represented by the
815 abstract type <tt/Dynamic/. Values can be converted into <tt/Dynamic/
816 ones, which can then be combined and manipulated by the program using
817 the operations provided over the abstract, dynamic type. One of
818 these operations allows you to convert a dynamically-typed value back
819 into a value with the same (monomorphic) type it had before converting
820 it into a dynamically-typed value.
821
822 The <tt/Dynamic/ library is capable of dealing with monomorphic types
823 only; no support for polymorphic dynamic values, but hopefully that
824 can be added at a later stage.
825
826 Examples where this library may come in handy (dynamic types, really -
827 hopefully the library provided here will suffice) are: persistent
828 programming, interpreters, distributed programming etc.
829
830 The following operations are provided over the <tt/Dynamic/ type:
831
832 <tscreen> <verb>
833 data Dynamic -- abstract, instance of: Show --
834
835 toDyn       :: Typeable a => a -> Dynamic
836 fromDyn     :: Typeable a => Dynamic -> a -> a
837 fromDynamic :: Typeable a => Dynamic -> Maybe a
838 </verb></tscreen>
839
840 <itemize>
841 <item> <tt/toDyn/ converts a value into a dynamic one, provided
842 <tt/toDyn/ knows the (concrete) type representation of the value.
843 The <tt/Typeable/ type class is used to encode this, overloading a
844 function that returns the type representation of a value. More on this
845 below.
846 <item> There's two ways of going from a dynamic value to one with
847 a concrete type: <tt/fromDyn/, tries to convert the dynamic value into
848 a value with the same type as its second argument. If this fails, the
849 default second argument is just returned. <tt/fromDynamic/ returns a
850 <tt/Maybe/ type instead, <tt/Nothing/ coming back if the conversion
851 was not possible.
852 <item>
853 The <tt/Dynamic/ type has got a <tt/Show/ instance which returns
854 a pretty printed string of the type of the dynamic value. (Useful when
855 debugging).
856 </itemize>
857
858 <sect1>  The <tt/Dynamic/ type
859 <nidx/The Dynamic type/ 
860 <label id="sec:Dynamic:TypeRep">
861 <p>
862
863 Haskell types are represented as terms using the <tt/TypeRep/
864 abstract type:
865
866 <tscreen> <verb>
867 data TypeRep  -- abstract, instance of: Eq, Show
868 data TyCon    -- abstract, instance of: Eq, Show
869
870 mkTyCon  :: String  -> TyCon
871 mkAppTy  :: TyCon   -> [TypeRep] -> TypeRep
872 mkFunTy  :: TypeRep -> TypeRep   -> TypeRep
873 applyTy  :: TypeRep -> TypeRep   -> Maybe TypeRep
874 </verb></tscreen>
875
876 <itemize>
877 <item> <tt/mkAppTy/ applies a type constructor to a sequence of types,
878 returning a type.
879 <item> <tt/mkFunTy/ is a special case of <tt/mkAppTy/, applying
880 the function type constructor to a pair of types.
881 <item> <tt/applyTy/ applies a type to a function type. If possible,
882 the result type is returned.
883 <item> Type constructors are represented by the abstract type,
884 <tt/TyCon/. 
885 <item>
886 Most importantly, <tt/TypeRep/s can be compared for equality.
887 Type equality is used when converting a <tt/Dynamic/ value into a
888 value of some specific type, comparing the type representation that
889 the <tt/Dynamic/ value embeds with equality of the type representation
890 of the type we're trying to convert the dynamically-typed value into.
891 <item> 
892 To allow comparisons between <tt/TypeRep/s to be implemented
893 efficiently, the <em/abstract/ <tt/TyCon/ type is used, with
894 the constructor function <tt/mkTyCon/ provided:
895
896 <tscreen> <verb>
897 mkTyCon :: String -> TyCon 
898 </verb></tscreen>
899
900 An implementation of the <tt/Dynamic/ interface guarantees the
901 following,
902
903 <tscreen> <verb>
904  mkTyCon "a" == mkTyCon "a"
905 </verb></tscreen>
906
907 A really efficient implementation is possible if we guarantee/demand
908 that the strings are unique, and for a particular type constructor,
909 the application <tt/mkTyCon/ to the string that represents the type
910 constructor is never duplicated. Provided you follow the 
911 the author of <tt/Typeable/
912
913  &lsqb;<bf/Q:/ <em>Would this constraint be
914 unworkable in practice?</em>&rsqb;
915 <item>
916 Both <tt/TyCon/ and <tt/TypeRep/ are instances of the <tt/Show/ type
917 classes. To have tuple types be shown in infix form, the <tt/Show/
918 instance guarantees that type constructors consisting of <tt/n/-commas,
919 i.e., (<tt/mkTyCon ",,,,"/), is shown as an <tt/(n+1)/ tuple in infix
920 form.
921 </itemize>
922
923 <sect1>  <idx/Representing types/ 
924 <label id="sec:Dynamic:Typeable">
925 <p>
926
927 To ease the construction of <tt/Dynamic/ values, we
928 introduce the following type class to help working with <tt/TypeRep/s:
929
930 <tscreen><verb>
931 class Typeable a where
932   typeOf :: a -> TypeRep
933 </verb></tscreen>
934
935 <itemize>
936 <item> The <tt/typeOf/ function is overloaded to return the type
937 representation associated with a type. 
938 <item> <bf/Important:/ The argument to <tt/typeOf/ is only used to
939 carry type information around so that overloading can be resolved.
940 <tt/Typeable/ instances should never, ever look at this argument.
941 <item> The <tt/Dynamic/ library provide <tt/Typeable/ instances 
942 for all Prelude and Hugs/GHC extension library types. They are:
943
944 <tscreen><verb>
945 Prelude types: 
946    Int, Char, Bool, Float, Double, Integer, (IO a),
947    [a], (Either a b), (Maybe a), (a->b), 
948    (), (,), (,,), (,,,), (,,,,),
949    Ordering, Complex, Array, Handle
950 Hugs/GHC types:
951    Addr, Word8, Word16, Word32, Word64,
952    Int8,Int16,Int32,Int64,
953    ForeignObj, MVar, (ST s a), (StablePtr a)
954 GHC types:
955    Word, ByteArray, MutableByteArray
956 </verb></tscreen>
957
958 </itemize>
959
960 <sect1>  <idx/Utility functions/ 
961 <label id="sec:Dynamic:util">
962 <p>
963
964 Operations for applying a dynamic function type to a
965 dynamically typed argument are commonly useful, and
966 also provided:
967
968 <tscreen> <verb>
969 dynApply   :: Dynamic -> Dynamic -> Dynamic -- unsafe.
970 dynApplyMb :: Dynamic -> Dynamic -> Maybe Dynamic
971 </verb></tscreen>
972
973
974 <sect> <idx/GetOpt/
975 <label id="sec:GetOpt">
976 <p>
977
978 The <tt/GetOpt/ library contains Sven Panne's Haskell implementation
979 of <tt/getopt/, providing features nigh-on identical to GNU <tt/getopt/:
980
981 <tscreen><verb>
982 module GetOpt where
983
984 -- representing a single option:
985 data OptDescr a
986  = Option [Char]         --    list of short option characters
987           [String]       --    list of long option strings (without "--")
988           (ArgDescr a)   --    argument descriptor
989           String         --    explanation of option for user
990
991 -- argument option:
992 data ArgDescr a
993    = NoArg                   a         --    no argument expected
994    | ReqArg (String       -> a) String --    option requires argument
995    | OptArg (Maybe String -> a) String --    optional argument
996
997 usageInfo :: String          -- header
998           -> [OptDescr a]    -- options recognised 
999           -> String          -- nicely formatted decription of options
1000
1001 getOpt :: ArgOrder a    -- non-option handling
1002        -> [OptDescr a]  -- options recognised
1003        -> [String]      -- the command-line
1004        -> ( [a]         -- options
1005           , [String]    -- non-options
1006           ,[String]     -- error messages
1007           )
1008
1009 data ArgOrder a
1010   = RequireOrder
1011   | Permute
1012   | ReturnInOrder (String -> a)
1013
1014 </verb></tscreen>
1015
1016 <itemize>
1017 <item> The command-line options recognised is described by a list of
1018 <tt/OptDescr/ values. The <tt/OptDescr/ describes the long and short
1019 strings that recognise the option, together with a help string and
1020 info on whether the option takes extra arguments, if any.
1021 <item>
1022 From a list of option values, <tt/usageInfo/ returns a nicely
1023 formatted string that enumerates the different options supported
1024 together with a short message about what
1025 <item>
1026 To decode a command-line with respect to a list of options,
1027 <tt/getOpt/ is used. It processes the command-line, and returns
1028 the list of values that matched (and those that didn't). The first
1029 argument to <tt/getOpt/ controls whether the user is to give the
1030 options in any old order or not.
1031 </itemize>
1032
1033 To hopefully illuminate the role of the different <tt/GetOpt/ data
1034 structures, here's the command-line options for a (very simple)
1035 compiler:
1036
1037 <tscreen><verb>
1038 module Opts where
1039
1040 import GetOpt
1041 import Maybe ( fromMaybe )
1042
1043 data Flag 
1044  = Verbose  | Version 
1045  | Input String | Output String | LibDir String
1046    deriving Show
1047
1048 options :: [OptDescr Flag]
1049 options =
1050  [ Option ['v']     ["verbose"] (NoArg Verbose)       "chatty output on stderr"
1051  , Option ['V','?'] ["version"] (NoArg Version)       "show version number"
1052  , Option ['o']     ["output"]  (OptArg outp "FILE")  "output FILE"
1053  , Option ['c']     []          (OptArg inp  "FILE")  "input FILE"
1054  , Option ['L']     ["libdir"]  (ReqArg LibDir "DIR") "library directory"
1055  ]
1056
1057 inp,outp :: Maybe String -> Flag
1058 outp = Output . fromMaybe "stdout"
1059 inp  = Input  . fromMaybe "stdout"
1060
1061 compilerOpts :: [String] -> IO ([Flag], [String])
1062 compilerOpts argv = 
1063    case (getOpt Permute options argv) of
1064       (o,n,[]  ) -> return (o,n)
1065       (_,_,errs) -> fail (userError (concat errs ++ usageInfo header options))
1066   where header = "Usage: ic [OPTION...] files..."
1067 </verb></tscreen>
1068
1069
1070 <sect> <idx/Pretty/
1071 <label id="sec:Pretty">
1072 <p>
1073
1074 This library contains Simon Peyton Jones' implementation of John
1075 Hughes's pretty printer combinators.
1076
1077 <tscreen><verb>
1078 module Pretty where
1079 infixl 6 <> 
1080 infixl 6 <+>
1081 infixl 5 $$, $+$
1082 data Doc  -- the Document datatype
1083
1084 -- The primitive Doc values
1085 empty                     :: Doc
1086 text                      :: String   -> Doc 
1087 char                      :: Char     -> Doc
1088 int                       :: Int      -> Doc
1089 integer                   :: Integer  -> Doc
1090 float                     :: Float    -> Doc
1091 double                    :: Double   -> Doc
1092 rational                  :: Rational -> Doc
1093 semi, comma, colon, space, equals              :: Doc
1094 lparen, rparen, lbrack, rbrack, lbrace, rbrace :: Doc
1095 parens, brackets, braces  :: Doc -> Doc 
1096 quotes, doubleQuotes      :: Doc -> Doc
1097
1098 -- Combining Doc values
1099 (<>)   :: Doc -> Doc -> Doc     -- Beside
1100 hcat   :: [Doc] -> Doc          -- List version of <>
1101 (<+>)  :: Doc -> Doc -> Doc     -- Beside, separated by space
1102 hsep   :: [Doc] -> Doc          -- List version of <+>
1103 ($$)   :: Doc -> Doc -> Doc     -- Above; if there is no
1104                                   -- overlap it "dovetails" the two
1105 vcat   :: [Doc] -> Doc          -- List version of $$
1106 cat    :: [Doc] -> Doc          -- Either hcat or vcat
1107 sep    :: [Doc] -> Doc          -- Either hsep or vcat
1108 fcat   :: [Doc] -> Doc          -- ``Paragraph fill'' version of cat
1109 fsep   :: [Doc] -> Doc          -- ``Paragraph fill'' version of sep
1110 nest   :: Int -> Doc -> Doc     -- Nested
1111 hang   :: Doc -> Int -> Doc -> Doc
1112 punctuate :: Doc -> [Doc] -> [Doc]      
1113 -- punctuate p [d1, ... dn] = [d1 <> p, d2 <> p, ... dn-1 <> p, dn]
1114
1115 -- Displaying Doc values
1116 instance Show Doc
1117 render     :: Doc -> String             -- Uses default style
1118 renderStyle  :: Style -> Doc -> String
1119 data Style = Style { lineLength     :: Int,   -- In chars
1120                        ribbonsPerLine :: Float, -- Ratio of ribbon length
1121                                                 -- to line length
1122                        mode :: Mode
1123                }
1124 data Mode = PageMode            -- Normal 
1125             | ZigZagMode          -- With zig-zag cuts
1126             | LeftMode            -- No indentation, infinitely long lines
1127             | OneLineMode         -- All on one line
1128 </verb></tscreen>
1129
1130 <biblio files="refs" style="abbrv">
1131
1132
1133 </article>
1134