1 <!doctype linuxdoc system>
4 o Add indexing support (to linuxdoc)
5 o Fix citations in html
10 <title>The Hugs-GHC Extension Libraries
11 <author>The Hugs/GHC Team
14 Hugs and GHC provide a common set of libraries to aid portability.
15 This document specifies the interfaces to these libraries and documents
21 <sect> <idx/Naming conventions/
22 <label id="sec:Naming conventions">
25 The set of interfaces specified in this document try to adhere to the
26 following naming conventions:
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/,
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/.
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/
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.
52 Conversions operators have the form <tt/AToB/ where <tt/A/ and <tt/B/
53 are the types we're converting between.
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.)
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/.
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/.
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
82 module ST( module ST, module Monad ) where
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)
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)
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)
116 GHC also supports ByteArrays --- these aren't supported by Hugs yet.
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.
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
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//.
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.
152 <label id="sec:LazyST">
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:
162 lazyToStrictST :: LazyST.ST s a -> ST.ST s a
163 strictToLazyST :: ST.ST s a -> LazyST.ST s a
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.
172 <label id="sec:IOExts">
175 This library provides the following extensions to the IO monad:
180 fixIO :: (a -> IO a) -> IO a
181 unsafePerformIO :: IO a -> a
182 unsafeInterleaveIO :: IO a -> IO a
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)
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)
199 openFileEx :: FilePath -> IOModeEx -> IO Handle
200 data IOModeEx = BinaryMode IO.IOMode | TextMode IO.IOMode
202 instance Read IOModeEx
203 instance Show IOModeEx
206 trace :: String -> a -> a
207 unsafePtrEq :: a -> a -> Bool
209 unsafeIOToST :: IO a -> ST s a
214 The operations <tt/fixIO/, <tt/unsafePerformIO/ and <tt/unsafeInterleaveIO/
215 described in <cite id="ImperativeFP">
218 References (aka mutable variables) and mutable arrays (but no form of
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
228 <tt/performGC/ triggers an immediate garbage collection
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.
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!
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:
254 > cache :: (a -> b) -> (a -> b)
255 > cache f = \x -> unsafePerformIO (check x)
257 > ref = unsafePerformIO (newIORef (error "cache", error "cache"))
258 > check x = readIORef ref >>= \ (x',a) ->
259 > if x `unsafePtrEq` x' then
263 > writeIORef ref (x, a) >>
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.
276 <sect> <idx/GlaExts/ <p>
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.
284 module GlaExts( module GlaExts, module IOExts, module ST, module Addr ) where
288 trace :: String -> a -> a
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
302 and a number of ``primitive operations'' (<tt/+&num/,
303 <tt/plusFloat&num/, etc.).
308 <label id="sec:Bits">
311 This library defines bitwise operations for signed and unsigned ints.
315 infixl 8 `shift`, `rotate`
321 (.&.), (.|.), xor :: a -> a -> a
323 shift :: a -> Int -> a
324 rotate :: a -> Int -> a
326 setBit :: a -> Int -> a
327 clearBit :: a -> Int -> a
328 complementBit :: a -> Int -> a
329 testBit :: a -> Int -> Bool
331 isSigned :: a -> Bool
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)
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.
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.
354 Bits are numbered from 0 with bit 0 being the least significant bit.
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.
360 <tt/rotate/ is well defined only if bitSize returns a number.
361 (Maybe we should impose a Bounded constraint on it?)
364 <tt/bit i/ is the value with the i'th bit set.
368 <label id="sec:Word">
371 This library provides unsigned integers of various sizes.
372 The types supported are as follows:
375 type | number of bits @
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
389 data W -- Unsigned Ints
404 word8ToWord32 :: Word8 -> Word32
405 word32ToWord8 :: Word32 -> Word8
406 word16ToWord32 :: Word16 -> Word32
407 word32ToWord16 :: Word32 -> Word16
409 word8ToInt :: Word8 -> Int
410 intToWord8 :: Int -> Word8
411 word16ToInt :: Word16 -> Int
412 intToWord16 :: Int -> Word16
413 word32ToInt :: Word32 -> Int
414 intToWord32 :: Int -> Word32
420 All arithmetic is performed modulo 2^n
422 One non-obvious consequequence of this is that <tt/negate/
423 should <em/not/ raise an error on negative arguments.
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.
433 ToDo: complete the set of coercion functions.
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.
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
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/
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
459 Hugs only provides <tt/Eq/, <tt/Ord/, <tt/Read/ and <tt/Show/
460 instances for <tt/Word64/ at the moment.
466 This library provides signed integers of various sizes. The types
467 supported are as follows:
470 type | number of bits @
479 For each type <it/I/ above, we provide the following instances.
482 data I -- Signed Ints
483 iToInt :: I -> Int -- not provided for Int64
484 intToi :: Int -> I -- not provided for Int64
499 int8ToInt :: Int8 -> Int
500 intToInt8 :: Int -> Int8
501 int16ToInt :: Int16 -> Int
502 intToInt16 :: Int -> Int16
503 int32ToInt :: Int32 -> Int
504 intToInt32 :: Int -> Int32
509 Hugs does not provide <tt/Int64/ at the moment.
512 ToDo: complete the set of coercion functions.
517 <label id="sec:Addr">
520 This library provides machine addresses and is primarily intended for
521 use in creating foreign function interfaces using GreenCard.
525 data Addr -- Address type
529 plusAddr :: Addr -> Int -> Addr
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
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
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 ()
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.
582 <label id="sec:NumExts">
585 The <tt/NumExts/ interface collect together various numeric
586 operations that have proven to be commonly useful
589 -- Going between Doubles and Floats:
590 doubleToFloat :: Double -> Float
591 floatToDouble :: Float -> Double
593 showHex :: Integral a => a -> ShowS
594 showOct :: Integral a => a -> ShowS
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.
605 No loss of precision occurs in the other direction with
606 <tt/floatToDouble/, the floating value remains unchanged.
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.
614 <label id="sec:Foreign">
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/:
623 data ForeignObj -- abstract, instance of: Eq
625 makeForeignObj :: Addr{-object-} -> Addr{-finaliser-} -> IO ForeignObj
626 writeForeignObj :: ForeignObj -> Addr{-new value-} -> IO ()
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 ()
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
643 void finaliseFO(void* obj);
646 The finaliser is passed the reference to the external object (i.e.,
647 the first argument to <tt/makeForeignObj/.)
650 The <tt/writeForeignObj/ lets you overwrite the encapsulated foreign
651 reference with another.
654 Stable pointers allow you to hand out references to Haskell heap
655 objects to the outside world. <bf/ToDo:/ <em/say more./
658 In addition to the above, the following operations for indexing via
659 a <tt/ForeignObj/ are also, mirrored on the same operations provided
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
673 indexInt8OffForeignObj :: ForeignObj -> Int -> Int8
674 indexInt16OffForeignObj :: ForeignObj -> Int -> Int16
675 indexInt32OffForeignObj :: ForeignObj -> Int -> Int32
676 indexInt64OffForeignObj :: ForeignObj -> Int -> Int64
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
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 ()
708 <sect> <idx/Concurrent/
709 <label id="sec:Concurrent">
712 This library provides the Concurrent Haskell extensions
713 <cite id="concurrentHaskell:popl96">.
715 We are grateful to the Glasgow Haskell Project for allowing us to
716 redistribute their implementation of this module.
719 module Concurrent where
721 data ThreadId -- thread identifiers
723 instance Ord ThreadId
725 forkIO :: IO () -> IO ThreadId
726 killThread :: ThreadId -> IO ()
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
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 ()
746 data CVar a -- one element channels
747 newCVar :: IO (CVar a)
748 putCVar :: CVar a -> a -> IO ()
749 getCVar :: CVar a -> IO a
751 data QSem -- General/quantity semaphores
752 newQSem :: Int -> IO QSem
753 waitQSem :: QSem -> IO ()
754 signalQSem :: QSem -> IO ()
756 data QSemN -- General/quantity semaphores
757 newQSemN :: Int -> IO QSemN
758 waitQSemN :: QSemN -> Int -> IO ()
759 signalQSemN :: QSemN -> Int -> IO ()
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 ()
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.
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:
782 main = forkIO (write 'a') >> write 'b'
783 where write c = putChar c >> write c
786 will print either <tt/aaaaaaaaaaaaaa.../ or <tt/bbbbbbbbbbbb.../,
787 instead of some random interleaving of <tt/a/s and <tt/b/s.
789 In practice, cooperative multitasking is sufficient for writing
790 simple graphical user interfaces.
793 Hugs does not provide the functions <tt/mergeIO/ or <tt/nmergeIO/ since these
794 require preemptive multitasking.
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.
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.
809 <label id="sec:Dynamic">
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.
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.
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.
830 The following operations are provided over the <tt/Dynamic/ type:
833 data Dynamic -- abstract, instance of: Show --
835 toDyn :: Typeable a => a -> Dynamic
836 fromDyn :: Typeable a => Dynamic -> a -> a
837 fromDynamic :: Typeable a => Dynamic -> Maybe a
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
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
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
858 <sect1> The <tt/Dynamic/ type
859 <nidx/The Dynamic type/
860 <label id="sec:Dynamic:TypeRep">
863 Haskell types are represented as terms using the <tt/TypeRep/
867 data TypeRep -- abstract, instance of: Eq, Show
868 data TyCon -- abstract, instance of: Eq, Show
870 mkTyCon :: String -> TyCon
871 mkAppTy :: TyCon -> [TypeRep] -> TypeRep
872 mkFunTy :: TypeRep -> TypeRep -> TypeRep
873 applyTy :: TypeRep -> TypeRep -> Maybe TypeRep
877 <item> <tt/mkAppTy/ applies a type constructor to a sequence of types,
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,
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.
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:
897 mkTyCon :: String -> TyCon
900 An implementation of the <tt/Dynamic/ interface guarantees the
904 mkTyCon "a" == mkTyCon "a"
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/
913 [<bf/Q:/ <em>Would this constraint be
914 unworkable in practice?</em>]
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
923 <sect1> <idx/Representing types/
924 <label id="sec:Dynamic:Typeable">
927 To ease the construction of <tt/Dynamic/ values, we
928 introduce the following type class to help working with <tt/TypeRep/s:
931 class Typeable a where
932 typeOf :: a -> TypeRep
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:
946 Int, Char, Bool, Float, Double, Integer, (IO a),
947 [a], (Either a b), (Maybe a), (a->b),
948 (), (,), (,,), (,,,), (,,,,),
949 Ordering, Complex, Array, Handle
951 Addr, Word8, Word16, Word32, Word64,
952 Int8,Int16,Int32,Int64,
953 ForeignObj, MVar, (ST s a), (StablePtr a)
955 Word, ByteArray, MutableByteArray
960 <sect1> <idx/Utility functions/
961 <label id="sec:Dynamic:util">
964 Operations for applying a dynamic function type to a
965 dynamically typed argument are commonly useful, and
969 dynApply :: Dynamic -> Dynamic -> Dynamic -- unsafe.
970 dynApplyMb :: Dynamic -> Dynamic -> Maybe Dynamic
975 <label id="sec:GetOpt">
978 The <tt/GetOpt/ library contains Sven Panne's Haskell implementation
979 of <tt/getopt/, providing features nigh-on identical to GNU <tt/getopt/:
984 -- representing a single option:
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
993 = NoArg a -- no argument expected
994 | ReqArg (String -> a) String -- option requires argument
995 | OptArg (Maybe String -> a) String -- optional argument
997 usageInfo :: String -- header
998 -> [OptDescr a] -- options recognised
999 -> String -- nicely formatted decription of options
1001 getOpt :: ArgOrder a -- non-option handling
1002 -> [OptDescr a] -- options recognised
1003 -> [String] -- the command-line
1005 , [String] -- non-options
1006 ,[String] -- error messages
1012 | ReturnInOrder (String -> a)
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.
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
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.
1033 To hopefully illuminate the role of the different <tt/GetOpt/ data
1034 structures, here's the command-line options for a (very simple)
1041 import Maybe ( fromMaybe )
1045 | Input String | Output String | LibDir String
1048 options :: [OptDescr Flag]
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"
1057 inp,outp :: Maybe String -> Flag
1058 outp = Output . fromMaybe "stdout"
1059 inp = Input . fromMaybe "stdout"
1061 compilerOpts :: [String] -> IO ([Flag], [String])
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..."
1071 <label id="sec:Pretty">
1074 This library contains Simon Peyton Jones' implementation of John
1075 Hughes's pretty printer combinators.
1082 data Doc -- the Document datatype
1084 -- The primitive Doc values
1086 text :: String -> 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
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]
1115 -- Displaying Doc values
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
1124 data Mode = PageMode -- Normal
1125 | ZigZagMode -- With zig-zag cuts
1126 | LeftMode -- No indentation, infinitely long lines
1127 | OneLineMode -- All on one line
1130 <biblio files="refs" style="abbrv">