1 %************************************************************************
3 \section[syslibs]{System libraries}
4 \index{system libraries}
5 \index{libraries, system}
8 This section gives an overview of the interfaces provided
9 by the different {\em syslibs} that comes bundled with GHC.
11 At the moment, there four different collections of system libraries:
14 \item The GHC system library - collection of interfaces that mainly
15 have grown out of abstractions used to implement GHC itself.
16 \item Parts of the HBC libraries.
17 \item The Posix interface - a mostly complete interface to OS functionality as
18 specified by {\tt POSIX 1003.1}. Sadly, this library isn't a standard
19 Haskell library...yet.
20 \item The contrib libraries - oodles of numeric codes..
23 If you provide a \tr{-syslib <name>}\index{-syslib <name> option}
24 option on the command line, then the interfaces for that library will
25 come into scope (and may be \tr{import}ed), and the code will be added
29 %************************************************************************
31 \subsection[GHC-library]{The GHC system library}
35 %************************************************************************
37 We have started to put together a ``GHC system library.''
39 At the moment, the library is made of generally-useful bits of the
42 To use this library, just give a \tr{-syslib ghc}\index{-syslib ghc option}
43 option to GHC, both for compiling and linking.
45 %************************************************************************
47 \subsubsection[Bag]{The @Bag@ type}
48 \index{Bag module (GHC syslib)}
50 %************************************************************************
52 A {\em bag} is an unordered collection of elements which may contain
53 duplicates. To use, \tr{import Bag}.
56 data Bag elt -- abstract
59 unitBag :: elt -> Bag elt
61 consBag :: elt -> Bag elt -> Bag elt
62 snocBag :: Bag elt -> elt -> Bag elt
64 unionBags :: Bag elt -> Bag elt -> Bag elt
65 unionManyBags :: [Bag elt] -> Bag elt
67 isEmptyBag :: Bag elt -> Bool
68 elemBag :: Eq elt => elt -> Bag elt -> Bool
70 filterBag :: (elt -> Bool) -> Bag elt -> Bag elt
71 partitionBag :: (elt -> Bool) -> Bag elt-> (Bag elt, Bag elt)
72 -- returns the elements that do/don't satisfy the predicate
74 concatBag :: Bag (Bag a) -> Bag a
75 foldBag :: (r -> r -> r) -> (a -> r) -> r -> Bag a -> r
76 mapBag :: (a -> b) -> Bag a -> Bag b
78 listToBag :: [elt] -> Bag elt
79 bagToList :: Bag elt -> [elt]
82 %************************************************************************
84 \subsubsection[FiniteMap]{The @FiniteMap@ type}
85 \index{FiniteMap module (GHC syslib)}
87 %************************************************************************
89 What functional programmers call a {\em finite map}, everyone else
90 calls a {\em lookup table}.
92 Out code is derived from that in this paper:
95 "Efficient sets: a balancing act"
96 Journal of functional programming 3(4) Oct 1993, pages 553-562
98 Guess what? The implementation uses balanced trees.
101 data FiniteMap key elt -- abstract
104 emptyFM :: FiniteMap key elt
105 unitFM :: key -> elt -> FiniteMap key elt
106 listToFM :: Ord key => [(key,elt)] -> FiniteMap key elt
107 -- In the case of duplicates, the last is taken
109 -- ADDING AND DELETING
110 -- Throws away any previous binding
111 -- In the list case, the items are added starting with the
112 -- first one in the list
113 addToFM :: Ord key => FiniteMap key elt -> key -> elt -> FiniteMap key elt
114 addListToFM :: Ord key => FiniteMap key elt -> [(key,elt)] -> FiniteMap key elt
116 -- Combines with previous binding
117 -- In the combining function, the first argument is
118 -- the "old" element, while the second is the "new" one.
119 addToFM_C :: Ord key => (elt -> elt -> elt)
120 -> FiniteMap key elt -> key -> elt
122 addListToFM_C :: Ord key => (elt -> elt -> elt)
123 -> FiniteMap key elt -> [(key,elt)]
126 -- Deletion doesn't complain if you try to delete something
128 delFromFM :: Ord key => FiniteMap key elt -> key -> FiniteMap key elt
129 delListFromFM :: Ord key => FiniteMap key elt -> [key] -> FiniteMap key elt
132 -- Bindings in right argument shadow those in the left
133 plusFM :: Ord key => FiniteMap key elt -> FiniteMap key elt
136 -- Combines bindings for the same thing with the given function
137 plusFM_C :: Ord key => (elt -> elt -> elt)
138 -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
140 minusFM :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
141 -- (minusFM a1 a2) deletes from a1 any bindings which are bound in a2
143 intersectFM :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
144 intersectFM_C :: Ord key => (elt -> elt -> elt)
145 -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
147 -- MAPPING, FOLDING, FILTERING
148 foldFM :: (key -> elt -> a -> a) -> a -> FiniteMap key elt -> a
149 mapFM :: (key -> elt1 -> elt2) -> FiniteMap key elt1 -> FiniteMap key elt2
150 filterFM :: Ord key => (key -> elt -> Bool)
151 -> FiniteMap key elt -> FiniteMap key elt
154 sizeFM :: FiniteMap key elt -> Int
155 isEmptyFM :: FiniteMap key elt -> Bool
157 elemFM :: Ord key => key -> FiniteMap key elt -> Bool
158 lookupFM :: Ord key => FiniteMap key elt -> key -> Maybe elt
160 :: Ord key => FiniteMap key elt -> elt -> key -> elt
161 -- lookupWithDefaultFM supplies a "default" elt
162 -- to return for an unmapped key
165 fmToList :: FiniteMap key elt -> [(key,elt)]
166 keysFM :: FiniteMap key elt -> [key]
167 eltsFM :: FiniteMap key elt -> [elt]
170 %************************************************************************
172 \subsubsection[ListSetOps]{The @ListSetOps@ type}
173 \index{ListSetOps module (GHC syslib)}
175 %************************************************************************
177 Just a few set-sounding operations on lists. If you want sets, use
181 unionLists :: Eq a => [a] -> [a] -> [a]
182 intersectLists :: Eq a => [a] -> [a] -> [a]
183 minusList :: Eq a => [a] -> [a] -> [a]
184 disjointLists :: Eq a => [a] -> [a] -> Bool
185 intersectingLists :: Eq a => [a] -> [a] -> Bool
188 %************************************************************************
190 \subsubsection[Maybes]{The @Maybes@ type}
191 \index{Maybes module (GHC syslib)}
193 %************************************************************************
195 The \tr{Maybe} type is in the Haskell 1.4 prelude. Moreover, the
196 required \tr{Maybe} library provides many useful functions on
197 \tr{Maybe}s. This (pre-1.3) module provides some more:
199 An \tr{Either}-like type called \tr{MaybeErr}:
201 data MaybeErr val err = Succeeded val | Failed err
204 Some operations to do with \tr{Maybe} (some commentary follows):
206 maybeToBool :: Maybe a -> Bool -- Nothing => False; Just => True
207 allMaybes :: [Maybe a] -> Maybe [a]
208 firstJust :: [Maybe a] -> Maybe a
209 findJust :: (a -> Maybe b) -> [a] -> Maybe b
211 assocMaybe :: Eq a => [(a,b)] -> a -> Maybe b
212 mkLookupFun :: (key -> key -> Bool) -- Equality predicate
213 -> [(key,val)] -- The assoc list
214 -> (key -> Maybe val) -- A lookup fun to use
215 mkLookupFunDef :: (key -> key -> Bool) -- Equality predicate
216 -> [(key,val)] -- The assoc list
217 -> val -- Value to return on failure
219 -> val -- The corresponding value
222 thenMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b
223 returnMaybe :: a -> Maybe a
225 mapMaybe :: (a -> Maybe b) -> [a] -> Maybe [b]
228 NB: @catMaybes@ which used to be here, is now available via the
229 standard @Maybe@ interface (@Maybe@ is an instance of @MonadPlus@).
231 @allMaybes@ collects a list of @Justs@ into a single @Just@, returning
232 @Nothing@ if there are any @Nothings@.
234 @firstJust@ takes a list of @Maybes@ and returns the
235 first @Just@ if there is one, or @Nothing@ otherwise.
237 @assocMaybe@ looks up in an association list, returning
238 @Nothing@ if it fails.
240 Now, some operations to do with \tr{MaybeErr} (comments follow):
242 -- a monad thing (surprise, surprise)
243 thenMaB :: MaybeErr a err -> (a -> MaybeErr b err) -> MaybeErr b err
244 returnMaB :: val -> MaybeErr val err
245 failMaB :: err -> MaybeErr val err
247 listMaybeErrs :: [MaybeErr val err] -> MaybeErr [val] [err]
248 foldlMaybeErrs :: (acc -> input -> MaybeErr acc err)
251 -> MaybeErr acc [err]
254 @listMaybeErrs@ takes a list of @MaybeErrs@ and, if they all succeed,
255 returns a @Succeeded@ of a list of their values. If any fail, it
256 returns a @Failed@ of the list of all the errors in the list.
258 @foldlMaybeErrs@ works along a list, carrying an accumulator; it
259 applies the given function to the accumulator and the next list item,
260 accumulating any errors that occur.
262 %************************************************************************
264 \subsubsection[PackedString]{The @PackedString@ type}
265 \index{PackedString module (GHC syslib)}
267 %************************************************************************
269 You need to \tr{import PackedString} and heave in your
270 \tr{-syslib ghc} to use \tr{PackedString}s.
272 The basic type and functions available are:
274 data PackedString -- abstract
276 packString :: [Char] -> PackedString
277 packStringST :: [Char] -> ST s PackedString
278 packCBytesST :: Int -> Addr -> ST s PackedString
279 packBytesForCST :: [Char] -> ST s (ByteArray Int)
280 byteArrayToPS :: ByteArray Int -> PackedString
281 unsafeByteArrayToPS :: ByteArray a -> Int -> PackedString
282 psToByteArray :: PackedString -> ByteArray Int
283 psToByteArrayST :: PackedString -> ST s (ByteArray Int)
285 unpackPS :: PackedString -> [Char]
288 We also provide a wad of list-manipulation-like functions:
290 nilPS :: PackedString
291 consPS :: Char -> PackedString -> PackedString
293 headPS :: PackedString -> Char
294 tailPS :: PackedString -> PackedString
295 nullPS :: PackedString -> Bool
296 appendPS :: PackedString -> PackedString -> PackedString
297 lengthPS :: PackedString -> Int
298 indexPS :: PackedString -> Int -> Char
299 -- 0-origin indexing into the string
300 mapPS :: (Char -> Char) -> PackedString -> PackedString
301 filterPS :: (Char -> Bool) -> PackedString -> PackedString
302 foldlPS :: (a -> Char -> a) -> a -> PackedString -> a
303 foldrPS :: (Char -> a -> a) -> a -> PackedString -> a
304 takePS :: Int -> PackedString -> PackedString
305 dropPS :: Int -> PackedString -> PackedString
306 splitAtPS :: Int -> PackedString -> (PackedString, PackedString)
307 takeWhilePS :: (Char -> Bool) -> PackedString -> PackedString
308 dropWhilePS :: (Char -> Bool) -> PackedString -> PackedString
309 spanPS :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
310 breakPS :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
311 linesPS :: PackedString -> [PackedString]
312 wordsPS :: PackedString -> [PackedString]
313 reversePS :: PackedString -> PackedString
314 concatPS :: [PackedString] -> PackedString
315 elemPS :: Char -> PackedString -> Bool
316 -- Perl-style split&join
317 splitPS :: Char -> PackedString -> [PackedString]
318 splitWithPS :: (Char -> Bool) -> PackedString -> [PackedString]
319 joinPS :: PackedString -> [PackedString] -> PackedString
321 substrPS :: PackedString -> Int -> Int -> PackedString
322 -- pluck out a piece of a PackedString
323 -- start and end chars you want; both 0-origin-specified
326 %************************************************************************
328 \subsubsection[Pretty]{The @Pretty@ type}
329 \index{Pretty module (GHC syslib)}
331 %************************************************************************
333 This is the pretty-printer that is currently used in GHC:
338 ppShow :: Int{-width-} -> Pretty -> [Char]
340 pp'SP :: Pretty -- "comma space"
341 ppComma :: Pretty -- ,
342 ppEquals :: Pretty -- =
343 ppLbrack :: Pretty -- [
344 ppLparen :: Pretty -- (
345 ppNil :: Pretty -- nothing
346 ppRparen :: Pretty -- )
347 ppRbrack :: Pretty -- ]
348 ppSP :: Pretty -- space
349 ppSemi :: Pretty -- ;
351 ppChar :: Char -> Pretty
352 ppDouble :: Double -> Pretty
353 ppFloat :: Float -> Pretty
354 ppInt :: Int -> Pretty
355 ppInteger :: Integer -> Pretty
356 ppRational :: Rational -> Pretty
357 ppStr :: [Char] -> Pretty
359 ppAbove :: Pretty -> Pretty -> Pretty
360 ppAboves :: [Pretty] -> Pretty
361 ppBeside :: Pretty -> Pretty -> Pretty
362 ppBesides :: [Pretty] -> Pretty
363 ppCat :: [Pretty] -> Pretty
364 ppHang :: Pretty -> Int -> Pretty -> Pretty
365 ppInterleave :: Pretty -> [Pretty] -> Pretty -- spacing between
366 ppIntersperse :: Pretty -> [Pretty] -> Pretty -- no spacing between
367 ppNest :: Int -> Pretty -> Pretty
368 ppSep :: [Pretty] -> Pretty
371 %************************************************************************
373 \subsubsection[Set]{The @Set@ type}
374 \index{Set module (GHC syslib)}
376 %************************************************************************
378 Our implementation of {\em sets} (key property: no duplicates) is just
379 a variant of the \tr{FiniteMap} module.
386 mkSet :: Ord a => [a] -> Set a
387 setToList :: Set a -> [a]
388 unitSet :: a -> Set a
389 singletonSet :: a -> Set a -- deprecated, use unitSet.
391 union :: Ord a => Set a -> Set a -> Set a
392 unionManySets :: Ord a => [Set a] -> Set a
393 minusSet :: Ord a => Set a -> Set a -> Set a
394 mapSet :: Ord a => (b -> a) -> Set b -> Set a
395 intersect :: Ord a => Set a -> Set a -> Set a
397 elementOf :: Ord a => a -> Set a -> Bool
398 isEmptySet :: Set a -> Bool
400 cardinality :: Set a -> Int
404 %************************************************************************
406 \subsubsection[BitSet]{The @BitSet@ interface}
407 \index{Bitset interface (GHC syslib)}
409 %************************************************************************
411 Bit sets are a fast implementation of sets of integers ranging from 0
412 to one less than the number of bits in a machine word (typically 31).
413 If any element exceeds the maximum value for a particular machine
414 architecture, the results of these operations are undefined. You have
418 data BitSet -- abstract
422 mkBS :: [Int] -> BitSet
423 unitBS :: Int -> BitSet
424 unionBS :: BitSet -> BitSet -> BitSet
425 minusBS :: BitSet -> BitSet -> BitSet
426 isEmptyBS :: BitSet -> Bool
427 intersectBS :: BitSet -> BitSet -> BitSet
428 elementBS :: Int -> BitSet -> Bool
429 listBS :: BitSet -> [Int]
432 %************************************************************************
434 \subsubsection[Util]{The @Util@ type}
435 \index{Util module (GHC syslib)}
437 %************************************************************************
439 Stuff that has been generally useful to use in writing the compiler.
440 Don't be too surprised if this stuff moves/gets-renamed/etc.
443 -- general list processing
444 forall :: (a -> Bool) -> [a] -> Bool
445 exists :: (a -> Bool) -> [a] -> Bool
447 nOfThem :: Int -> a -> [a]
448 lengthExceeds :: [a] -> Int -> Bool
449 isSingleton :: [a] -> Bool
451 --paranoid zip'ing (equal length lists)
452 zipEqual :: [a] -> [b] -> [(a,b)]
453 zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
454 zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
455 zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
456 -- lazy in second argument
457 zipLazy :: [a] -> [b] -> [(a,b)]
459 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
460 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
462 -- prefix and suffix matching on lists of characters.
463 startsWith :: {-prefix-}String -> String -> Maybe String
464 endsWith :: {-suffix-}String -> String -> Maybe String
467 assoc :: Eq a => String -> [(a, b)] -> a -> b
469 -- duplicate handling
470 hasNoDups :: Eq a => [a] -> Bool
471 equivClasses :: (a -> a -> Ordering) -> [a] -> [[a]]
472 runs :: (a -> a -> Bool) -> [a] -> [[a]]
473 removeDups :: (a -> a -> Ordering) -> [a] -> ([a], [[a]])
475 -- sorting (don't complain of no choice...)
476 quicksort :: (a -> a -> Bool) -> [a] -> [a]
477 sortLt :: (a -> a -> Bool) -> [a] -> [a]
478 stableSortLt :: (a -> a -> Bool) -> [a] -> [a]
479 mergesort :: (a -> a -> _CMP_TAG) -> [a] -> [a]
480 mergeSort :: Ord a => [a] -> [a]
481 naturalMergeSort :: Ord a => [a] -> [a]
482 mergeSortLe :: Ord a => [a] -> [a]
483 naturalMergeSortLe :: Ord a => [a] -> [a]
485 -- transitive closures
486 transitiveClosure :: (a -> [a]) -- Successor function
487 -> (a -> a -> Bool) -- Equality predicate
489 -> [a] -- The transitive closure
491 -- accumulating (Left, Right, Bi-directional)
492 mapAccumL :: (acc -> x -> (acc, y))
493 -- Function of elt of input list and
494 -- accumulator, returning new accumulator and
495 -- elt of result list
496 -> acc -- Initial accumulator
498 -> (acc, [y]) -- Final accumulator and result list
500 mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
502 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
503 -> accl -> accr -> [x]
506 --list comparison with explicit element comparer.
507 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
510 applyToPair :: ((a -> c), (b -> d)) -> (a, b) -> (c, d)
511 applyToFst :: (a -> c) -> (a, b) -> (c, b)
512 applyToSnd :: (b -> d) -> (a, b) -> (a, d)
513 foldPair :: (a->a->a, b->b->b) -> (a, b) -> [(a, b)] -> (a, b)
514 unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
517 %************************************************************************
519 \subsection[C-interfaces]{Interfaces to C libraries}
520 \index{C library interfaces}
521 \index{interfaces, C library}
523 %************************************************************************
525 The GHC system library (\tr{-syslib ghc}) also provides interfaces to
526 several useful C libraries, mostly from the GNU project.
528 %************************************************************************
530 \subsubsection[Readline]{The @Readline@ interface}
531 \index{Readline library (GHC syslib)}
532 \index{command-line editing library}
534 %************************************************************************
536 (Darren Moffat supplied the \tr{Readline} interface.)
538 The \tr{Readline} module is a straightforward interface to the GNU
539 Readline library. As such, you will need to look at the GNU
540 documentation (and have a \tr{libreadline.a} file around somewhere...)
542 You'll need to link any Readlining program with \tr{-lreadline -ltermcap},
543 besides the usual \tr{-syslib ghc} (and \tr{-fhaskell-1.3}).
545 The main function you'll use is:
547 readline :: String{-the prompt-} -> IO String
550 If you want to mess around with Full Readline G(l)ory, we also
553 rlInitialize, addHistory,
555 rlBindKey, rlAddDefun, RlCallbackFunction(..),
557 rlGetLineBuffer, rlSetLineBuffer, rlGetPoint, rlSetPoint, rlGetEnd,
558 rlSetEnd, rlGetMark, rlSetMark, rlSetDone, rlPendingInput,
560 rlPrompt, rlTerminalName, rlSetReadlineName, rlGetReadlineName
562 (All those names are just Haskellised versions of what you
563 will see in the GNU readline documentation.)
565 %************************************************************************
567 \subsubsection[Regexp]{The @Regexp@ and @MatchPS@ interfaces}
568 \index{Regex library (GHC syslib)}
569 \index{MatchPS library (GHC syslib)}
570 \index{regular-expressions library}
572 %************************************************************************
574 (Sigbjorn Finne supplied the regular-expressions interface.)
576 The \tr{Regex} library provides quite direct interface to the GNU
577 regular-expression library, for doing manipulation on
578 \tr{PackedString}s. You probably need to see the GNU documentation
579 if you are operating at this level.
581 The datatypes and functions that \tr{Regex} provides are:
583 data PatBuffer # just a bunch of bytes (mutable)
586 = REmatch (Array Int GroupBounds) -- for $1, ... $n
587 GroupBounds -- for $` (everything before match)
588 GroupBounds -- for $& (entire matched string)
589 GroupBounds -- for $' (everything after)
590 GroupBounds -- for $+ (matched by last bracket)
592 -- GroupBounds hold the interval where a group
593 -- matched inside a string, e.g.
595 -- matching "reg(exp)" "a regexp" returns the pair (5,7) for the
596 -- (exp) group. (PackedString indices start from 0)
598 type GroupBounds = (Int, Int)
601 :: PackedString -- pattern to compile
602 -> Bool -- True <=> assume single-line mode
603 -> Bool -- True <=> case-insensitive
606 re_match :: PatBuffer -- compiled regexp
607 -> PackedString -- string to match
608 -> Int -- start position
609 -> Bool -- True <=> record results in registers
610 -> PrimIO (Maybe REmatch)
612 -- Matching on 2 strings is useful when you're dealing with multiple
613 -- buffers, which is something that could prove useful for
614 -- PackedStrings, as we don't want to stuff the contents of a file
615 -- into one massive heap chunk, but load (smaller chunks) on demand.
617 re_match2 :: PatBuffer -- 2-string version
623 -> PrimIO (Maybe REmatch)
625 re_search :: PatBuffer -- compiled regexp
626 -> PackedString -- string to search
627 -> Int -- start index
629 -> Bool -- True <=> record results in registers
630 -> PrimIO (Maybe REmatch)
632 re_search2 :: PatBuffer -- Double buffer search
635 -> Int -- start index
638 -> Bool -- True <=> results in registers
639 -> PrimIO (Maybe REmatch)
642 The \tr{MatchPS} module provides Perl-like ``higher-level'' facilities
643 to operate on \tr{PackedStrings}. The regular expressions in
644 question are in Perl syntax. The ``flags'' on various functions can
645 include: \tr{i} for case-insensitive, \tr{s} for single-line mode, and
646 \tr{g} for global. (It's probably worth your time to peruse the
650 matchPS :: PackedString -- regexp
651 -> PackedString -- string to match
653 -> Maybe REmatch -- info about what matched and where
655 searchPS :: PackedString -- regexp
656 -> PackedString -- string to match
660 -- Perl-like match-and-substitute:
661 substPS :: PackedString -- regexp
662 -> PackedString -- replacement
664 -> PackedString -- string
667 -- same as substPS, but no prefix and suffix:
668 replacePS :: PackedString -- regexp
669 -> PackedString -- replacement
671 -> PackedString -- string
674 match2PS :: PackedString -- regexp
675 -> PackedString -- string1 to match
676 -> PackedString -- string2 to match
680 search2PS :: PackedString -- regexp
681 -> PackedString -- string to match
682 -> PackedString -- string to match
686 -- functions to pull the matched pieces out of an REmatch:
688 getMatchesNo :: REmatch -> Int
689 getMatchedGroup :: REmatch -> Int -> PackedString -> PackedString
690 getWholeMatch :: REmatch -> PackedString -> PackedString
691 getLastMatch :: REmatch -> PackedString -> PackedString
692 getAfterMatch :: REmatch -> PackedString -> PackedString
694 -- (reverse) brute-force string matching;
695 -- Perl equivalent is index/rindex:
696 findPS, rfindPS :: PackedString -> PackedString -> Maybe Int
698 -- Equivalent to Perl "chop" (off the last character, if any):
699 chopPS :: PackedString -> PackedString
701 -- matchPrefixPS: tries to match as much as possible of strA starting
702 -- from the beginning of strB (handy when matching fancy literals in
704 matchPrefixPS :: PackedString -> PackedString -> Int
707 %************************************************************************
709 \subsubsection[Socket]{Network-interface toolkit---@Socket@ and @SocketPrim@}
710 \index{SocketPrim interface (GHC syslib)}
711 \index{Socket interface (GHC syslib)}
712 \index{network-interface library}
713 \index{sockets library}
714 \index{BSD sockets library}
716 %************************************************************************
718 (Darren Moffat supplied the network-interface toolkit.)
720 Your best bet for documentation is to look at the code---really!---
721 normally in \tr{hslibs/ghc/src/{BSD,Socket,SocketPrim}.lhs}.
723 The \tr{BSD} module provides functions to get at system-database info;
724 pretty straightforward if you're into this sort of thing:
726 getHostName :: IO String
728 getServiceByName :: ServiceName -> IO ServiceEntry
729 getServicePortNumber:: ServiceName -> IO PortNumber
730 getServiceEntry :: IO ServiceEntry
731 setServiceEntry :: Bool -> IO ()
732 endServiceEntry :: IO ()
734 getProtocolByName :: ProtocolName -> IO ProtocolEntry
735 getProtocolByNumber :: ProtocolNumber -> IO ProtcolEntry
736 getProtocolNumber :: ProtocolName -> ProtocolNumber
737 getProtocolEntry :: IO ProtocolEntry
738 setProtocolEntry :: Bool -> IO ()
739 endProtocolEntry :: IO ()
741 getHostByName :: HostName -> IO HostEntry
742 getHostByAddr :: Family -> HostAddress -> IO HostEntry
743 getHostEntry :: IO HostEntry
744 setHostEntry :: Bool -> IO ()
745 endHostEntry :: IO ()
748 The \tr{SocketPrim} interface provides quite direct access to the
749 socket facilities in a BSD Unix system, including all the
750 complications. We hope you don't need to use it! See the source if
753 The \tr{Socket} interface is a ``higher-level'' interface to sockets,
754 and it is what we recommend. Please tell us if the facilities it
755 offers are inadequate to your task!
757 The interface is relatively modest:
759 connectTo :: Hostname -> PortID -> IO Handle
760 listenOn :: PortID -> IO Socket
762 accept :: Socket -> IO (Handle, HostName)
763 sendTo :: Hostname -> PortID -> String -> IO ()
765 recvFrom :: Hostname -> PortID -> IO String
766 socketPort :: Socket -> IO PortID
768 data PortID -- PortID is a non-abstract type
769 = Service String -- Service Name eg "ftp"
770 | PortNumber Int -- User defined Port Number
771 | UnixSocket String -- Unix family socket in file system
773 type Hostname = String
776 Various examples of networking Haskell code are provided in
777 %\tr{ghc/misc/examples/}, notably the \tr{net???/Main.hs} programs.
779 %************************************************************************
781 \subsection[Posix-library]{The Posix system library}
782 \index{Posix system library}
783 \index{system library, Posix}
785 %************************************************************************
787 The @Posix@ interface gives you access to the set of OS services
788 standardised by POSIX 1003.1b (or the {\em IEEE Portable Operating System
789 Interface for Computing Environments} - IEEE Std. 1003.1). The
790 interface is accessed by \tr{import Posix} and adding
791 \tr{-syslib posix} on your command-line.
793 \subsubsection[Posix data types]{Posix data types}
794 \index{Posix, data types}
798 data ByteCount -- instances of : Eq Ord Num Real Integral Ix Enum Show
801 A \tr{ByteCount} is a primitive of type \tr{unsigned}. At a minimum,
802 an conforming implementation must support values in the range
806 data ClockTick -- instances of : Eq Ord Num Real Integral Ix Enum Show
809 A \tr{ClockTick} is a primitive of type \tr{clock_t}, which
810 is used to measure intervals of time in fractions of a second. The
811 resolution is determined by \tr{getSysVar ClockTick}.
814 data DeviceID -- instances of : Eq Ord Num Real Integral Ix Enum Show
817 A \tr{DeviceID} is a primitive of type \tr{dev_t}. It must
818 be an arithmetic type.
821 data EpochTime -- instances of : Eq Ord Num Real Integral Ix Enum Show
824 A \tr{EpochTime} is a primitive of type \tr{time_t}, which is
825 used to measure seconds since the Epoch. At a minimum, the implementation
826 must support values in the range \tr{[0, INT_MAX]}.
829 data FileID -- instances of : Eq Ord Num Real Integral Ix Enum Show
832 A \tr{FileID} is a primitive of type \tr{ino_t}. It must
833 be an arithmetic type.
836 data FileMode -- instances of : Eq Ord Num Real Integral Ix Enum Show
839 A \tr{FileMode} is a primitive of type \tr{mode_t}.
840 It must be an arithmetic type.
843 data FileOffset -- instances of : Eq Ord Num Real Integral Ix Enum Show
846 A \tr{FileOffset} is a primitive of type \tr{off_t}. It must
847 be an arithmetic type.
850 data GroupID -- instances of : Eq Ord Num Real Integral Ix Enum Show
853 A \tr{GroupID} is a primitive of type \tr{gid_t}. It must
854 be an arithmetic type.
856 data Limit -- instances of : Eq Ord Num Real Integral Ix Enum Show
859 A \tr{Limit} is a primitive of type \tr{long}.
860 At a minimum, the implementation must support values in the range
861 \tr{[LONG_MIN, LONG_MAX]}.
864 data LinkCount -- instances of : Eq Ord Num Real Integral Ix Enum Show
867 A \tr{LinkCount} is a primitive of type \tr{nlink_t}. It must
868 be an arithmetic type.
871 data ProcessID -- instances of : Eq Ord Num Real Integral Ix Enum Show
872 type ProcessGroupID = ProcessID
875 A \tr{ProcessID} is a primitive of type \tr{pid_t}. It
876 must be a signed arithmetic type.
878 data UserID -- instances of : Eq Ord Num Real Integral Ix Enum Show
881 A \tr{UserID} is a primitive of type \tr{uid_t}. It
882 must be an arithmetic type.
887 A \tr{DirStream} is a primitive of type \tr{DIR *}.
892 A \tr{FileStatus} is a primitive of type \tr{struct stat}.
898 A \tr{GroupEntry} is a primitive of type \tr{struct group}.
903 \tr{ProcessTimes} is a primitive structure containing a
904 \tr{clock_t} and a \tr{struct tms}.
910 An \tr{SignalSet} is a primitive of type \tr{sigset_t}.
916 A \tr{SystemID} is a primitive of type \tr{struct utsname}.
919 data TerminalAttributes
921 \tr{TerminalAttributes} is a primitive of type \tr{struct termios}.
927 A \tr{UserEntry} is a primitive of type \tr{struct passwd}.
930 data BaudRate = B0 | B50 | B75 | B110 | B134 | B150 | B200 | B300 | B600
931 | B1200 | B1800 | B2400 | B4800 | B9600 | B19200 | B38400
936 intToFd :: Int -> Fd -- use with care.
938 data FdOption = AppendOnWrite
942 data ControlCharacter = EndOfFile
954 type FileLock = (LockRequest, SeekMode, FileOffset, FileOffset)
955 -- whence start length
957 data FlowAction = SuspendOutput | RestartOutput | TransmitStop | TransmitStart
959 data Handler = Default | Ignore | Catch (IO ())
961 data LockRequest = ReadLock | WriteLock | Unlock
964 data OpenMode = ReadOnly | WriteOnly | ReadWrite
966 data PathVar = LinkLimit
972 | SetOwnerAndGroupIsRestricted
973 | FileNamesAreNotTruncated
975 data QueueSelector = InputQueue | OutputQueue | BothQueues
979 data SysVar = ArgumentLimit
988 data TerminalMode = InterruptOnBreak -- BRKINT
990 | IgnoreBreak -- IGNBRK
992 | IgnoreParityErrors -- IGNPAR
994 | CheckParity -- INPCK
995 | StripHighBit -- ISTRIP
996 | StartStopInput -- IXOFF
997 | StartStopOutput -- IXON
998 | MarkParityErrors -- PARMRK
999 | ProcessOutput -- OPOST
1000 | LocalMode -- CLOCAL
1001 | ReadEnable -- CREAD
1002 | TwoStopBits -- CSTOPB
1003 | HangupOnClose -- HUPCL
1004 | EnableParity -- PARENB
1005 | OddParity -- PARODD
1006 | EnableEcho -- ECHO
1007 | EchoErase -- ECHOE
1010 | ProcessInput -- ICANON
1011 | ExtendedFunctions -- IEXTEN
1012 | KeyboardInterrupts -- ISIG
1013 | NoFlushOnInterrupt -- NOFLSH
1014 | BackgroundWriteInterrupt -- TOSTOP
1016 data TerminalState = Immediately | WhenDrained | WhenFlushed
1018 data ProcessStatus = Exited ExitCode
1024 \subsubsection[Process Primitives]{Posix Process Primitives}
1027 forkProcess :: IO (Maybe ProcessID)
1030 \tr{forkProcess} calls \tr{fork}, returning
1031 \tr{Just pid} to the parent, where \tr{pid} is the
1032 ProcessID of the child, and returning \tr{Nothing} to the
1036 executeFile :: FilePath -- Command
1037 -> Bool -- Search PATH?
1038 -> [String] -- Arguments
1039 -> Maybe [(String, String)] -- Environment
1043 \tr{executeFile cmd args env} calls one of the
1044 \tr{execv*} family, depending on whether or not the current
1045 PATH is to be searched for the command, and whether or not an
1046 environment is provided to supersede the process's current
1047 environment. The basename (leading directory names suppressed) of
1048 the command is passed to \tr{execv*} as \tr{arg[0]};
1049 the argument list passed to \tr{executeFile} therefore begins
1053 Search PATH? Supersede environ? Call
1054 ~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ~~~~~~~
1061 Note that \tr{execvpe} is not provided by the POSIX standard, and must
1062 be written by hand. Care must be taken to ensure that the search path
1063 is extracted from the original environment, and not from the
1064 environment to be passed on to the new image.
1066 A successful \tr{executeFile} overlays the current process image with
1067 a new one, so it only returns on failure.
1069 runProcess :: FilePath -- Command
1070 -> [String] -- Arguments
1071 -> Maybe [(String, String)] -- Environment (Nothing -> Inherited)
1072 -> Maybe FilePath -- Working directory (Nothing -> inherited)
1073 -> Maybe Handle -- stdin (Nothing -> inherited)
1074 -> Maybe Handle -- stdout (Nothing -> inherited)
1075 -> Maybe Handle -- stderr (Nothing -> inherited)
1079 \tr{runProcess} is our candidate for the high-level OS-independent
1082 \tr{runProcess cmd args env wd inhdl outhdl errhdl} runs \tr{cmd}
1083 (searching the current \tr{PATH}) with arguments \tr{args}. If
1084 \tr{env} is \tr{Just pairs}, the command is executed with the
1085 environment specified by \tr{pairs} of variables and values;
1086 otherwise, the command is executed with the current environment. If
1087 \tr{wd} is \tr{Just dir}, the command is executed with working
1088 directory \tr{dir}; otherwise, the command is executed in the current
1089 working directory. If \tr{{in,out,err}hdl} is \tr{Just handle}, the
1090 command is executed with the \tr{Fd} for \tr{std{in,out,err}}
1091 attached to the specified \tr{handle}; otherwise, the \tr{Fd} for
1092 \tr{std{in,out,err}} is left unchanged.
1095 getProcessStatus :: Bool -- Block?
1096 -> Bool -- Stopped processes?
1098 -> IO (Maybe ProcessStatus)
1101 \tr{getProcessStatus blk stopped pid} calls \tr{waitpid}, returning
1102 \tr{Just tc}, the \tr{ProcessStatus} for process \tr{pid} if it is
1103 available, \tr{Nothing} otherwise. If \tr{blk} is \tr{False}, then
1104 \tr{WNOHANG} is set in the options for \tr{waitpid}, otherwise not.
1105 If \tr{stopped} is \tr{True}, then \tr{WUNTRACED} is set in the
1106 options for \tr{waitpid}, otherwise not.
1109 getGroupProcessStatus :: Bool -- Block?
1110 -> Bool -- Stopped processes?
1112 -> IO (Maybe (ProcessID, ProcessStatus))
1115 \tr{getGroupProcessStatus blk stopped pgid} calls \tr{waitpid},
1116 returning \tr{Just (pid, tc)}, the \tr{ProcessID} and
1117 \tr{ProcessStatus} for any process in group \tr{pgid} if one is
1118 available, \tr{Nothing} otherwise. If \tr{blk} is \tr{False}, then
1119 \tr{WNOHANG} is set in the options for \tr{waitpid}, otherwise not.
1120 If \tr{stopped} is \tr{True}, then \tr{WUNTRACED} is set in the
1121 options for \tr{waitpid}, otherwise not.
1124 getAnyProcessStatus :: Bool -- Block?
1125 -> Bool -- Stopped processes?
1126 -> IO (Maybe (ProcessID, ProcessStatus))
1129 \tr{getAnyProcessStatus blk stopped} calls \tr{waitpid}, returning
1130 \tr{Just (pid, tc)}, the \tr{ProcessID} and \tr{ProcessStatus} for any
1131 child process if one is available, \tr{Nothing} otherwise. If
1132 \tr{blk} is \tr{False}, then \tr{WNOHANG} is set in the options for
1133 \tr{waitpid}, otherwise not. If \tr{stopped} is \tr{True}, then
1134 \tr{WUNTRACED} is set in the options for \tr{waitpid}, otherwise not.
1137 exitImmediately :: ExitCode -> IO ()
1140 \tr{exitImmediately status} calls \tr{_exit} to terminate the process
1141 with the indicated exit \tr{status}.
1142 The operation never returns.
1145 getEnvironment :: IO [(String, String)]
1148 \tr{getEnvironment} parses the environment variable mapping provided by
1149 \tr{environ}, returning \tr{(variable, value)} pairs.
1150 The operation never fails.
1153 setEnvironment :: [(String, String)] -> IO ()
1156 \tr{setEnvironment} replaces the process environment with the provided
1157 mapping of \tr{(variable, value)} pairs.
1160 getEnvVar :: String -> IO String
1163 \tr{getEnvVar var} returns the value associated with variable \tr{var}
1164 in the current environment (identical functionality provided through
1165 standard Haskell library function @System.getEnv@).
1167 The operation may fail with:
1170 \item[\tr{NoSuchThing}]
1171 The variable has no mapping in the current environment.
1175 setEnvVar :: String -> String -> IO ()
1178 \tr{setEnvVar var val} sets the value associated with variable \tr{var}
1179 in the current environment to be \tr{val}. Any previous mapping is
1183 removeEnvVar :: String -> IO ()
1186 \tr{removeEnvVar var} removes any value associated with variable \tr{var}
1187 in the current environment. Deleting a variable for which there is no mapping
1188 does not generate an error.
1191 nullSignal :: Signal
1194 backgroundRead, sigTTIN :: Signal
1195 backgroundWrite, sigTTOU :: Signal
1196 continueProcess, sigCONT :: Signal
1197 floatingPointException, sigFPE :: Signal
1198 illegalInstruction, sigILL :: Signal
1199 internalAbort, sigABRT :: Signal
1200 keyboardSignal, sigINT :: Signal
1201 keyboardStop, sigTSTP :: Signal
1202 keyboardTermination, sigQUIT :: Signal
1203 killProcess, sigKILL :: Signal
1204 lostConnection, sigHUP :: Signal
1205 openEndedPipe, sigPIPE :: Signal
1206 processStatusChanged, sigCHLD :: Signal
1207 realTimeAlarm, sigALRM :: Signal
1208 segmentationViolation, sigSEGV :: Signal
1209 softwareStop, sigSTOP :: Signal
1210 softwareTermination, sigTERM :: Signal
1211 userDefinedSignal1, sigUSR1 :: Signal
1212 userDefinedSignal2, sigUSR2 :: Signal
1214 signalProcess :: Signal -> ProcessID -> IO ()
1217 \tr{signalProcess int pid} calls \tr{kill} to signal
1218 process \tr{pid} with interrupt signal \tr{int}.
1221 raiseSignal :: Signal -> IO ()
1224 \tr{raiseSignal int} calls \tr{kill} to signal the current process
1225 with interrupt signal \tr{int}.
1228 signalProcessGroup :: Signal -> ProcessGroupID -> IO ()
1231 \tr{signalProcessGroup int pgid} calls \tr{kill} to signal
1232 all processes in group \tr{pgid} with interrupt signal \tr{int}.
1235 setStoppedChildFlag :: Bool -> IO Bool
1238 \tr{setStoppedChildFlag bool} sets a flag which controls whether or
1239 not the \tr{NOCLDSTOP} option will be used the next time a signal
1240 handler is installed for \tr{SIGCHLD}. If \tr{bool} is \tr{True} (the
1241 default), \tr{NOCLDSTOP} will not be used; otherwise it will be. The
1242 operation never fails.
1245 queryStoppedChildFlag :: IO Bool
1248 \tr{queryStoppedChildFlag} queries the flag which
1249 controls whether or not the \tr{NOCLDSTOP} option will be used
1250 the next time a signal handler is installed for \tr{SIGCHLD}.
1251 If \tr{NOCLDSTOP} will be used, it returns \tr{False};
1252 otherwise (the default) it returns \tr{True}.
1253 The operation never fails.
1256 emptySignalSet :: SignalSet
1257 fullSignalSet :: SignalSet
1258 addSignal :: Signal -> SignalSet -> SignalSet
1259 deleteSignal :: Signal -> SignalSet -> SignalSet
1260 inSignalSet :: Signal -> SignalSet -> Bool
1262 installHandler :: Signal
1264 -> Maybe SignalSet -- other signals to block
1265 -> IO Handler -- old handler
1268 \tr{installHandler int handler iset} calls \tr{sigaction} to install
1269 an interrupt handler for signal \tr{int}. If \tr{handler} is
1270 \tr{Default}, \tr{SIG_DFL} is installed; if \tr{handler} is
1271 \tr{Ignore}, \tr{SIG_IGN} is installed; if \tr{handler} is
1272 \tr{Catch action}, a handler is installed which will invoke \tr{action} as a
1273 replacement for \tr{main}. If \tr{iset} is \tr{Just s}, then the
1274 \tr{sa_mask} of the \tr{sigaction} structure is set to \tr{s};
1275 otherwise it is cleared. The previously installed signal handler for
1276 \tr{int} is returned.
1279 getSignalMask :: IO SignalSet
1282 \tr{getSignalMask} calls \tr{sigprocmask} to determine the
1283 set of interrupts which are currently being blocked.
1286 setSignalMask :: SignalSet -> IO SignalSet
1289 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1290 \tr{SIG_SETMASK} to block all interrupts in \tr{mask}. The
1291 previous set of blocked interrupts is returned.
1294 blockSignals :: SignalSet -> IO SignalSet
1297 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1298 \tr{SIG_BLOCK} to add all interrupts in \tr{mask} to the
1299 set of blocked interrupts. The previous set of blocked interrupts is returned.
1302 unBlockSignals :: SignalSet -> IO SignalSet
1305 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1306 \tr{SIG_UNBLOCK} to remove all interrupts in \tr{mask} from the
1307 set of blocked interrupts. The previous set of blocked interrupts is returned.
1310 getPendingSignals :: IO SignalSet
1313 \tr{getPendingSignals} calls \tr{sigpending} to obtain
1314 the set of interrupts which have been received but are currently blocked.
1317 awaitSignal :: Maybe SignalSet -> IO ()
1320 \tr{awaitSignal iset} suspends execution until an interrupt is received.
1321 If \tr{iset} is \tr{Just s}, \tr{awaitSignal} calls
1322 \tr{sigsuspend}, installing \tr{s} as the new signal mask before
1323 suspending execution; otherwise, it calls \tr{pause}. If successful,
1324 \tr{awaitSignal} does not return.
1327 scheduleAlarm :: Int -> IO Int
1330 \tr{scheduleAlarm i} calls \tr{alarm} to schedule a real time
1331 alarm at least \tr{i} seconds in the future.
1334 sleep :: Int -> IO ()
1337 \tr{sleep i} calls \tr{sleep} to suspend execution of the
1338 program until at least \tr{i} seconds have elapsed or a signal is
1341 \subsubsection[Process Environment]{Posix Process Environment}
1342 \index{Posix, process environment}
1345 getProcessID :: IO ProcessID
1348 \tr{getProcessID} calls \tr{getpid} to obtain the \tr{ProcessID} for
1349 the current process.
1352 getParentProcessID :: IO ProcessID
1355 \tr{getProcessID} calls \tr{getppid} to obtain the \tr{ProcessID} for
1356 the parent of the current process.
1359 getRealUserID :: IO UserID
1362 \tr{getRealUserID} calls \tr{getuid} to obtain the real \tr{UserID}
1363 associated with the current process.
1366 getEffectiveUserID :: IO UserID
1369 \tr{getRealUserID} calls \tr{geteuid} to obtain the effective
1370 \tr{UserID} associated with the current process.
1373 setUserID :: UserID -> IO ()
1376 \tr{setUserID uid} calls \tr{setuid} to set the real, effective, and
1377 saved set-user-id associated with the current process to \tr{uid}.
1380 getLoginName :: IO String
1383 \tr{getLoginName} calls \tr{getlogin} to obtain the login name
1384 associated with the current process.
1387 getRealGroupID :: IO GroupID
1390 \tr{getRealGroupID} calls \tr{getgid} to obtain the real \tr{GroupID}
1391 associated with the current process.
1394 getEffectiveGroupID :: IO GroupID
1397 \tr{getEffectiveGroupID} calls \tr{getegid} to obtain the effective
1398 \tr{GroupID} associated with the current process.
1401 setGroupID :: GroupID -> IO ()
1404 \tr{setGroupID gid} calls \tr{setgid} to set the real, effective, and
1405 saved set-group-id associated with the current process to \tr{gid}.
1408 getGroups :: IO [GroupID]
1411 \tr{getGroups} calls \tr{getgroups} to obtain the list of
1412 supplementary \tr{GroupID}s associated with the current process.
1415 getEffectiveUserName :: IO String
1418 \tr{getEffectiveUserName} calls \tr{cuserid} to obtain a name
1419 associated with the effective \tr{UserID} of the process.
1422 getProcessGroupID :: IO ProcessGroupID
1425 \tr{getProcessGroupID} calls \tr{getpgrp} to obtain the
1426 \tr{ProcessGroupID} for the current process.
1429 createProcessGroup :: ProcessID -> IO ProcessGroupID
1432 \tr{createProcessGroup pid} calls \tr{setpgid} to make
1433 process \tr{pid} a new process group leader.
1436 joinProcessGroup :: ProcessGroupID -> IO ProcessGroupID
1439 \tr{joinProcessGroup pgid} calls \tr{setpgid} to set the
1440 \tr{ProcessGroupID} of the current process to \tr{pgid}.
1443 setProcessGroupID :: ProcessID -> ProcessGroupID -> IO ()
1446 \tr{setProcessGroupID pid pgid} calls \tr{setpgid} to set the
1447 \tr{ProcessGroupID} for process \tr{pid} to \tr{pgid}.
1450 createSession :: IO ProcessGroupID
1453 \tr{createSession} calls \tr{setsid} to create a new session
1454 with the current process as session leader.
1457 systemName :: SystemID -> String
1458 nodeName :: SystemID -> String
1459 release :: SystemID -> String
1460 version :: SystemID -> String
1461 machine :: SystemID -> String
1463 getSystemID :: IO SystemID
1466 \tr{getSystemID} calls \tr{uname} to obtain information
1467 about the current operating system.
1470 > epochTime :: IO EpochTime
1473 \tr{epochTime} calls \tr{time} to obtain the number of
1474 seconds that have elapsed since the epoch (Jan 01 00:00:00 GMT 1970).
1477 elapsedTime :: ProcessTimes -> ClockTick
1478 userTime :: ProcessTimes -> ClockTick
1479 systemTime :: ProcessTimes -> ClockTick
1480 childUserTime :: ProcessTimes -> ClockTick
1481 childSystemTime :: ProcessTimes -> ClockTick
1483 getProcessTimes :: IO ProcessTimes
1486 \tr{getProcessTimes} calls \tr{times} to obtain time-accounting
1487 information for the current process and its children.
1490 getControllingTerminalName :: IO FilePath
1493 \tr{getControllingTerminalName} calls \tr{ctermid} to obtain
1494 a name associated with the controlling terminal for the process. If a
1495 controlling terminal exists,
1496 \tr{getControllingTerminalName} returns the name of the
1497 controlling terminal.
1499 The operation may fail with:
1502 \item[\tr{NoSuchThing}]
1503 There is no controlling terminal, or its name cannot be determined.
1504 \item[\tr{SystemError}]
1505 Various other causes.
1509 getTerminalName :: Fd -> IO FilePath
1512 \tr{getTerminalName fd} calls \tr{ttyname} to obtain a name associated
1513 with the terminal for \tr{Fd} \tr{fd}. If \tr{fd} is associated
1514 with a terminal, \tr{getTerminalName} returns the name of the
1517 The operation may fail with:
1520 \item[\tr{InappropriateType}]
1521 The channel is not associated with a terminal.
1522 \item[\tr{NoSuchThing}]
1523 The channel is associated with a terminal, but it has no name.
1524 \item[\tr{SystemError}]
1525 Various other causes.
1529 queryTerminal :: Fd -> IO Bool
1532 \tr{queryTerminal fd} calls \tr{isatty} to determine whether or
1533 not \tr{Fd} \tr{fd} is associated with a terminal.
1536 getSysVar :: SysVar -> IO Limit
1539 \tr{getSysVar var} calls \tr{sysconf} to obtain the
1540 dynamic value of the requested configurable system limit or option.
1541 For defined system limits, \tr{getSysVar} returns the associated
1542 value. For defined system options, the result of \tr{getSysVar}
1543 is undefined, but not failure.
1545 The operation may fail with:
1548 \item[\tr{NoSuchThing}]
1549 The requested system limit or option is undefined.
1552 \subsubsection[Files and Directories]{Posix operations on files and directories}
1553 \index{Posix, files and directories}
1556 openDirStream :: FilePath -> IO DirStream
1559 \tr{openDirStream dir} calls \tr{opendir} to obtain a
1560 directory stream for \tr{dir}.
1563 readDirStream :: DirStream -> IO String
1566 \tr{readDirStream dp} calls \tr{readdir} to obtain the
1567 next directory entry (\tr{struct dirent}) for the open directory
1568 stream \tr{dp}, and returns the \tr{d_name} member of that
1571 The operation may fail with:
1575 End of file has been reached.
1576 \item[\tr{SystemError}]
1577 Various other causes.
1581 rewindDirStream :: DirStream -> IO ()
1584 \tr{rewindDirStream dp} calls \tr{rewinddir} to reposition
1585 the directory stream \tr{dp} at the beginning of the directory.
1588 closeDirStream :: DirStream -> IO ()
1591 \tr{closeDirStream dp} calls \tr{closedir} to close
1592 the directory stream \tr{dp}.
1595 getWorkingDirectory :: IO FilePath
1598 \tr{getWorkingDirectory} calls \tr{getcwd} to obtain the name
1599 of the current working directory.
1602 changeWorkingDirectory :: FilePath -> IO ()
1605 \tr{changeWorkingDirectory dir} calls \tr{chdir} to change
1606 the current working directory to \tr{dir}.
1609 nullFileMode :: FileMode -- ---------
1610 ownerReadMode :: FileMode -- r--------
1611 ownerWriteMode :: FileMode -- -w-------
1612 ownerExecuteMode :: FileMode -- --x------
1613 groupReadMode :: FileMode -- ---r-----
1614 groupWriteMode :: FileMode -- ----w----
1615 groupExecuteMode :: FileMode -- -----x---
1616 otherReadMode :: FileMode -- ------r--
1617 otherWriteMode :: FileMode -- -------w-
1618 otherExecuteMode :: FileMode -- --------x
1619 setUserIDMode :: FileMode -- --S------
1620 setGroupIDMode :: FileMode -- -----S---
1622 stdFileMode :: FileMode -- rw-rw-rw-
1624 ownerModes :: FileMode -- rwx------
1625 groupModes :: FileMode -- ---rwx---
1626 otherModes :: FileMode -- ------rwx
1627 accessModes :: FileMode -- rwxrwxrwx
1629 unionFileModes :: FileMode -> FileMode -> FileMode
1630 intersectFileModes :: FileMode -> FileMode -> FileMode
1633 stdInput = intToFd 0
1636 stdOutput = intToFd 1
1639 stdError = intToFd 2
1641 data OpenFileFlags =
1652 -> Maybe FileMode -- Just x => O_CREAT, Nothing => must exist
1657 \tr{openFd path acc mode (OpenFileFlags app excl noctty nonblock trunc)} calls
1658 \tr{open} to obtain a \tr{Fd} for the file \tr{path} with access
1659 mode \tr{acc}. If \tr{mode} is \tr{Just m}, the \tr{O_CREAT} flag is
1660 set and the file's permissions will be based on \tr{m} if it does not
1661 already exist; otherwise, the \tr{O_CREAT} flag is not set. The
1662 arguments \tr{app}, \tr{excl}, \tr{noctty}, \tr{nonblock}, and
1663 \tr{trunc} control whether or not the flags \tr{O_APPEND},
1664 \tr{O_EXCL}, \tr{O_NOCTTY}, \tr{O_NONBLOCK}, and \tr{O_TRUNC} are set,
1668 createFile :: FilePath -> FileMode -> IO Fd
1671 \tr{createFile path mode} calls \tr{creat} to obtain a \tr{Fd}
1672 for file \tr{path}, which will be created with permissions based on
1673 \tr{mode} if it does not already exist.
1676 setFileCreationMask :: FileMode -> IO FileMode
1679 \tr{setFileCreationMask mode} calls \tr{umask} to set
1680 the process's file creation mask to \tr{mode}. The previous file
1681 creation mask is returned.
1684 createLink :: FilePath -> FilePath -> IO ()
1687 \tr{createLink old new} calls \tr{link} to create a
1688 new path, \tr{new}, linked to an existing file, \tr{old}.
1690 createDirectory :: FilePath -> FileMode -> IO ()
1693 \tr{createDirectory dir mode} calls \tr{mkdir} to
1694 create a new directory, \tr{dir}, with permissions based on
1698 createNamedPipe :: FilePath -> FileMode -> IO ()
1701 \tr{createNamedPipe fifo mode} calls \tr{mkfifo} to
1702 create a new named pipe, \tr{fifo}, with permissions based on
1706 removeLink :: FilePath -> IO ()
1709 \tr{removeLink path} calls \tr{unlink} to remove the link
1713 removeDirectory :: FilePath -> IO ()
1716 \tr{removeDirectory dir} calls \tr{rmdir} to remove the
1717 directory named \tr{dir}.
1720 rename :: FilePath -> FilePath -> IO ()
1723 \tr{rename old new} calls \tr{rename} to rename a
1724 file or directory from \tr{old} to \tr{new}.
1727 fileMode :: FileStatus -> FileMode
1729 fileID :: FileStatus -> FileID
1730 deviceID :: FileStatus -> DeviceID
1732 linkCount :: FileStatus -> LinkCount
1734 fileOwner :: FileStatus -> UserID
1735 fileGroup :: FileStatus -> GroupID
1736 fileSize :: FileStatus -> FileOffset
1738 accessTime :: FileStatus -> EpochTime
1739 modificationTime :: FileStatus -> EpochTime
1740 statusChangeTime :: FileStatus -> EpochTime
1742 isDirectory :: FileStatus -> Bool
1743 isCharacterDevice :: FileStatus -> Bool
1744 isBlockDevice :: FileStatus -> Bool
1745 isRegularFile :: FileStatus -> Bool
1746 isNamedPipe :: FileStatus -> Bool
1748 getFileStatus :: FilePath -> IO FileStatus
1751 \tr{getFileStatus path} calls \tr{stat} to get the
1752 \tr{FileStatus} information for the file \tr{path}.
1755 getFdStatus :: Fd -> IO FileStatus
1758 \tr{getFdStatus fd} calls \tr{fstat} to get the
1759 \tr{FileStatus} information for the file associated with
1763 queryAccess :: FilePath -> Bool -> Bool -> Bool -> IO Bool
1766 \tr{queryAccess path r w x} calls \tr{access} to test the access
1767 permissions for file \tr{path}. The three arguments, \tr{r}, \tr{w},
1768 and \tr{x} control whether or not \tr{access} is called with
1769 \tr{R_OK}, \tr{W_OK}, and \tr{X_OK} respectively.
1772 queryFile :: FilePath -> IO Bool
1775 \tr{queryFile path} calls \tr{access} with \tr{F_OK} to test for the
1776 existence for file \tr{path}.
1779 setFileMode :: FilePath -> FileMode -> IO ()
1782 \tr{setFileMode path mode} calls \tr{chmod} to set the
1783 permission bits associated with file \tr{path} to \tr{mode}.
1786 setOwnerAndGroup :: FilePath -> UserID -> GroupID -> IO ()
1789 \tr{setOwnerAndGroup path uid gid} calls \tr{chown} to
1790 set the \tr{UserID} and \tr{GroupID} associated with file
1791 \tr{path} to \tr{uid} and \tr{gid}, respectively.
1794 setFileTimes :: FilePath -> EpochTime -> EpochTime -> IO ()
1797 \tr{setFileTimes path atime mtime} calls \tr{utime} to
1798 set the access and modification times associated with file
1799 \tr{path} to \tr{atime} and \tr{mtime}, respectively.
1802 touchFile :: FilePath -> IO ()
1805 \tr{touchFile path} calls \tr{utime} to
1806 set the access and modification times associated with file
1807 \tr{path} to the current time.
1810 getPathVar :: PathVar -> FilePath -> IO Limit
1813 \tr{getPathVar var path} calls \tr{pathconf} to obtain the
1814 dynamic value of the requested configurable file limit or option associated
1815 with file or directory \tr{path}. For
1816 defined file limits, \tr{getPathVar} returns the associated
1817 value. For defined file options, the result of \tr{getPathVar}
1818 is undefined, but not failure.
1819 The operation may fail with:
1821 \item[\tr{NoSuchThing}]
1822 The requested file limit or option is undefined.
1823 \item[\tr{SystemError}]
1824 Various other causes.
1829 getFdVar :: PathVar -> Fd -> IO Limit
1832 \tr{getFdVar var fd} calls \tr{fpathconf} to obtain the
1833 dynamic value of the requested configurable file limit or option associated
1834 with the file or directory attached to the open channel \tr{fd}.
1835 For defined file limits, \tr{getFdVar} returns the associated
1836 value. For defined file options, the result of \tr{getFdVar}
1837 is undefined, but not failure.
1839 The operation may fail with:
1842 \item[\tr{NoSuchThing}]
1843 The requested file limit or option is undefined.
1844 \item[\tr{SystemError}]
1845 Various other causes.
1848 \subsubsection[Inut Output]{Posix Input and Output Primitives}
1849 \index{Posix, input/output}
1852 createPipe :: IO (Fd, Fd)
1855 \tr{createPipe} calls \tr{pipe} to create a pipe and returns a pair of
1856 \tr{Fd}s, the first for writing and the second for reading.
1862 \tr{dup fd} calls \tr{dup} to duplicate \tr{Fd} \tr{fd} to
1866 dupTo :: Fd -> Fd -> IO ()
1869 \tr{dupTo src dst} calls \tr{dup2} to duplicate \tr{Fd}
1870 \tr{src} to \tr{Fd} \tr{dst}.
1873 fdClose :: Fd -> IO ()
1876 \tr{fdClose fd} calls \tr{close} to close \tr{Fd} \tr{fd}.
1879 fdRead :: Fd -> ByteCount -> IO (String, ByteCount)
1882 \tr{fdRead fd nbytes} calls \tr{read} to read at most \tr{nbytes}
1883 bytes from \tr{Fd} \tr{fd}, and returns the result as a string
1884 paired with the number of bytes actually read.
1886 The operation may fail with:
1890 End of file has been reached.
1891 \item[\tr{SystemError}]
1892 Various other causes.
1896 fdWrite :: Fd -> String -> IO ByteCount
1899 \tr{fdWrite fd s} calls \tr{write} to write
1900 the string \tr{s} to \tr{Fd} \tr{fd} as a
1901 contiguous sequence of bytes. It returns the number of bytes successfully
1905 queryFdOption :: FdOption -> Fd -> IO Bool
1908 \tr{getFdOption opt fd} calls \tr{fcntl} to determine whether or
1909 not the flag associated with \tr{FdOption} \tr{opt} is set for
1913 setFdOption :: Fd -> FdOption -> Bool -> IO ()
1916 \tr{setFdOption fd opt val} calls \tr{fcntl} to set the flag
1917 associated with \tr{FdOption} \tr{opt} on \tr{Fd} \tr{fd} to
1921 getLock :: Fd -> FileLock -> IO (Maybe (ProcessID, FileLock))
1924 \tr{getLock fd lock} calls \tr{fcntl} to get the first \tr{FileLock}
1925 for \tr{Fd} \tr{fd} which blocks the \tr{FileLock} \tr{lock}. If
1926 no such \tr{FileLock} exists, \tr{getLock} returns \tr{Nothing}.
1927 Otherwise, it returns \tr{Just (pid, block)}, where \tr{block} is the
1928 blocking \tr{FileLock} and \tr{pid} is the \tr{ProcessID} of the
1929 process holding the blocking \tr{FileLock}.
1933 setLock :: Fd -> FileLock -> IO ()
1936 \tr{setLock fd lock} calls \tr{fcntl} with \tr{F_SETLK} to set or
1937 clear a lock segment for \tr{Fd} \tr{fd} as indicated by the
1938 \tr{FileLock} \tr{lock}. \tr{setLock} does not block, but fails with
1939 \tr{SystemError} if the request cannot be satisfied immediately.
1942 waitToSetLock :: Fd -> FileLock -> IO ()
1945 \tr{waitToSetLock fd lock} calls \tr{fcntl} with \tr{F_SETLKW} to set
1946 or clear a lock segment for \tr{Fd} \tr{fd} as indicated by the
1947 \tr{FileLock} \tr{lock}. If the request cannot be satisfied
1948 immediately, \tr{waitToSetLock} blocks until the request can be
1953 fdSeek :: Fd -> SeekMode -> FileOffset -> IO FileOffset
1956 \tr{fdSeek fd whence offset} calls \tr{lseek} to position the
1957 \tr{Fd} \tr{fd} at the given \tr{offset} from the starting location
1958 indicated by \tr{whence}. It returns the resulting offset from the
1959 start of the file in bytes.
1961 \subsubsection[Device Specific Functions]{Posix, Device- and Class-Specific Functions}
1962 \index{Posix, device and class-specific functions}
1965 terminalMode :: TerminalMode -> TerminalAttributes -> Bool
1966 withMode :: TerminalAttributes -> TerminalMode -> TerminalAttributes
1967 withoutMode :: TerminalAttributes -> TerminalMode -> TerminalAttributes
1969 bitsPerByte :: TerminalAttributes -> Int
1970 withBits :: TerminalAttributes -> Int -> TerminalAttributes
1972 controlChar :: TerminalAttributes -> ControlCharacter -> Maybe Char
1973 withCC :: TerminalAttributes
1974 -> (ControlCharacter, Char)
1975 -> TerminalAttributes
1976 withoutCC :: TerminalAttributes
1978 -> TerminalAttributes
1980 inputTime :: TerminalAttributes -> Int
1981 withTime :: TerminalAttributes -> Int -> TerminalAttributes
1983 minInput :: TerminalAttributes -> Int
1984 withMinInput :: TerminalAttributes -> Int -> TerminalAttributes
1986 inputSpeed :: TerminalAttributes -> BaudRate
1987 withInputSpeed :: TerminalAttributes -> BaudRate -> TerminalAttributes
1989 outputSpeed :: TerminalAttributes -> BaudRate
1990 withOutputSpeed :: TerminalAttributes -> BaudRate -> TerminalAttributes
1992 getTerminalAttributes :: Fd -> IO TerminalAttributes
1995 \tr{getTerminalAttributes fd} calls \tr{tcgetattr} to obtain
1996 the \tr{TerminalAttributes} associated with \tr{Fd} \tr{fd}.
1999 setTerminalAttributes :: Fd
2000 -> TerminalAttributes
2005 \tr{setTerminalAttributes fd attr ts} calls \tr{tcsetattr} to change
2006 the \tr{TerminalAttributes} associated with \tr{Fd} \tr{fd} to
2007 \tr{attr}, when the terminal is in the state indicated by \tr{ts}.
2010 sendBreak :: Fd -> Int -> IO ()
2013 \tr{sendBreak fd duration} calls \tr{tcsendbreak} to transmit a
2014 continuous stream of zero-valued bits on \tr{Fd} \tr{fd} for the
2015 specified implementation-dependent \tr{duration}.
2018 drainOutput :: Fd -> IO ()
2021 \tr{drainOutput fd} calls \tr{tcdrain} to block until all output
2022 written to \tr{Fd} \tr{fd} has been transmitted.
2025 discardData :: Fd -> QueueSelector -> IO ()
2028 \tr{discardData fd queues} calls \tr{tcflush} to discard
2029 pending input and/or output for \tr{Fd} \tr{fd},
2030 as indicated by the \tr{QueueSelector} \tr{queues}.
2033 controlFlow :: Fd -> FlowAction -> IO ()
2036 \tr{controlFlow fd action} calls \tr{tcflow} to control the
2037 flow of data on \tr{Fd} \tr{fd}, as indicated by
2041 getTerminalProcessGroupID :: Fd -> IO ProcessGroupID
2044 \tr{getTerminalProcessGroupID fd} calls \tr{tcgetpgrp} to
2045 obtain the \tr{ProcessGroupID} of the foreground process group
2046 associated with the terminal attached to \tr{Fd} \tr{fd}.
2049 setTerminalProcessGroupID :: Fd -> ProcessGroupID -> IO ()
2052 \tr{setTerminalProcessGroupID fd pgid} calls \tr{tcsetpgrp} to
2053 set the \tr{ProcessGroupID} of the foreground process group
2054 associated with the terminal attached to \tr{Fd}
2055 \tr{fd} to \tr{pgid}.
2057 \subsubsection[System Database]{Posix System Databases}
2058 \index{Posix, system databases}
2061 groupName :: GroupEntry -> String
2062 groupID :: GroupEntry -> GroupID
2063 groupMembers :: GroupEntry -> [String]
2065 getGroupEntryForID :: GroupID -> IO GroupEntry
2068 \tr{getGroupEntryForID gid} calls \tr{getgrgid} to obtain
2069 the \tr{GroupEntry} information associated with \tr{GroupID}
2072 The operation may fail with:
2075 \item[\tr{NoSuchThing}]
2076 There is no group entry for the GroupID.
2080 getGroupEntryForName :: String -> IO GroupEntry
2083 \tr{getGroupEntryForName name} calls \tr{getgrnam} to obtain
2084 the \tr{GroupEntry} information associated with the group called
2087 The operation may fail with:
2090 \item[\tr{NoSuchThing}]
2091 There is no group entry for the name.
2095 userName :: UserEntry -> String
2096 userID :: UserEntry -> UserID
2097 userGroupID :: UserEntry -> GroupID
2098 homeDirectory :: UserEntry -> String
2099 userShell :: UserEntry -> String
2101 getUserEntryForID :: UserID -> IO UserEntry
2104 \tr{getUserEntryForID gid} calls \tr{getpwuid} to obtain
2105 the \tr{UserEntry} information associated with \tr{UserID}
2107 The operation may fail with:
2110 \item[\tr{NoSuchThing}]
2111 There is no user entry for the UserID.
2115 getUserEntryForName :: String -> IO UserEntry
2118 \tr{getUserEntryForName name} calls \tr{getpwnam} to obtain
2119 the \tr{UserEntry} information associated with the user login
2122 The operation may fail with:
2125 \item[\tr{NoSuchThing}]
2126 There is no user entry for the name.
2129 \subsubsection[Error reporting and handling]{POSIX Errors}
2130 \index{Posix, errors}
2133 getErrorCode :: IO ErrorCode
2136 \tr{getErrorCode} returns the current value of the external
2137 variable \tr{errno}. It never fails.
2140 setErrorCode :: ErrorCode -> IO ()
2143 \tr{setErrorCode err} sets the external
2144 variable \tr{errno} to \tr{err}. It never fails.
2147 noError :: ErrorCode
2150 argumentListTooLong, e2BIG :: ErrorCode
2151 badFd, eBADF :: ErrorCode
2152 brokenPipe, ePIPE :: ErrorCode
2153 directoryNotEmpty, eNOTEMPTY :: ErrorCode
2154 execFormatError, eNOEXEC :: ErrorCode
2155 fileAlreadyExists, eEXIST :: ErrorCode
2156 fileTooLarge, eFBIG :: ErrorCode
2157 filenameTooLong, eNAMETOOLONG :: ErrorCode
2158 improperLink, eXDEV :: ErrorCode
2159 inappropriateIOControlOperation, eNOTTY :: ErrorCode
2160 inputOutputError, eIO :: ErrorCode
2161 interruptedOperation, eINTR :: ErrorCode
2162 invalidArgument, eINVAL :: ErrorCode
2163 invalidSeek, eSPIPE :: ErrorCode
2164 isADirectory, eISDIR :: ErrorCode
2165 noChildProcess, eCHILD :: ErrorCode
2166 noLocksAvailable, eNOLCK :: ErrorCode
2167 noSpaceLeftOnDevice, eNOSPC :: ErrorCode
2168 noSuchOperationOnDevice, eNODEV :: ErrorCode
2169 noSuchDeviceOrAddress, eNXIO :: ErrorCode
2170 noSuchFileOrDirectory, eNOENT :: ErrorCode
2171 noSuchProcess, eSRCH :: ErrorCode
2172 notADirectory, eNOTDIR :: ErrorCode
2173 notEnoughMemory, eNOMEM :: ErrorCode
2174 operationNotImplemented, eNOSYS :: ErrorCode
2175 operationNotPermitted, ePERM :: ErrorCode
2176 permissionDenied, eACCES :: ErrorCode
2177 readOnlyFileSystem, eROFS :: ErrorCode
2178 resourceBusy, eBUSY :: ErrorCode
2179 resourceDeadlockAvoided, eDEADLK :: ErrorCode
2180 resourceTemporarilyUnavailable, eAGAIN :: ErrorCode
2181 tooManyLinks, eMLINK :: ErrorCode
2182 tooManyOpenFiles, eMFILE :: ErrorCode
2183 tooManyOpenFilesInSystem, eNFILE :: ErrorCode
2187 %************************************************************************
2189 \subsection[HBC-library]{The HBC system library}
2190 \index{HBC system library}
2191 \index{system library, HBC}
2193 %************************************************************************
2195 This documentation is stolen directly from the HBC distribution. The
2196 modules that GHC does not support (because they require HBC-specific
2197 extensions) are omitted.
2201 \index{Either module (HBC library)}%
2202 A binary sum data type:
2204 data Either a b = Left a | Right b
2206 The constructor \tr{Left} is typically used for errors; it can be
2207 renamed to \tr{Wrong} on import.
2210 \index{Maybe module (HBC library)}%
2211 A type for failure or success:
2213 data Maybe a = Nothing | Just a
2214 thenM :: Maybe a -> (a -> Maybe b) -> Maybe b
2215 -- apply a function that may fail
2219 \index{Option module (HBC library)}%
2220 An alias for \tr{Maybe}:
2222 data Option a = None | Some a
2223 thenO :: Option a -> (a -> Option b) -> Option b
2226 \item[\tr{ListUtil}:]
2227 \index{ListUtil module (HBC library)}%
2228 Various useful functions involving lists that are missing from the
2231 assoc :: (Eq c) => (a -> b) -> b -> [(c, a)] -> c -> b
2232 -- assoc f d l k looks for k in the association list l, if it
2233 -- is found f is applied to the value, otherwise d is returned.
2234 concatMap :: (a -> [b]) -> [a] -> [b]
2235 -- flattening map (LML's concmap)
2236 unfoldr :: (a -> (b, a)) -> (a -> Bool) -> a -> [b]
2237 -- unfoldr f p x repeatedly applies f to x until (p x) holds.
2238 -- (f x) should give a list element and a new x.
2239 mapAccuml :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
2240 -- mapAccuml f s l maps f over l, but also threads the state s
2241 -- through (LML's mapstate).
2242 union :: (Eq a) => [a] -> [a] -> [a]
2243 -- union of two lists
2244 intersection :: (Eq a) => [a] -> [a] -> [a]
2245 -- intersection of two lists
2246 chopList :: ([a] -> (b, [a])) -> [a] -> [b]
2248 assocDef :: (Eq a) => [(a, b)] -> b -> a -> b
2250 lookup :: (Eq a) => [(a, b)] -> a -> Option b
2251 -- lookup l k looks for the key k in the association list l
2252 -- and returns an optional value
2253 tails :: [a] -> [[a]]
2254 -- return all the tails of a list
2255 rept :: (Integral a) => a -> b -> [b]
2256 -- repeat a value a number of times
2257 groupEq :: (a->a->Bool) -> [a] -> [[a]]
2258 -- group list elements according to an equality predicate
2259 group :: (Eq a) => [a] -> [[a]]
2260 -- group according to} ==
2261 readListLazily :: (Text a) => String -> [a]
2262 -- read a list in a lazy fashion
2266 \index{Pretty module (HBC library)}%
2267 John Hughes's pretty printing library.
2269 type Context = (Bool, Int, Int, Int)
2270 type IText = Context -> [String]
2271 text :: String -> IText -- just text
2272 (~.) :: IText -> IText -> IText -- horizontal composition
2273 (^.) :: IText -> IText -> IText -- vertical composition
2274 separate :: [IText] -> IText -- separate by spaces
2275 nest :: Int -> IText -> IText -- indent
2276 pretty :: Int -> Int -> IText -> String -- format it
2280 \index{QSort module (HBC library)}%
2281 A sort function using quicksort.
2283 sortLe :: (a -> a -> Bool) -> [a] -> [a]
2284 -- sort le l sorts l with le as less than predicate
2285 sort :: (Ord a) => [a] -> [a]
2286 -- sort l sorts l using the Ord class
2290 \index{Random module (HBC library)}%
2293 randomInts :: Int -> Int -> [Int]
2294 -- given two seeds gives a list of random Int
2295 randomDoubles :: Int -> Int -> [Double]
2296 -- random Double with uniform distribution in (0,1)
2297 normalRandomDoubles :: Int -> Int -> [Double]
2298 -- random Double with normal distribution, mean 0, variance 1
2302 Simple tracing. (Note: This comes with GHC anyway.)
2304 trace :: String -> a -> a -- trace x y prints x and returns y
2307 \item[\tr{Miranda}:]
2308 \index{Miranda module (HBC library)}%
2309 Functions found in the Miranda library.
2310 (Note: Miranda is a registered trade mark of Research Software Ltd.)
2313 \index{Word module (HBC library)}
2314 Bit manipulation. (GHC doesn't implement absolutely all of this.
2315 And don't count on @Word@ being 32 bits on a Alpha...)
2318 bitAnd :: a -> a -> a -- bitwise and
2319 bitOr :: a -> a -> a -- bitwise or
2320 bitXor :: a -> a -> a -- bitwise xor
2321 bitCompl :: a -> a -- bitwise negation
2322 bitRsh :: a -> Int -> a -- bitwise right shift
2323 bitLsh :: a -> Int -> a -- bitwise left shift
2324 bitSwap :: a -> a -- swap word halves
2325 bit0 :: a -- word with least significant bit set
2326 bitSize :: a -> Int -- number of bits in a word
2328 data Byte -- 8 bit quantity
2329 data Short -- 16 bit quantity
2330 data Word -- 32 bit quantity
2332 instance Bits Byte, Bits Short, Bits Word
2333 instance Eq Byte, Eq Short, Eq Word
2334 instance Ord Byte, Ord Short, Ord Word
2335 instance Text Byte, Text Short, Text Word
2336 instance Num Byte, Num Short, Num Word
2337 wordToShorts :: Word -> [Short] -- convert a Word to two Short
2338 wordToBytes :: Word -> [Byte] -- convert a Word to four Byte
2339 bytesToString :: [Byte] -> String -- convert a list of Byte to a String (bit by bit)
2340 wordToInt :: Word -> Int -- convert a Word to Int
2341 shortToInt :: Short -> Int -- convert a Short to Int
2342 byteToInt :: Byte -> Int -- convert a Byte to Int
2345 \item[\tr{TimeUtil}:]
2346 \index{Time module (HBC library)}%
2347 Manipulate time values (a Double with seconds since 1970).
2348 [7/97 -- this lib has been more or less superceeded by the standard Time
2352 -- year mon day hour min sec dec-sec weekday
2353 data Time = Time Int Int Int Int Int Int Double Int
2354 dblToTime :: Double -> Time -- convert a Double to a Time
2355 timeToDbl :: Time -> Double -- convert a Time to a Double
2356 timeToString :: Time -> String -- convert a Time to a readable String
2360 \index{Hash module (HBC library)}%
2363 class Hashable a where
2364 hash :: a -> Int -- hash a value, return an Int
2365 -- instances for all Prelude types
2366 hashToMax :: (Hashable a) => Int -> a -> Int -- hash into interval [0..x-1]
2369 \item[\tr{NameSupply}:]
2370 \index{NameSupply module (HBC library)}%
2371 Functions to generate unique names (Int).
2374 initialNameSupply :: NameSupply
2375 -- The initial name supply (may be different every
2376 -- time the program is run.
2377 splitNameSupply :: NameSupply -> (NameSupply,NameSupply)
2378 -- split the namesupply into two
2379 getName :: NameSupply -> Name
2380 -- get the name associated with a name supply
2384 \index{Parse module (HBC library)}%
2385 Higher order functions to build parsers. With a little care these
2386 combinators can be used to build efficient parsers with good error
2389 infixr 8 +.+ , ..+ , +..
2390 infix 6 `act` , >>> , `into` , .>
2391 infixr 4 ||| , ||! , |!!
2392 data ParseResult a b
2393 type Parser a b = a -> Int -> ParseResult a b
2394 (|||) :: Parser a b -> Parser a b -> Parser a b
2396 (||!) :: Parser a b -> Parser a b -> Parser a b
2397 -- Alternative, but with committed choice
2398 (|!!) :: Parser a b -> Parser a b -> Parser a b
2399 -- Alternative, but with committed choice
2400 (+.+) :: Parser a b -> Parser a c -> Parser a (b,c)
2402 (..+) :: Parser a b -> Parser a c -> Parser a c
2403 -- Sequence, throw away first part
2404 (+..) :: Parser a b -> Parser a c -> Parser a b
2405 -- Sequence, throw away second part
2406 act :: Parser a b -> (b->c) -> Parser a c
2408 (>>>) :: Parser a (b,c) -> (b->c->d) -> Parser a d
2409 -- Action on two items
2410 (.>) :: Parser a b -> c -> Parse a c
2411 -- Action ignoring value
2412 into :: Parser a b -> (b -> Parser a c) -> Parser a c
2413 -- Use a produced value in a parser.
2414 succeed b :: Parser a b
2415 -- Always succeeds without consuming a token
2418 many :: Parser a b -> Parser a [b]
2420 many1 :: Parser a b -> Parser a [b]
2422 count :: Parser a b -> Int -> Parser a [b]
2423 -- Parse an exact number of items
2424 sepBy1 :: Parser a b -> Parser a c -> Parser a [b]
2425 -- Non-empty sequence of items separated by something
2426 sepBy :: Parser a b -> Parser a c -> Parser a [b]
2427 -- Sequence of items separated by something
2428 lit :: (Eq a, Text a) => a -> Parser [a] a
2429 -- Recognise a literal token from a list of tokens
2430 litp :: String -> (a->Bool) -> Parser [a] a
2431 -- Recognise a token with a predicate.
2432 -- The string is a description for error messages.
2433 testp :: String -> (a -> Bool) -> (Parser b a) -> Parser b a
2434 -- Test a semantic value.
2435 token :: (a -> Either String (b, a)) -> Parser a b
2436 -- General token recogniser.
2437 parse :: Parser a b -> a -> Either ([String], a) [(b, a)]
2438 -- Do a parse. Return either error (possible tokens and rest
2439 -- of tokens) or all possible parses.
2440 sParse :: (Text a) => (Parser [a] b) -> [a] -> Either String b
2441 -- Simple parse. Return error message or result.
2444 %%%simpleLex :: String -> [String] -- A simple (but useful) lexical analyzer
2447 \index{Native module (HBC library)}%
2448 Functions to convert the primitive types \tr{Int}, \tr{Float}, and \tr{Double} to
2449 their native representation as a list of bytes (\tr{Char}). If such a list
2450 is read/written to a file it will have the same format as when, e.g.,
2451 C read/writes the same kind of data.
2453 type Bytes = [Char] -- A byte stream is just a list of characters
2455 class Native a where
2456 showBytes :: a -> Bytes -> Bytes
2457 -- prepend the representation of an item the a byte stream
2458 listShowBytes :: [a] -> Bytes -> Bytes
2459 -- prepend the representation of a list of items to a stream
2460 -- (may be more efficient than repeating showBytes).
2461 readBytes :: Bytes -> Maybe (a, Bytes)
2462 -- get an item from the stream and return the rest,
2463 -- or fail if the stream is to short.
2464 listReadBytes :: Int -> Bytes -> Maybe ([a], Bytes)
2465 -- read n items from a stream.
2468 instance Native Float
2469 instance Native Double
2470 instance (Native a, Native b) => Native (a,b)
2471 -- juxtaposition of the two items
2472 instance (Native a, Native b, Native c) => Native (a, b, c)
2473 -- juxtaposition of the three items
2474 instance (Native a) => Native [a]
2475 -- an item count in an Int followed by the items
2477 shortIntToBytes :: Int -> Bytes -> Bytes
2478 -- Convert an Int to what corresponds to a short in C.
2479 bytesToShortInt :: Bytes -> Maybe (Int, Bytes)
2480 -- Get a short from a byte stream and convert to an Int.
2482 showB :: (Native a) => a -> Bytes -- Simple interface to showBytes.
2483 readB :: (Native a) => Bytes -> a -- Simple interface to readBytes.
2487 \index{Number module (HBC library)}%
2488 Simple numbers that belong to all numeric classes and behave like
2489 a naive user would expect (except that printing is still ugly).
2490 (NB: GHC does not provide a magic way to use \tr{Numbers} everywhere,
2491 but you should be able to do it with normal \tr{import}ing and
2494 data Number -- The type itself.
2495 instance ... -- All reasonable instances.
2496 isInteger :: Number -> Bool -- Test if a Number is an integer.