[project @ 1996-01-08 20:28:12 by partain]
[ghc-hetmet.git] / ghc / docs / users_guide / libraries.lit
1 %************************************************************************
2 %*                                                                      *
3 \section[syslibs]{System libraries}
4 \index{system libraries}
5 \index{libraries, system}
6 %*                                                                      *
7 %************************************************************************
8
9 We intend to provide more and more ready-to-use Haskell code, so that
10 every program doesn't have to invent everything from scratch.
11
12 At the moment, we supply a part of the HBC library, as well as the
13 beginnings of one of our own (``GHC library'').
14
15 If you provide a \tr{-syslib <name>}\index{-syslib <name> option} option,
16 then the interfaces for that library will come into scope (and may be
17 \tr{import}ed), and the code will be added in at link time.
18
19 %************************************************************************
20 %*                                                                      *
21 \subsection[GHC-library]{The GHC system library}
22 \index{library, GHC}
23 \index{GHC library}
24 %*                                                                      *
25 %************************************************************************
26
27 We have started to put together a ``GHC system library.''
28
29 At the moment, the library is made of generally-useful bits of the
30 compiler itself.
31
32 To use this library, just give a \tr{-syslib ghc}\index{-syslib ghc option}
33 option to GHC, both for compiling and linking.
34
35 %************************************************************************
36 %*                                                                      *
37 \subsubsection[Bag]{The @Bag@ type}
38 \index{Bag module (GHC syslib)}
39 %*                                                                      *
40 %************************************************************************
41
42 A {\em bag} is an unordered collection of elements which may contain
43 duplicates.  To use, \tr{import Bag}.
44
45 \begin{verbatim}
46 emptyBag        :: Bag elt
47 unitBag         :: elt -> Bag elt
48
49 unionBags       :: Bag elt   -> Bag elt -> Bag elt
50 unionManyBags   :: [Bag elt] -> Bag elt
51 snocBag         :: Bag elt   -> elt     -> Bag elt
52
53 elemBag         :: Eq elt => elt -> Bag elt -> Bool
54 isEmptyBag      ::                  Bag elt -> Bool
55 filterBag       :: (elt -> Bool) -> Bag elt -> Bag elt
56 partitionBag    :: (elt -> Bool) -> Bag elt-> (Bag elt, Bag elt)
57         -- returns the elements that do/don't satisfy the predicate
58
59 listToBag       :: [elt] -> Bag elt
60 bagToList       :: Bag elt -> [elt]
61 \end{verbatim}
62
63 %************************************************************************
64 %*                                                                      *
65 \subsubsection[BitSet]{The @BitSet@ type}
66 \index{BitSet module (GHC syslib)}
67 %*                                                                      *
68 %************************************************************************
69
70 Bit sets are a fast implementation of sets of integers ranging from 0
71 to one less than the number of bits in a machine word (typically 31).
72 If any element exceeds the maximum value for a particular machine
73 architecture, the results of these operations are undefined.  You have
74 been warned.  [``If you put any safety checks in this code, I will have
75 to kill you.'' --JSM]
76
77 \begin{verbatim}
78 mkBS        :: [Int]  -> BitSet
79 listBS      :: BitSet -> [Int]
80 emptyBS     :: BitSet 
81 singletonBS :: Int    -> BitSet
82
83 unionBS     :: BitSet -> BitSet -> BitSet
84 minusBS     :: BitSet -> BitSet -> BitSet
85 elementBS   :: Int    -> BitSet -> Bool
86 intersectBS :: BitSet -> BitSet -> BitSet
87
88 isEmptyBS   :: BitSet -> Bool
89 \end{verbatim}
90
91 %************************************************************************
92 %*                                                                      *
93 \subsubsection[FiniteMap]{The @FiniteMap@ type}
94 \index{FiniteMap module (GHC syslib)}
95 %*                                                                      *
96 %************************************************************************
97
98 What functional programmers call a {\em finite map}, everyone else
99 calls a {\em lookup table}.
100
101 Out code is derived from that in this paper:
102 \begin{display}
103 S Adams
104 "Efficient sets: a balancing act"
105 Journal of functional programming 3(4) Oct 1993, pages 553-562
106 \end{display}
107 Guess what?  The implementation uses balanced trees.
108
109 \begin{verbatim}
110 --      BUILDING
111 emptyFM         :: FiniteMap key elt
112 singletonFM     :: key -> elt -> FiniteMap key elt
113 listToFM        :: Ord key => [(key,elt)] -> FiniteMap key elt
114                         -- In the case of duplicates, the last is taken
115
116 --      ADDING AND DELETING
117                    -- Throws away any previous binding
118                    -- In the list case, the items are added starting with the
119                    -- first one in the list
120 addToFM         :: Ord key => FiniteMap key elt -> key -> elt  -> FiniteMap key elt
121 addListToFM     :: Ord key => FiniteMap key elt -> [(key,elt)] -> FiniteMap key elt
122
123                    -- Combines with previous binding
124 addToFM_C       :: Ord key => (elt -> elt -> elt)
125                            -> FiniteMap key elt -> key -> elt  
126                            -> FiniteMap key elt
127 addListToFM_C   :: Ord key => (elt -> elt -> elt)
128                            -> FiniteMap key elt -> [(key,elt)] 
129                            -> FiniteMap key elt
130
131                    -- Deletion doesn't complain if you try to delete something
132                    -- which isn't there
133 delFromFM       :: Ord key => FiniteMap key elt -> key   -> FiniteMap key elt
134 delListFromFM   :: Ord key => FiniteMap key elt -> [key] -> FiniteMap key elt
135
136 --      COMBINING
137                    -- Bindings in right argument shadow those in the left
138 plusFM          :: Ord key => FiniteMap key elt -> FiniteMap key elt
139                            -> FiniteMap key elt
140
141                    -- Combines bindings for the same thing with the given function
142 plusFM_C        :: Ord key => (elt -> elt -> elt) 
143                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
144
145 minusFM         :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
146                    -- (minusFM a1 a2) deletes from a1 any bindings which are bound in a2
147
148 intersectFM     :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt 
149 intersectFM_C   :: Ord key => (elt -> elt -> elt)
150                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt 
151
152 --      MAPPING, FOLDING, FILTERING
153 foldFM          :: (key -> elt -> a -> a) -> a -> FiniteMap key elt -> a
154 mapFM           :: (key -> elt1 -> elt2) -> FiniteMap key elt1 -> FiniteMap key elt2
155 filterFM        :: Ord key => (key -> elt -> Bool) 
156                            -> FiniteMap key elt -> FiniteMap key elt
157
158 --      INTERROGATING
159 sizeFM          :: FiniteMap key elt -> Int
160 isEmptyFM       :: FiniteMap key elt -> Bool
161
162 elemFM          :: Ord key => key -> FiniteMap key elt -> Bool
163 lookupFM        :: Ord key => FiniteMap key elt -> key -> Maybe elt
164 lookupWithDefaultFM
165                 :: Ord key => FiniteMap key elt -> elt -> key -> elt
166                 -- lookupWithDefaultFM supplies a "default" elt
167                 -- to return for an unmapped key
168
169 --      LISTIFYING
170 fmToList        :: FiniteMap key elt -> [(key,elt)]
171 keysFM          :: FiniteMap key elt -> [key]
172 eltsFM          :: FiniteMap key elt -> [elt]
173 \end{verbatim}
174
175 %************************************************************************
176 %*                                                                      *
177 \subsubsection[ListSetOps]{The @ListSetOps@ type}
178 \index{ListSetOps module (GHC syslib)}
179 %*                                                                      *
180 %************************************************************************
181
182 Just a few set-sounding operations on lists.  If you want sets, use
183 the \tr{Set} module.
184
185 \begin{verbatim}
186 unionLists          :: Eq a => [a] -> [a] -> [a]
187 intersectLists      :: Eq a => [a] -> [a] -> [a]
188 minusList           :: Eq a => [a] -> [a] -> [a]
189 disjointLists       :: Eq a => [a] -> [a] -> Bool
190 intersectingLists   :: Eq a => [a] -> [a] -> Bool
191 \end{verbatim}
192
193 %************************************************************************
194 %*                                                                      *
195 \subsubsection[Maybes]{The @Maybes@ type}
196 \index{Maybes module (GHC syslib)}
197 %*                                                                      *
198 %************************************************************************
199
200 Note: a \tr{Maybe} type is nearly inevitable in Haskell~1.3.
201 You should use this module with \tr{-fhaskell-1.3}.
202
203 Two non-abstract types:
204 \begin{verbatim}
205 data Maybe    a       = Nothing       | Just a -- Prelude; re-exported
206 data MaybeErr val err = Succeeded val | Failed err
207 \end{verbatim}
208
209 Some operations to do with \tr{Maybe} (some commentary follows):
210 \begin{verbatim}
211 maybeToBool :: Maybe a -> Bool      -- Nothing => False; Just => True
212 catMaybes   :: [Maybe a] -> [a]
213 allMaybes   :: [Maybe a] -> Maybe [a]
214 firstJust   :: [Maybe a] -> Maybe a
215 findJust    :: (a -> Maybe b) -> [a] -> Maybe b
216
217 assocMaybe  :: Eq a => [(a,b)] -> a -> Maybe b
218 mkLookupFun :: (key -> key -> Bool) -- Equality predicate
219             -> [(key,val)]          -- The assoc list
220             -> (key -> Maybe val)   -- A lookup fun to use
221
222     -- a monad thing
223 thenMaybe   :: Maybe a -> (a -> Maybe b) -> Maybe b
224 returnMaybe :: a -> Maybe a
225 failMaybe   :: Maybe a
226 mapMaybe    :: (a -> Maybe b) -> [a] -> Maybe [b]
227 \end{verbatim}
228
229 @catMaybes@ takes a list of @Maybe@s and returns a list of the
230 contents of all the @Just@s in it.
231
232 @allMaybes@ collects a list of @Justs@ into a single @Just@, returning
233 @Nothing@ if there are any @Nothings@.
234
235 @firstJust@ takes a list of @Maybes@ and returns the
236 first @Just@ if there is one, or @Nothing@ otherwise.
237
238 @assocMaybe@ looks up in an association list, returning
239 @Nothing@ if it fails.
240
241 Now, some operations to do with \tr{MaybeErr} (comments follow):
242 \begin{verbatim}
243     -- a monad thing (surprise, surprise)
244 thenMaB   :: MaybeErr a err -> (a -> MaybeErr b err) -> MaybeErr b err
245 returnMaB :: val -> MaybeErr val err
246 failMaB   :: err -> MaybeErr val err
247
248 listMaybeErrs :: [MaybeErr val err] -> MaybeErr [val] [err]
249 foldlMaybeErrs :: (acc -> input -> MaybeErr acc err)
250                -> acc
251                -> [input]
252                -> MaybeErr acc [err]
253 \end{verbatim}
254
255 @listMaybeErrs@ takes a list of @MaybeErrs@ and, if they all succeed,
256 returns a @Succeeded@ of a list of their values.  If any fail, it
257 returns a @Failed@ of the list of all the errors in the list.
258
259 @foldlMaybeErrs@ works along a list, carrying an accumulator; it
260 applies the given function to the accumulator and the next list item,
261 accumulating any errors that occur.
262
263 %************************************************************************
264 %*                                                                      *
265 \subsubsection[PackedString]{The @_PackedString@ type}
266 \index{PackedString module (GHC syslib)}
267 %*                                                                      *
268 %************************************************************************
269
270 The type \tr{_PackedString} is built-in, i.e., no
271 special action (other than a \tr{-fglasgow-exts} flag) is required to
272 use it.
273
274 The documentation here describes the {\em built-in} functions.
275
276 You may also access this code as a system library and {\em not} use
277 the \tr{-fglasgow-exts} flag.  Just do \tr{import PackedString},
278 heave in your \tr{-syslib ghc}, and drop off the leading underscores
279 which you see here.
280
281 We still may change this interface (again).
282
283 The basic type and functions which are available are:
284 \begin{verbatim}
285 data _PackedString
286
287 _packString      :: [Char] -> _PackedString
288 _packStringST    :: [Char] -> _ST s _PackedString
289 _packCString     :: _Addr  -> _PackedString
290 _packCBytes      :: Int -> _Addr -> _PackedString
291 _packCBytesST    :: Int -> _Addr -> _ST s _PackedString
292 _packBytesForC   :: [Char] -> _ByteArray Int
293 _packBytesForCST :: [Char] -> _ST s (_ByteArray Int)
294 _byteArrayToPS   :: _ByteArray Int -> _PackedString
295 _psToByteArray   :: _PackedString -> _ByteArray Int
296
297 _unpackPS        :: _PackedString -> [Char]
298 \end{verbatim}
299
300 We also provide a wad of list-manipulation-like functions:
301 \begin{verbatim}
302 _nilPS      :: _PackedString
303 _consPS     :: Char -> _PackedString -> _PackedString
304
305 _headPS     :: _PackedString -> Char
306 _tailPS     :: _PackedString -> _PackedString
307 _nullPS     :: _PackedString -> Bool
308 _appendPS   :: _PackedString -> _PackedString -> _PackedString
309 _lengthPS   :: _PackedString -> Int
310 _indexPS    :: _PackedString -> Int -> Char
311             -- 0-origin indexing into the string
312 _mapPS      :: (Char -> Char) -> _PackedString -> _PackedString {-or String?-}
313 _filterPS   :: (Char -> Bool) -> _PackedString -> _PackedString {-or String?-}
314 _foldlPS    :: (a -> Char -> a) -> a -> _PackedString -> a
315 _foldrPS    :: (Char -> a -> a) -> a -> _PackedString -> a
316 _takePS     :: Int -> _PackedString -> _PackedString
317 _dropPS     :: Int -> _PackedString -> _PackedString
318 _splitAtPS  :: Int -> _PackedString -> (_PackedString, _PackedString)
319 _takeWhilePS:: (Char -> Bool) -> _PackedString -> _PackedString
320 _dropWhilePS:: (Char -> Bool) -> _PackedString -> _PackedString
321 _spanPS     :: (Char -> Bool) -> _PackedString -> (_PackedString, _PackedString)
322 _breakPS    :: (Char -> Bool) -> _PackedString -> (_PackedString, _PackedString)
323 _linesPS    :: _PackedString -> [_PackedString]
324 _wordsPS    :: _PackedString -> [_PackedString]
325 _reversePS  :: _PackedString -> _PackedString
326 _concatPS   :: [_PackedString] -> _PackedString
327
328 _substrPS   :: _PackedString -> Int -> Int -> _PackedString
329             -- pluck out a piece of a _PS
330             -- start and end chars you want; both 0-origin-specified
331 \end{verbatim}
332
333 %************************************************************************
334 %*                                                                      *
335 \subsubsection[Pretty]{The @Pretty@ type}
336 \index{Pretty module (GHC syslib)}
337 %*                                                                      *
338 %************************************************************************
339
340 This is the pretty-printer that we use in GHC.
341
342 \begin{verbatim}
343 type Pretty
344
345 ppShow          :: Int{-width-} -> Pretty -> [Char]
346
347 pp'SP           :: Pretty -- "comma space"
348 ppComma         :: Pretty -- ,
349 ppEquals        :: Pretty -- =
350 ppLbrack        :: Pretty -- [
351 ppLparen        :: Pretty -- (
352 ppNil           :: Pretty -- nothing
353 ppRparen        :: Pretty -- )
354 ppRbrack        :: Pretty -- ]
355 ppSP            :: Pretty -- space
356 ppSemi          :: Pretty -- ;
357
358 ppChar          :: Char -> Pretty
359 ppDouble        :: Double -> Pretty
360 ppFloat         :: Float -> Pretty
361 ppInt           :: Int -> Pretty
362 ppInteger       :: Integer -> Pretty
363 ppRational      :: Rational -> Pretty
364 ppStr           :: [Char] -> Pretty
365
366 ppAbove         :: Pretty -> Pretty -> Pretty
367 ppAboves        :: [Pretty] -> Pretty
368 ppBeside        :: Pretty -> Pretty -> Pretty
369 ppBesides       :: [Pretty] -> Pretty
370 ppCat           :: [Pretty] -> Pretty
371 ppHang          :: Pretty -> Int -> Pretty -> Pretty
372 ppInterleave    :: Pretty -> [Pretty] -> Pretty -- spacing between
373 ppIntersperse   :: Pretty -> [Pretty] -> Pretty -- no spacing between
374 ppNest          :: Int -> Pretty -> Pretty
375 ppSep           :: [Pretty] -> Pretty
376 \end{verbatim}
377
378 %************************************************************************
379 %*                                                                      *
380 \subsubsection[Set]{The @Set@ type}
381 \index{Set module (GHC syslib)}
382 %*                                                                      *
383 %************************************************************************
384
385 Our implementation of {\em sets} (key property: no duplicates) is just
386 a variant of the \tr{FiniteMap} module.
387
388 \begin{verbatim}
389 mkSet           :: Ord a => [a]  -> Set a
390 setToList       :: Set a -> [a]
391 emptySet        :: Set a
392 singletonSet    :: a -> Set a
393
394 union           :: Ord a => Set a -> Set a -> Set a
395 unionManySets   :: Ord a => [Set a] -> Set a
396 intersect       :: Ord a => Set a -> Set a -> Set a
397 minusSet        :: Ord a => Set a -> Set a -> Set a
398 mapSet          :: Ord a => (b -> a) -> Set b -> Set a
399
400 elementOf       :: Ord a => a -> Set a -> Bool
401 isEmptySet      :: Set a -> Bool
402 \end{verbatim}
403
404 %************************************************************************
405 %*                                                                      *
406 \subsubsection[Util]{The @Util@ type}
407 \index{Util module (GHC syslib)}
408 %*                                                                      *
409 %************************************************************************
410
411 Stuff that has been useful to use in writing the compiler.  Don't be
412 too surprised if this stuff moves/gets-renamed/etc.
413
414 \begin{verbatim}
415 -- general list processing
416 forall          :: (a -> Bool) -> [a] -> Bool
417 exists          :: (a -> Bool) -> [a] -> Bool
418 zipEqual        :: [a] -> [b] -> [(a,b)]
419 nOfThem         :: Int -> a -> [a]
420 lengthExceeds   :: [a] -> Int -> Bool
421 isSingleton     :: [a] -> Bool
422
423 -- association lists
424 assoc       :: Eq a => String -> [(a, b)] -> a -> b
425
426 -- duplicate handling
427 hasNoDups    :: Eq a => [a] -> Bool
428 equivClasses :: (a -> a -> _CMP_TAG) -> [a] -> [[a]]
429 runs         :: (a -> a -> Bool)     -> [a] -> [[a]]
430 removeDups   :: (a -> a -> _CMP_TAG) -> [a] -> ([a], [[a]])
431
432 -- sorting (don't complain of no choice...)
433 quicksort          :: (a -> a -> Bool)     -> [a] -> [a]
434 sortLt             :: (a -> a -> Bool)     -> [a] -> [a]
435 stableSortLt       :: (a -> a -> Bool)     -> [a] -> [a]
436 mergesort          :: (a -> a -> _CMP_TAG) -> [a] -> [a]
437 mergeSort          :: Ord a => [a] -> [a]
438 naturalMergeSort   :: Ord a => [a] -> [a]
439 mergeSortLe        :: Ord a => [a] -> [a]
440 naturalMergeSortLe :: Ord a => [a] -> [a]
441
442 -- transitive closures
443 transitiveClosure :: (a -> [a])         -- Successor function
444                   -> (a -> a -> Bool)   -- Equality predicate
445                   -> [a] 
446                   -> [a]                -- The transitive closure
447
448 -- accumulating (Left, Right, Bi-directional)
449 mapAccumL :: (acc -> x -> (acc, y))
450                         -- Function of elt of input list and
451                         -- accumulator, returning new accumulator and
452                         -- elt of result list
453           -> acc        -- Initial accumulator
454           -> [x]        -- Input list
455           -> (acc, [y]) -- Final accumulator and result list
456
457 mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
458
459 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
460           -> accl -> accr -> [x]
461           -> (accl, accr, [y])
462
463 -- comparisons
464 cmpString :: String -> String -> _CMP_TAG
465
466 -- this type is built-in
467 data _CMP_TAG = _LT | _EQ | _GT
468
469 -- pairs
470 applyToPair :: ((a -> c), (b -> d)) -> (a, b) -> (c, d)
471 applyToFst  :: (a -> c) -> (a, b) -> (c, b)
472 applyToSnd  :: (b -> d) -> (a, b) -> (a, d)
473 foldPair    :: (a->a->a, b->b->b) -> (a, b) -> [(a, b)] -> (a, b)
474 unzipWith   :: (a -> b -> c) -> [(a, b)] -> [c]
475 \end{verbatim}
476
477 %************************************************************************
478 %*                                                                      *
479 \subsection[C-interfaces]{Interfaces to C libraries}
480 \index{C library interfaces}
481 \index{interfaces, C library}
482 %*                                                                      *
483 %************************************************************************
484
485 The GHC system library (\tr{-syslib ghc}) also provides interfaces to
486 several useful C libraries, mostly from the GNU project.
487
488 %************************************************************************
489 %*                                                                      *
490 \subsubsection[Readline]{The @Readline@ interface}
491 \index{Readline library (GHC syslib)}
492 \index{command-line editing library}
493 %*                                                                      *
494 %************************************************************************
495
496 (Darren Moffat supplied the \tr{Readline} interface.)
497
498 The \tr{Readline} module is a straightforward interface to the GNU
499 Readline library.  As such, you will need to look at the GNU
500 documentation (and have a \tr{libreadline.a} file around somewhere...)
501
502 You'll need to link any Readlining program with \tr{-lreadline -ltermcap},
503 besides the usual \tr{-syslib ghc} (and \tr{-fhaskell-1.3}).
504
505 The main function you'll use is:
506 \begin{verbatim}
507 readline :: String{-the prompt-} -> IO String
508 \end{verbatim}
509
510 If you want to mess around with Full Readline G(l)ory, we also
511 provide:
512 \begin{verbatim}
513 rlInitialize, addHistory,
514
515 rlBindKey, rlAddDefun, RlCallbackFunction(..),
516
517 rlGetLineBuffer, rlSetLineBuffer, rlGetPoint, rlSetPoint, rlGetEnd,
518 rlSetEnd, rlGetMark, rlSetMark, rlSetDone, rlPendingInput,
519
520 rlPrompt, rlTerminalName, rlSetReadlineName, rlGetReadlineName
521 \end{verbatim}
522 (All those names are just Haskellised versions of what you
523 will see in the GNU readline documentation.)
524
525 %************************************************************************
526 %*                                                                      *
527 \subsubsection[Regexp]{The @Regexp@ and @MatchPS@ interfaces}
528 \index{Regex library (GHC syslib)}
529 \index{MatchPS library (GHC syslib)}
530 \index{regular-expressions library}
531 %*                                                                      *
532 %************************************************************************
533
534 (Sigbjorn Finne supplied the regular-expressions interface.)
535
536 The \tr{Regex} library provides quite direct interface to the GNU
537 regular-expression library, for doing manipulation on
538 \tr{_PackedString}s.  You probably need to see the GNU documentation
539 if you are operating at this level.
540
541 The datatypes and functions that \tr{Regex} provides are:
542 \begin{verbatim}
543 data PatBuffer  # just a bunch of bytes (mutable)
544
545 data REmatch
546  = REmatch (Array Int GroupBounds)  -- for $1, ... $n
547            GroupBounds              -- for $` (everything before match)
548            GroupBounds              -- for $& (entire matched string)
549            GroupBounds              -- for $' (everything after)
550            GroupBounds              -- for $+ (matched by last bracket)
551
552 -- GroupBounds hold the interval where a group
553 -- matched inside a string, e.g.
554 --
555 -- matching "reg(exp)" "a regexp" returns the pair (5,7) for the
556 -- (exp) group. (_PackedString indices start from 0)
557
558 type GroupBounds = (Int, Int)
559
560 re_compile_pattern
561         :: _PackedString        -- pattern to compile
562         -> Bool                 -- True <=> assume single-line mode
563         -> Bool                 -- True <=> case-insensitive
564         -> PrimIO PatBuffer
565
566 re_match :: PatBuffer           -- compiled regexp
567          -> _PackedString       -- string to match
568          -> Int                 -- start position
569          -> Bool                -- True <=> record results in registers
570          -> PrimIO (Maybe REmatch)
571
572 -- Matching on 2 strings is useful when you're dealing with multiple
573 -- buffers, which is something that could prove useful for
574 -- PackedStrings, as we don't want to stuff the contents of a file
575 -- into one massive heap chunk, but load (smaller chunks) on demand.
576
577 re_match2 :: PatBuffer          -- 2-string version
578           -> _PackedString
579           -> _PackedString
580           -> Int
581           -> Int
582           -> Bool
583           -> PrimIO (Maybe REmatch)
584
585 re_search :: PatBuffer          -- compiled regexp
586           -> _PackedString      -- string to search
587           -> Int                -- start index
588           -> Int                -- stop index
589           -> Bool               -- True <=> record results in registers
590           -> PrimIO (Maybe REmatch)
591
592 re_search2 :: PatBuffer         -- Double buffer search
593            -> _PackedString
594            -> _PackedString
595            -> Int               -- start index
596            -> Int               -- range (?)
597            -> Int               -- stop index
598            -> Bool              -- True <=> results in registers
599            -> PrimIO (Maybe REmatch)
600 \end{verbatim}
601
602 The \tr{MatchPS} module provides Perl-like ``higher-level'' facilities
603 to operate on \tr{_PackedStrings}.  The regular expressions in
604 question are in Perl syntax.  The ``flags'' on various functions can
605 include: \tr{i} for case-insensitive, \tr{s} for single-line mode, and
606 \tr{g} for global.  (It's probably worth your time to peruse the
607 source code...)
608
609 \begin{verbatim}
610 matchPS :: _PackedString    -- regexp
611         -> _PackedString    -- string to match
612         -> [Char]           -- flags
613         -> Maybe REmatch    -- info about what matched and where
614
615 searchPS :: _PackedString   -- regexp
616          -> _PackedString   -- string to match
617          -> [Char]          -- flags
618          -> Maybe REmatch
619
620 -- Perl-like match-and-substitute:
621 substPS :: _PackedString    -- regexp
622         -> _PackedString    -- replacement
623         -> [Char]           -- flags
624         -> _PackedString    -- string
625         -> _PackedString
626
627 -- same as substPS, but no prefix and suffix:
628 replacePS :: _PackedString  -- regexp
629           -> _PackedString  -- replacement
630           -> [Char]         -- flags
631           -> _PackedString  -- string
632           -> _PackedString
633
634 match2PS :: _PackedString   -- regexp
635          -> _PackedString   -- string1 to match
636          -> _PackedString   -- string2 to match
637          -> [Char]          -- flags
638          -> Maybe REmatch
639
640 search2PS :: _PackedString  -- regexp
641           -> _PackedString  -- string to match
642           -> _PackedString  -- string to match
643           -> [Char]         -- flags
644           -> Maybe REmatch
645
646 -- functions to pull the matched pieces out of an REmatch:
647
648 getMatchesNo    :: REmatch -> Int
649 getMatchedGroup :: REmatch -> Int -> _PackedString -> _PackedString
650 getWholeMatch   :: REmatch -> _PackedString -> _PackedString
651 getLastMatch    :: REmatch -> _PackedString -> _PackedString
652 getAfterMatch   :: REmatch -> _PackedString -> _PackedString
653
654 -- (reverse) brute-force string matching;
655 -- Perl equivalent is index/rindex:
656 findPS, rfindPS :: _PackedString -> _PackedString -> Maybe Int
657
658 -- Equivalent to Perl "chop" (off the last character, if any):
659 chopPS :: _PackedString -> _PackedString
660
661 -- matchPrefixPS: tries to match as much as possible of strA starting
662 -- from the beginning of strB (handy when matching fancy literals in
663 -- parsers):
664 matchPrefixPS :: _PackedString -> _PackedString -> Int
665 \end{verbatim}
666
667 %************************************************************************
668 %*                                                                      *
669 \subsubsection[Socket]{Network-interface toolkit---@Socket@ and @SocketPrim@}
670 \index{SocketPrim interface (GHC syslib)}
671 \index{Socket interface (GHC syslib)}
672 \index{network-interface library}
673 \index{sockets library}
674 \index{BSD sockets library}
675 %*                                                                      *
676 %************************************************************************
677
678 (Darren Moffat supplied the network-interface toolkit.)
679
680 Your best bet for documentation is to look at the code---really!--- 
681 normally in \tr{ghc/lib/ghc/{BSD,Socket,SocketPrim}.lhs}.
682
683 The \tr{BSD} module provides functions to get at system-database info;
684 pretty straightforward if you're into this sort of thing:
685 \begin{verbatim}
686 getHostName         :: IO String
687
688 getServiceByName    :: ServiceName -> IO ServiceEntry
689 getServicePortNumber:: ServiceName -> IO PortNumber
690 getServiceEntry     :: IO ServiceEntry
691 setServiceEntry     :: Bool -> IO ()
692 endServiceEntry     :: IO ()
693
694 getProtocolByName   :: ProtocolName -> IO ProtocolEntry
695 getProtocolByNumber :: ProtocolNumber -> IO ProtcolEntry
696 getProtocolNumber   :: ProtocolName -> ProtocolNumber
697 getProtocolEntry    :: IO ProtocolEntry
698 setProtocolEntry    :: Bool -> IO ()
699 endProtocolEntry    :: IO ()
700
701 getHostByName       :: HostName -> IO HostEntry
702 getHostByAddr       :: Family -> HostAddress -> IO HostEntry
703 getHostEntry        :: IO HostEntry
704 setHostEntry        :: Bool -> IO ()
705 endHostEntry        :: IO ()
706 \end{verbatim}
707
708 The \tr{SocketPrim} interface provides quite direct access to the
709 socket facilities in a BSD Unix system, including all the
710 complications.  We hope you don't need to use it!  See the source if
711 needed...
712
713 The \tr{Socket} interface is a ``higher-level'' interface to sockets,
714 and it is what we recommend.  Please tell us if the facilities it
715 offers are inadequate to your task!
716
717 The interface is relatively modest:
718 \begin{verbatim}
719 connectTo       :: Hostname -> PortID -> IO Handle
720 listenOn        :: PortID -> IO Socket
721
722 accept          :: Socket -> IO (Handle, HostName)
723 sendTo          :: Hostname -> PortID -> String -> IO ()
724
725 recvFrom        :: Hostname -> PortID -> IO String
726 socketPort      :: Socket -> IO PortID
727
728 data PortID     -- PortID is a non-abstract type
729   = Service String      -- Service Name eg "ftp"
730   | PortNumber Int      -- User defined Port Number
731   | UnixSocket String   -- Unix family socket in file system
732
733 type Hostname = String
734 \end{verbatim}
735
736 Various examples of networking Haskell code are provided in
737 \tr{ghc/misc/examples/}, notably the \tr{net???/Main.hs} programs.
738
739 %************************************************************************
740 %*                                                                      *
741 \subsection[HBC-library]{The HBC system library}
742 \index{HBC system library}
743 \index{system library, HBC}
744 %*                                                                      *
745 %************************************************************************
746
747 This documentation is stolen directly from the HBC distribution.  The
748 modules that GHC does not support (because they require HBC-specific
749 extensions) are omitted.
750
751 \begin{description}
752 \item[\tr{Either}:]
753 \index{Either module (HBC library)}%
754 A binary sum data type:
755 \begin{verbatim}
756 data Either a b = Left a | Right b
757 \end{verbatim}
758 The constructor \tr{Left} is typically used for errors; it can be
759 renamed to \tr{Wrong} on import.
760
761 \item[\tr{Maybe}:]
762 \index{Maybe module (HBC library)}%
763 A type for failure or success:
764 \begin{verbatim}
765 data Maybe a = Nothing | Just a
766 thenM :: Maybe a -> (a -> Maybe b) -> Maybe b
767     -- apply a function that may fail
768 \end{verbatim}
769
770 \item[\tr{Option}:]
771 \index{Option module (HBC library)}%
772 An alias for \tr{Maybe}:
773 \begin{verbatim}
774 data Option a = None | Some a
775 thenO :: Option a -> (a -> Option b) -> Option b
776 \end{verbatim}
777
778 \item[\tr{ListUtil}:]
779 \index{ListUtil module (HBC library)}%
780 Various useful functions involving lists that are missing from the
781 \tr{Prelude}:
782 \begin{verbatim}
783 assoc :: (Eq c) => (a -> b) -> b -> [(c, a)] -> c -> b
784         -- assoc f d l k looks for k in the association list l, if it
785         -- is found f is applied to the value, otherwise d is returned.
786 concatMap :: (a -> [b]) -> [a] -> [b]
787         -- flattening map (LML's concmap)
788 unfoldr :: (a -> (b, a)) -> (a -> Bool) -> a -> [b]
789         -- unfoldr f p x repeatedly applies f to x until (p x) holds.
790         -- (f x) should give a list element and a new x.
791 mapAccuml :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
792         -- mapAccuml f s l maps f over l, but also threads the state s
793         -- through (LML's mapstate).
794 union :: (Eq a) => [a] -> [a] -> [a]
795         -- union of two lists
796 intersection :: (Eq a) => [a] -> [a] -> [a]
797         -- intersection of two lists
798 chopList :: ([a] -> (b, [a])) -> [a] -> [b]
799         -- LMLs choplist
800 assocDef :: (Eq a) => [(a, b)] -> b -> a -> b
801         -- LMLs assocdef
802 lookup :: (Eq a) => [(a, b)] -> a -> Option b
803         -- lookup l k looks for the key k in the association list l
804         -- and returns an optional value
805 tails :: [a] -> [[a]]
806         -- return all the tails of a list
807 rept :: (Integral a) => a -> b -> [b]
808         -- repeat a value a number of times
809 groupEq :: (a->a->Bool) -> [a] -> [[a]]
810         -- group list elements according to an equality predicate
811 group :: (Eq a) => [a] -> [[a]]
812         -- group according to} ==
813 readListLazily :: (Text a) => String -> [a]
814         -- read a list in a lazy fashion
815 \end{verbatim}
816
817 \item[\tr{Pretty}:]
818 \index{Pretty module (HBC library)}%
819 John Hughes's pretty printing library.  
820 \begin{verbatim}
821 type Context = (Bool, Int, Int, Int)
822 type IText = Context -> [String]
823 text :: String -> IText                 -- just text
824 (~.) :: IText -> IText -> IText         -- horizontal composition
825 (^.) :: IText -> IText -> IText         -- vertical composition
826 separate :: [IText] -> IText            -- separate by spaces
827 nest :: Int -> IText -> IText           -- indent
828 pretty :: Int -> Int -> IText -> String -- format it
829 \end{verbatim}
830
831 \item[\tr{QSort}:]
832 \index{QSort module (HBC library)}%
833 A sort function using quicksort.
834 \begin{verbatim}
835 sortLe :: (a -> a -> Bool) -> [a] -> [a]
836         -- sort le l  sorts l with le as less than predicate
837 sort :: (Ord a) => [a] -> [a]
838         -- sort l  sorts l using the Ord class
839 \end{verbatim}
840
841 \item[\tr{Random}:]
842 \index{Random module (HBC library)}%
843 Random numbers.
844 \begin{verbatim}
845 randomInts :: Int -> Int -> [Int]
846         -- given two seeds gives a list of random Int
847 randomDoubles :: Int -> Int -> [Double]
848         -- random Double with uniform distribution in (0,1)
849 normalRandomDoubles :: Int -> Int -> [Double]
850         -- random Double with normal distribution, mean 0, variance 1
851 \end{verbatim}
852
853 \item[\tr{Trace}:]
854 Simple tracing.  (Note: This comes with GHC anyway.)
855 \begin{verbatim}
856 trace :: String -> a -> a       -- trace x y  prints x and returns y
857 \end{verbatim}
858
859 \item[\tr{Miranda}:]
860 \index{Miranda module (HBC library)}%
861 Functions found in the Miranda library.
862 (Note: Miranda is a registered trade mark of Research Software Ltd.)
863
864 \item[\tr{Word}:]
865 \index{Word module (HBC library)}
866 Bit manipulation.  (GHC doesn't implement absolutely all of this.
867 And don't count on @Word@ being 32 bits on a Alpha...)
868 \begin{verbatim}
869 class Bits a where
870     bitAnd :: a -> a -> a       -- bitwise and
871     bitOr :: a -> a -> a        -- bitwise or
872     bitXor :: a -> a -> a       -- bitwise xor
873     bitCompl :: a -> a          -- bitwise negation
874     bitRsh :: a -> Int -> a     -- bitwise right shift
875     bitLsh :: a -> Int -> a     -- bitwise left shift
876     bitSwap :: a -> a           -- swap word halves
877     bit0 :: a                   -- word with least significant bit set
878     bitSize :: a -> Int         -- number of bits in a word
879
880 data Byte                       -- 8  bit quantity
881 data Short                      -- 16 bit quantity
882 data Word                       -- 32 bit quantity
883
884 instance Bits Byte, Bits Short, Bits Word
885 instance Eq Byte, Eq Short, Eq Word
886 instance Ord Byte, Ord Short, Ord Word
887 instance Text Byte, Text Short, Text Word
888 instance Num Byte, Num Short, Num Word
889 wordToShorts :: Word -> [Short]   -- convert a Word to two Short
890 wordToBytes :: Word -> [Byte]     -- convert a Word to four Byte
891 bytesToString :: [Byte] -> String -- convert a list of Byte to a String (bit by bit)
892 wordToInt :: Word -> Int          -- convert a Word to Int
893 shortToInt :: Short -> Int        -- convert a Short to Int
894 byteToInt :: Byte -> Int          -- convert a Byte to Int
895 \end{verbatim}
896
897 \item[\tr{Time}:]
898 \index{Time module (HBC library)}%
899 Manipulate time values (a Double with seconds since 1970).
900 \begin{verbatim}
901 --               year mon  day  hour min  sec  dec-sec  weekday
902 data Time = Time Int  Int  Int  Int  Int  Int  Double  Int
903 dblToTime :: Double -> Time     -- convert a Double to a Time
904 timeToDbl :: Time -> Double     -- convert a Time to a Double
905 timeToString :: Time -> String  -- convert a Time to a readable String
906 \end{verbatim}
907
908 \item[\tr{Hash}:]
909 \index{Hash module (HBC library)}%
910 Hashing functions.
911 \begin{verbatim}
912 class Hashable a where
913     hash :: a -> Int                            -- hash a value, return an Int
914 -- instances for all Prelude types
915 hashToMax :: (Hashable a) => Int -> a -> Int    -- hash into interval [0..x-1]
916 \end{verbatim}
917
918 \item[\tr{NameSupply}:]
919 \index{NameSupply module (HBC library)}%
920 Functions to generate unique names (Int).
921 \begin{verbatim}
922 type Name = Int
923 initialNameSupply :: NameSupply
924         -- The initial name supply (may be different every
925         -- time the program is run.
926 splitNameSupply :: NameSupply -> (NameSupply,NameSupply)
927         -- split the namesupply into two
928 getName :: NameSupply -> Name
929         -- get the name associated with a name supply
930 \end{verbatim}
931
932 \item[\tr{Parse}:]
933 \index{Parse module (HBC library)}%
934 Higher order functions to build parsers.  With a little care these
935 combinators can be used to build efficient parsers with good error
936 messages.
937 \begin{verbatim}
938 infixr 8 +.+ , ..+ , +.. 
939 infix  6 `act` , >>> , `into` , .> 
940 infixr 4 ||| , ||! , |!! 
941 data ParseResult a b 
942 type Parser a b = a -> Int -> ParseResult a b 
943 (|||) :: Parser a b -> Parser a b -> Parser a b
944         -- Alternative
945 (||!) :: Parser a b -> Parser a b -> Parser a b
946         -- Alternative, but with committed choice
947 (|!!) :: Parser a b -> Parser a b -> Parser a b
948         -- Alternative, but with committed choice
949 (+.+) :: Parser a b -> Parser a c -> Parser a (b,c)
950         -- Sequence
951 (..+) :: Parser a b -> Parser a c -> Parser a c
952         -- Sequence, throw away first part
953 (+..) :: Parser a b -> Parser a c -> Parser a b
954         -- Sequence, throw away second part
955 act   :: Parser a b -> (b->c) -> Parser a c
956         -- Action
957 (>>>) :: Parser a (b,c) -> (b->c->d) -> Parser a d
958         -- Action on two items
959 (.>) :: Parser a b -> c -> Parse a c
960         -- Action ignoring value
961 into :: Parser a b -> (b -> Parser a c) -> Parser a c
962         -- Use a produced value in a parser.
963 succeed b :: Parser a b
964         -- Always succeeds without consuming a token
965 failP :: Parser a b
966         -- Always fails.
967 many :: Parser a b -> Parser a [b]
968         -- Kleene star
969 many1 :: Parser a b -> Parser a [b]
970         -- Kleene plus
971 count :: Parser a b -> Int -> Parser a [b]
972         -- Parse an exact number of items
973 sepBy1 :: Parser a b -> Parser a c -> Parser a [b]
974         -- Non-empty sequence of items separated by something
975 sepBy :: Parser a b -> Parser a c -> Parser a [b]
976         -- Sequence of items separated by something
977 lit :: (Eq a, Text a) => a -> Parser [a] a
978         -- Recognise a literal token from a list of tokens
979 litp :: String -> (a->Bool) -> Parser [a] a
980         -- Recognise a token with a predicate.
981         -- The string is a description for error messages.
982 testp :: String -> (a -> Bool) -> (Parser b a) -> Parser b a
983         -- Test a semantic value. 
984 token :: (a -> Either String (b, a)) -> Parser a b
985         -- General token recogniser.
986 parse :: Parser a b -> a -> Either ([String], a) [(b, a)]
987         -- Do a parse.  Return either error (possible tokens and rest
988         -- of tokens) or all possible parses.
989 sParse :: (Text a) => (Parser [a] b) -> [a] -> Either String b
990         -- Simple parse.  Return error message or result.
991 \end{verbatim}
992
993 %%%simpleLex :: String -> [String]              -- A simple (but useful) lexical analyzer
994
995 \item[\tr{Native}:]
996 \index{Native module (HBC library)}%
997 Functions to convert the primitive types \tr{Int}, \tr{Float}, and \tr{Double} to
998 their native representation as a list of bytes (\tr{Char}).  If such a list
999 is read/written to a file it will have the same format as when, e.g.,
1000 C read/writes the same kind of data.
1001 \begin{verbatim}
1002 type Bytes = [Char] -- A byte stream is just a list of characters
1003
1004 class Native a where 
1005     showBytes     :: a -> Bytes -> Bytes
1006         -- prepend the representation of an item the a byte stream
1007     listShowBytes :: [a] -> Bytes -> Bytes
1008         -- prepend the representation of a list of items to a stream
1009         -- (may be more efficient than repeating showBytes).
1010     readBytes     :: Bytes -> Maybe (a, Bytes)
1011         -- get an item from the stream and return the rest,
1012         -- or fail if the stream is to short.
1013     listReadBytes :: Int -> Bytes -> Maybe ([a], Bytes)
1014         -- read n items from a stream.
1015
1016 instance Native Int 
1017 instance Native Float 
1018 instance Native Double 
1019 instance (Native a, Native b) => Native (a,b)
1020         -- juxtaposition of the two items
1021 instance (Native a, Native b, Native c) => Native (a, b, c)
1022         -- juxtaposition of the three items
1023 instance (Native a) => Native [a]
1024         -- an item count in an Int followed by the items
1025
1026 shortIntToBytes :: Int -> Bytes -> Bytes
1027         -- Convert an Int to what corresponds to a short in C.
1028 bytesToShortInt :: Bytes -> Maybe (Int, Bytes)
1029         -- Get a short from a byte stream and convert to an Int.
1030
1031 showB :: (Native a) => a -> Bytes       -- Simple interface to showBytes.
1032 readB :: (Native a) => Bytes -> a       -- Simple interface to readBytes.
1033 \end{verbatim}
1034
1035 \item[\tr{Number}:]
1036 \index{Number module (HBC library)}%
1037 Simple numbers that belong to all numeric classes and behave like
1038 a naive user would expect (except that printing is still ugly).
1039 (NB: GHC does not provide a magic way to use \tr{Numbers} everywhere,
1040 but you should be able to do it with normal \tr{import}ing and
1041 \tr{default}ing.)
1042 \begin{verbatim}
1043 data Number                     -- The type itself.
1044 instance ...                    -- All reasonable instances.
1045 isInteger :: Number -> Bool     -- Test if a Number is an integer.
1046 \end{verbatim}
1047 \end{description}