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 data ChannelOption = AppendOnWrite
940 data ControlCharacter = EndOfFile
952 type FileLock = (LockRequest, SeekMode, FileOffset, FileOffset)
953 -- whence start length
955 data FlowAction = SuspendOutput | RestartOutput | TransmitStop | TransmitStart
957 data Handler = Default | Ignore | Catch (IO ())
959 data LockRequest = ReadLock | WriteLock | Unlock
962 data OpenMode = ReadOnly | WriteOnly | ReadWrite
964 data PathVar = LinkLimit
970 | SetOwnerAndGroupIsRestricted
971 | FileNamesAreNotTruncated
973 data QueueSelector = InputQueue | OutputQueue | BothQueues
977 data SysVar = ArgumentLimit
986 data TerminalMode = InterruptOnBreak -- BRKINT
988 | IgnoreBreak -- IGNBRK
990 | IgnoreParityErrors -- IGNPAR
992 | CheckParity -- INPCK
993 | StripHighBit -- ISTRIP
994 | StartStopInput -- IXOFF
995 | StartStopOutput -- IXON
996 | MarkParityErrors -- PARMRK
997 | ProcessOutput -- OPOST
998 | LocalMode -- CLOCAL
999 | ReadEnable -- CREAD
1000 | TwoStopBits -- CSTOPB
1001 | HangupOnClose -- HUPCL
1002 | EnableParity -- PARENB
1003 | OddParity -- PARODD
1004 | EnableEcho -- ECHO
1005 | EchoErase -- ECHOE
1008 | ProcessInput -- ICANON
1009 | ExtendedFunctions -- IEXTEN
1010 | KeyboardInterrupts -- ISIG
1011 | NoFlushOnInterrupt -- NOFLSH
1012 | BackgroundWriteInterrupt -- TOSTOP
1014 data TerminalState = Immediately | WhenDrained | WhenFlushed
1016 data ProcessStatus = Exited ExitCode
1022 \subsubsection[Process Primitives]{Posix Process Primitives}
1025 forkProcess :: IO (Maybe ProcessID)
1028 \tr{forkProcess} calls \tr{fork}, returning
1029 \tr{Just pid} to the parent, where \tr{pid} is the
1030 ProcessID of the child, and returning \tr{Nothing} to the
1034 executeFile :: FilePath -- Command
1035 -> Bool -- Search PATH?
1036 -> [String] -- Arguments
1037 -> Maybe [(String, String)] -- Environment
1041 \tr{executeFile cmd args env} calls one of the
1042 \tr{execv*} family, depending on whether or not the current
1043 PATH is to be searched for the command, and whether or not an
1044 environment is provided to supersede the process's current
1045 environment. The basename (leading directory names suppressed) of
1046 the command is passed to \tr{execv*} as \tr{arg[0]};
1047 the argument list passed to \tr{executeFile} therefore begins
1051 Search PATH? Supersede environ? Call
1052 ~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ~~~~~~~
1059 Note that \tr{execvpe} is not provided by the POSIX standard, and must
1060 be written by hand. Care must be taken to ensure that the search path
1061 is extracted from the original environment, and not from the
1062 environment to be passed on to the new image.
1064 A successful \tr{executeFile} overlays the current process image with
1065 a new one, so it only returns on failure.
1067 runProcess :: FilePath -- Command
1068 -> [String] -- Arguments
1069 -> Maybe [(String, String)] -- Environment (Nothing -> Inherited)
1070 -> Maybe FilePath -- Working directory (Nothing -> inherited)
1071 -> Maybe Handle -- stdin (Nothing -> inherited)
1072 -> Maybe Handle -- stdout (Nothing -> inherited)
1073 -> Maybe Handle -- stderr (Nothing -> inherited)
1077 \tr{runProcess} is our candidate for the high-level OS-independent
1080 \tr{runProcess cmd args env wd inhdl outhdl errhdl} runs \tr{cmd}
1081 (searching the current \tr{PATH}) with arguments \tr{args}. If
1082 \tr{env} is \tr{Just pairs}, the command is executed with the
1083 environment specified by \tr{pairs} of variables and values;
1084 otherwise, the command is executed with the current environment. If
1085 \tr{wd} is \tr{Just dir}, the command is executed with working
1086 directory \tr{dir}; otherwise, the command is executed in the current
1087 working directory. If \tr{{in,out,err}hdl} is \tr{Just handle}, the
1088 command is executed with the \tr{Channel} for \tr{std{in,out,err}}
1089 attached to the specified \tr{handle}; otherwise, the \tr{Channel} for
1090 \tr{std{in,out,err}} is left unchanged.
1093 getProcessStatus :: Bool -- Block?
1094 -> Bool -- Stopped processes?
1096 -> IO (Maybe ProcessStatus)
1099 \tr{getProcessStatus blk stopped pid} calls \tr{waitpid}, returning
1100 \tr{Just tc}, the \tr{ProcessStatus} for process \tr{pid} if it is
1101 available, \tr{Nothing} otherwise. If \tr{blk} is \tr{False}, then
1102 \tr{WNOHANG} is set in the options for \tr{waitpid}, otherwise not.
1103 If \tr{stopped} is \tr{True}, then \tr{WUNTRACED} is set in the
1104 options for \tr{waitpid}, otherwise not.
1107 getGroupProcessStatus :: Bool -- Block?
1108 -> Bool -- Stopped processes?
1110 -> IO (Maybe (ProcessID, ProcessStatus))
1113 \tr{getGroupProcessStatus blk stopped pgid} calls \tr{waitpid},
1114 returning \tr{Just (pid, tc)}, the \tr{ProcessID} and
1115 \tr{ProcessStatus} for any process in group \tr{pgid} if one is
1116 available, \tr{Nothing} otherwise. If \tr{blk} is \tr{False}, then
1117 \tr{WNOHANG} is set in the options for \tr{waitpid}, otherwise not.
1118 If \tr{stopped} is \tr{True}, then \tr{WUNTRACED} is set in the
1119 options for \tr{waitpid}, otherwise not.
1122 getAnyProcessStatus :: Bool -- Block?
1123 -> Bool -- Stopped processes?
1124 -> IO (Maybe (ProcessID, ProcessStatus))
1127 \tr{getAnyProcessStatus blk stopped} calls \tr{waitpid}, returning
1128 \tr{Just (pid, tc)}, the \tr{ProcessID} and \tr{ProcessStatus} for any
1129 child process if one is available, \tr{Nothing} otherwise. If
1130 \tr{blk} is \tr{False}, then \tr{WNOHANG} is set in the options for
1131 \tr{waitpid}, otherwise not. If \tr{stopped} is \tr{True}, then
1132 \tr{WUNTRACED} is set in the options for \tr{waitpid}, otherwise not.
1135 exitImmediately :: ExitCode -> IO ()
1138 \tr{exitImmediately status} calls \tr{_exit} to terminate the process
1139 with the indicated exit \tr{status}.
1140 The operation never returns.
1143 getEnvironment :: IO [(String, String)]
1146 \tr{getEnvironment} parses the environment variable mapping provided by
1147 \tr{environ}, returning \tr{(variable, value)} pairs.
1148 The operation never fails.
1151 setEnvironment :: [(String, String)] -> IO ()
1154 \tr{setEnvironment} replaces the process environment with the provided
1155 mapping of \tr{(variable, value)} pairs.
1158 getEnvVar :: String -> IO String
1161 \tr{getEnvVar var} returns the value associated with variable \tr{var}
1162 in the current environment (identical functionality provided through
1163 standard Haskell library function @System.getEnv@).
1165 The operation may fail with:
1168 \item[\tr{NoSuchThing}]
1169 The variable has no mapping in the current environment.
1173 setEnvVar :: String -> String -> IO ()
1176 \tr{setEnvVar var val} sets the value associated with variable \tr{var}
1177 in the current environment to be \tr{val}. Any previous mapping is
1181 removeEnvVar :: String -> IO ()
1184 \tr{removeEnvVar var} removes any value associated with variable \tr{var}
1185 in the current environment. Deleting a variable for which there is no mapping
1186 does not generate an error.
1189 nullSignal :: Signal
1192 backgroundRead, sigTTIN :: Signal
1193 backgroundWrite, sigTTOU :: Signal
1194 continueProcess, sigCONT :: Signal
1195 floatingPointException, sigFPE :: Signal
1196 illegalInstruction, sigILL :: Signal
1197 internalAbort, sigABRT :: Signal
1198 keyboardSignal, sigINT :: Signal
1199 keyboardStop, sigTSTP :: Signal
1200 keyboardTermination, sigQUIT :: Signal
1201 killProcess, sigKILL :: Signal
1202 lostConnection, sigHUP :: Signal
1203 openEndedPipe, sigPIPE :: Signal
1204 processStatusChanged, sigCHLD :: Signal
1205 realTimeAlarm, sigALRM :: Signal
1206 segmentationViolation, sigSEGV :: Signal
1207 softwareStop, sigSTOP :: Signal
1208 softwareTermination, sigTERM :: Signal
1209 userDefinedSignal1, sigUSR1 :: Signal
1210 userDefinedSignal2, sigUSR2 :: Signal
1212 signalProcess :: Signal -> ProcessID -> IO ()
1215 \tr{signalProcess int pid} calls \tr{kill} to signal
1216 process \tr{pid} with interrupt signal \tr{int}.
1219 raiseSignal :: Signal -> IO ()
1222 \tr{raiseSignal int} calls \tr{kill} to signal the current process
1223 with interrupt signal \tr{int}.
1226 signalProcessGroup :: Signal -> ProcessGroupID -> IO ()
1229 \tr{signalProcessGroup int pgid} calls \tr{kill} to signal
1230 all processes in group \tr{pgid} with interrupt signal \tr{int}.
1233 setStoppedChildFlag :: Bool -> IO Bool
1236 \tr{setStoppedChildFlag bool} sets a flag which controls whether or
1237 not the \tr{NOCLDSTOP} option will be used the next time a signal
1238 handler is installed for \tr{SIGCHLD}. If \tr{bool} is \tr{True} (the
1239 default), \tr{NOCLDSTOP} will not be used; otherwise it will be. The
1240 operation never fails.
1243 queryStoppedChildFlag :: IO Bool
1246 \tr{queryStoppedChildFlag} queries the flag which
1247 controls whether or not the \tr{NOCLDSTOP} option will be used
1248 the next time a signal handler is installed for \tr{SIGCHLD}.
1249 If \tr{NOCLDSTOP} will be used, it returns \tr{False};
1250 otherwise (the default) it returns \tr{True}.
1251 The operation never fails.
1254 emptySignalSet :: SignalSet
1255 fullSignalSet :: SignalSet
1256 addSignal :: Signal -> SignalSet -> SignalSet
1257 deleteSignal :: Signal -> SignalSet -> SignalSet
1258 inSignalSet :: Signal -> SignalSet -> Bool
1260 installHandler :: Signal
1262 -> Maybe SignalSet -- other signals to block
1263 -> IO Handler -- old handler
1266 \tr{installHandler int handler iset} calls \tr{sigaction} to install
1267 an interrupt handler for signal \tr{int}. If \tr{handler} is
1268 \tr{Default}, \tr{SIG_DFL} is installed; if \tr{handler} is
1269 \tr{Ignore}, \tr{SIG_IGN} is installed; if \tr{handler} is
1270 \tr{Catch action}, a handler is installed which will invoke \tr{action} as a
1271 replacement for \tr{main}. If \tr{iset} is \tr{Just s}, then the
1272 \tr{sa_mask} of the \tr{sigaction} structure is set to \tr{s};
1273 otherwise it is cleared. The previously installed signal handler for
1274 \tr{int} is returned.
1277 getSignalMask :: IO SignalSet
1280 \tr{getSignalMask} calls \tr{sigprocmask} to determine the
1281 set of interrupts which are currently being blocked.
1284 setSignalMask :: SignalSet -> IO SignalSet
1287 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1288 \tr{SIG_SETMASK} to block all interrupts in \tr{mask}. The
1289 previous set of blocked interrupts is returned.
1292 blockSignals :: SignalSet -> IO SignalSet
1295 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1296 \tr{SIG_BLOCK} to add all interrupts in \tr{mask} to the
1297 set of blocked interrupts. The previous set of blocked interrupts is returned.
1300 unBlockSignals :: SignalSet -> IO SignalSet
1303 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1304 \tr{SIG_UNBLOCK} to remove all interrupts in \tr{mask} from the
1305 set of blocked interrupts. The previous set of blocked interrupts is returned.
1308 getPendingSignals :: IO SignalSet
1311 \tr{getPendingSignals} calls \tr{sigpending} to obtain
1312 the set of interrupts which have been received but are currently blocked.
1315 awaitSignal :: Maybe SignalSet -> IO ()
1318 \tr{awaitSignal iset} suspends execution until an interrupt is received.
1319 If \tr{iset} is \tr{Just s}, \tr{awaitSignal} calls
1320 \tr{sigsuspend}, installing \tr{s} as the new signal mask before
1321 suspending execution; otherwise, it calls \tr{pause}. If successful,
1322 \tr{awaitSignal} does not return.
1325 scheduleAlarm :: Int -> IO Int
1328 \tr{scheduleAlarm i} calls \tr{alarm} to schedule a real time
1329 alarm at least \tr{i} seconds in the future.
1332 sleep :: Int -> IO ()
1335 \tr{sleep i} calls \tr{sleep} to suspend execution of the
1336 program until at least \tr{i} seconds have elapsed or a signal is
1339 \subsubsection[Process Environment]{Posix Process Environment}
1340 \index{Posix, process environment}
1343 getProcessID :: IO ProcessID
1346 \tr{getProcessID} calls \tr{getpid} to obtain the \tr{ProcessID} for
1347 the current process.
1350 getParentProcessID :: IO ProcessID
1353 \tr{getProcessID} calls \tr{getppid} to obtain the \tr{ProcessID} for
1354 the parent of the current process.
1357 getRealUserID :: IO UserID
1360 \tr{getRealUserID} calls \tr{getuid} to obtain the real \tr{UserID}
1361 associated with the current process.
1364 getEffectiveUserID :: IO UserID
1367 \tr{getRealUserID} calls \tr{geteuid} to obtain the effective
1368 \tr{UserID} associated with the current process.
1371 setUserID :: UserID -> IO ()
1374 \tr{setUserID uid} calls \tr{setuid} to set the real, effective, and
1375 saved set-user-id associated with the current process to \tr{uid}.
1378 getLoginName :: IO String
1381 \tr{getLoginName} calls \tr{getlogin} to obtain the login name
1382 associated with the current process.
1385 getRealGroupID :: IO GroupID
1388 \tr{getRealGroupID} calls \tr{getgid} to obtain the real \tr{GroupID}
1389 associated with the current process.
1392 getEffectiveGroupID :: IO GroupID
1395 \tr{getEffectiveGroupID} calls \tr{getegid} to obtain the effective
1396 \tr{GroupID} associated with the current process.
1399 setGroupID :: GroupID -> IO ()
1402 \tr{setGroupID gid} calls \tr{setgid} to set the real, effective, and
1403 saved set-group-id associated with the current process to \tr{gid}.
1406 getGroups :: IO [GroupID]
1409 \tr{getGroups} calls \tr{getgroups} to obtain the list of
1410 supplementary \tr{GroupID}s associated with the current process.
1413 getEffectiveUserName :: IO String
1416 \tr{getEffectiveUserName} calls \tr{cuserid} to obtain a name
1417 associated with the effective \tr{UserID} of the process.
1420 getProcessGroupID :: IO ProcessGroupID
1423 \tr{getProcessGroupID} calls \tr{getpgrp} to obtain the
1424 \tr{ProcessGroupID} for the current process.
1427 createProcessGroup :: ProcessID -> IO ProcessGroupID
1430 \tr{createProcessGroup pid} calls \tr{setpgid} to make
1431 process \tr{pid} a new process group leader.
1434 joinProcessGroup :: ProcessGroupID -> IO ProcessGroupID
1437 \tr{joinProcessGroup pgid} calls \tr{setpgid} to set the
1438 \tr{ProcessGroupID} of the current process to \tr{pgid}.
1441 setProcessGroupID :: ProcessID -> ProcessGroupID -> IO ()
1444 \tr{setProcessGroupID pid pgid} calls \tr{setpgid} to set the
1445 \tr{ProcessGroupID} for process \tr{pid} to \tr{pgid}.
1448 createSession :: IO ProcessGroupID
1451 \tr{createSession} calls \tr{setsid} to create a new session
1452 with the current process as session leader.
1455 systemName :: SystemID -> String
1456 nodeName :: SystemID -> String
1457 release :: SystemID -> String
1458 version :: SystemID -> String
1459 machine :: SystemID -> String
1461 getSystemID :: IO SystemID
1464 \tr{getSystemID} calls \tr{uname} to obtain information
1465 about the current operating system.
1468 > epochTime :: IO EpochTime
1471 \tr{epochTime} calls \tr{time} to obtain the number of
1472 seconds that have elapsed since the epoch (Jan 01 00:00:00 GMT 1970).
1475 elapsedTime :: ProcessTimes -> ClockTick
1476 userTime :: ProcessTimes -> ClockTick
1477 systemTime :: ProcessTimes -> ClockTick
1478 childUserTime :: ProcessTimes -> ClockTick
1479 childSystemTime :: ProcessTimes -> ClockTick
1481 getProcessTimes :: IO ProcessTimes
1484 \tr{getProcessTimes} calls \tr{times} to obtain time-accounting
1485 information for the current process and its children.
1488 getControllingTerminalName :: IO FilePath
1491 \tr{getControllingTerminalName} calls \tr{ctermid} to obtain
1492 a name associated with the controlling terminal for the process. If a
1493 controlling terminal exists,
1494 \tr{getControllingTerminalName} returns the name of the
1495 controlling terminal.
1497 The operation may fail with:
1500 \item[\tr{NoSuchThing}]
1501 There is no controlling terminal, or its name cannot be determined.
1502 \item[\tr{SystemError}]
1503 Various other causes.
1507 getTerminalName :: Channel -> IO FilePath
1510 \tr{getTerminalName fd} calls \tr{ttyname} to obtain a name associated
1511 with the terminal for \tr{Channel} \tr{fd}. If \tr{fd} is associated
1512 with a terminal, \tr{getTerminalName} returns the name of the
1515 The operation may fail with:
1518 \item[\tr{InappropriateType}]
1519 The channel is not associated with a terminal.
1520 \item[\tr{NoSuchThing}]
1521 The channel is associated with a terminal, but it has no name.
1522 \item[\tr{SystemError}]
1523 Various other causes.
1527 queryTerminal :: Channel -> IO Bool
1530 \tr{queryTerminal fd} calls \tr{isatty} to determine whether or
1531 not \tr{Channel} \tr{fd} is associated with a terminal.
1534 getSysVar :: SysVar -> IO Limit
1537 \tr{getSysVar var} calls \tr{sysconf} to obtain the
1538 dynamic value of the requested configurable system limit or option.
1539 For defined system limits, \tr{getSysVar} returns the associated
1540 value. For defined system options, the result of \tr{getSysVar}
1541 is undefined, but not failure.
1543 The operation may fail with:
1546 \item[\tr{NoSuchThing}]
1547 The requested system limit or option is undefined.
1550 \subsubsection[Files and Directories]{Posix operations on files and directories}
1551 \index{Posix, files and directories}
1554 openDirStream :: FilePath -> IO DirStream
1557 \tr{openDirStream dir} calls \tr{opendir} to obtain a
1558 directory stream for \tr{dir}.
1561 readDirStream :: DirStream -> IO String
1564 \tr{readDirStream dp} calls \tr{readdir} to obtain the
1565 next directory entry (\tr{struct dirent}) for the open directory
1566 stream \tr{dp}, and returns the \tr{d_name} member of that
1569 The operation may fail with:
1573 End of file has been reached.
1574 \item[\tr{SystemError}]
1575 Various other causes.
1579 rewindDirStream :: DirStream -> IO ()
1582 \tr{rewindDirStream dp} calls \tr{rewinddir} to reposition
1583 the directory stream \tr{dp} at the beginning of the directory.
1586 closeDirStream :: DirStream -> IO ()
1589 \tr{closeDirStream dp} calls \tr{closedir} to close
1590 the directory stream \tr{dp}.
1593 getWorkingDirectory :: IO FilePath
1596 \tr{getWorkingDirectory} calls \tr{getcwd} to obtain the name
1597 of the current working directory.
1600 changeWorkingDirectory :: FilePath -> IO ()
1603 \tr{changeWorkingDirectory dir} calls \tr{chdir} to change
1604 the current working directory to \tr{dir}.
1607 nullFileMode :: FileMode -- ---------
1608 ownerReadMode :: FileMode -- r--------
1609 ownerWriteMode :: FileMode -- -w-------
1610 ownerExecuteMode :: FileMode -- --x------
1611 groupReadMode :: FileMode -- ---r-----
1612 groupWriteMode :: FileMode -- ----w----
1613 groupExecuteMode :: FileMode -- -----x---
1614 otherReadMode :: FileMode -- ------r--
1615 otherWriteMode :: FileMode -- -------w-
1616 otherExecuteMode :: FileMode -- --------x
1617 setUserIDMode :: FileMode -- --S------
1618 setGroupIDMode :: FileMode -- -----S---
1620 stdFileMode :: FileMode -- rw-rw-rw-
1622 ownerModes :: FileMode -- rwx------
1623 groupModes :: FileMode -- ---rwx---
1624 otherModes :: FileMode -- ------rwx
1625 accessModes :: FileMode -- rwxrwxrwx
1627 unionFileModes :: FileMode -> FileMode -> FileMode
1628 intersectFileModes :: FileMode -> FileMode -> FileMode
1633 stdOutput :: Channel
1639 openChannel :: FilePath
1641 -> Maybe FileMode -- Just x => O_CREAT, Nothing => must exist
1645 -> Bool -- O_NONBLOCK
1650 \tr{openChannel path acc mode app excl noctty nonblock trunc} calls
1651 \tr{open} to obtain a \tr{Channel} for the file \tr{path} with access
1652 mode \tr{acc}. If \tr{mode} is \tr{Just m}, the \tr{O_CREAT} flag is
1653 set and the file's permissions will be based on \tr{m} if it does not
1654 already exist; otherwise, the \tr{O_CREAT} flag is not set. The
1655 arguments \tr{app}, \tr{excl}, \tr{noctty}, \tr{nonblock}, and
1656 \tr{trunc} control whether or not the flags \tr{O_APPEND},
1657 \tr{O_EXCL}, \tr{O_NOCTTY}, \tr{O_NONBLOCK}, and \tr{O_TRUNC} are set,
1661 createFile :: FilePath -> FileMode -> IO Channel
1664 \tr{createFile path mode} calls \tr{creat} to obtain a \tr{Channel}
1665 for file \tr{path}, which will be created with permissions based on
1666 \tr{mode} if it does not already exist.
1669 setFileCreationMask :: FileMode -> IO FileMode
1672 \tr{setFileCreationMask mode} calls \tr{umask} to set
1673 the process's file creation mask to \tr{mode}. The previous file
1674 creation mask is returned.
1677 createLink :: FilePath -> FilePath -> IO ()
1680 \tr{createLink old new} calls \tr{link} to create a
1681 new path, \tr{new}, linked to an existing file, \tr{old}.
1683 createDirectory :: FilePath -> FileMode -> IO ()
1686 \tr{createDirectory dir mode} calls \tr{mkdir} to
1687 create a new directory, \tr{dir}, with permissions based on
1691 createNamedPipe :: FilePath -> FileMode -> IO ()
1694 \tr{createNamedPipe fifo mode} calls \tr{mkfifo} to
1695 create a new named pipe, \tr{fifo}, with permissions based on
1699 removeLink :: FilePath -> IO ()
1702 \tr{removeLink path} calls \tr{unlink} to remove the link
1706 removeDirectory :: FilePath -> IO ()
1709 \tr{removeDirectory dir} calls \tr{rmdir} to remove the
1710 directory named \tr{dir}.
1713 rename :: FilePath -> FilePath -> IO ()
1716 \tr{rename old new} calls \tr{rename} to rename a
1717 file or directory from \tr{old} to \tr{new}.
1720 fileMode :: FileStatus -> FileMode
1722 fileID :: FileStatus -> FileID
1723 deviceID :: FileStatus -> DeviceID
1725 linkCount :: FileStatus -> LinkCount
1727 fileOwner :: FileStatus -> UserID
1728 fileGroup :: FileStatus -> GroupID
1729 fileSize :: FileStatus -> FileOffset
1731 accessTime :: FileStatus -> EpochTime
1732 modificationTime :: FileStatus -> EpochTime
1733 statusChangeTime :: FileStatus -> EpochTime
1735 isDirectory :: FileStatus -> Bool
1736 isCharacterDevice :: FileStatus -> Bool
1737 isBlockDevice :: FileStatus -> Bool
1738 isRegularFile :: FileStatus -> Bool
1739 isNamedPipe :: FileStatus -> Bool
1741 getFileStatus :: FilePath -> IO FileStatus
1744 \tr{getFileStatus path} calls \tr{stat} to get the
1745 \tr{FileStatus} information for the file \tr{path}.
1748 getChannelStatus :: Channel -> IO FileStatus
1751 \tr{getChannelStatus fd} calls \tr{fstat} to get the
1752 \tr{FileStatus} information for the file associated with
1753 \tr{Channel} \tr{fd}.
1756 queryAccess :: FilePath -> Bool -> Bool -> Bool -> IO Bool
1759 \tr{queryAccess path r w x} calls \tr{access} to test the access
1760 permissions for file \tr{path}. The three arguments, \tr{r}, \tr{w},
1761 and \tr{x} control whether or not \tr{access} is called with
1762 \tr{R_OK}, \tr{W_OK}, and \tr{X_OK} respectively.
1765 queryFile :: FilePath -> IO Bool
1768 \tr{queryFile path} calls \tr{access} with \tr{F_OK} to test for the
1769 existence for file \tr{path}.
1772 setFileMode :: FilePath -> FileMode -> IO ()
1775 \tr{setFileMode path mode} calls \tr{chmod} to set the
1776 permission bits associated with file \tr{path} to \tr{mode}.
1779 setOwnerAndGroup :: FilePath -> UserID -> GroupID -> IO ()
1782 \tr{setOwnerAndGroup path uid gid} calls \tr{chown} to
1783 set the \tr{UserID} and \tr{GroupID} associated with file
1784 \tr{path} to \tr{uid} and \tr{gid}, respectively.
1787 setFileTimes :: FilePath -> EpochTime -> EpochTime -> IO ()
1790 \tr{setFileTimes path atime mtime} calls \tr{utime} to
1791 set the access and modification times associated with file
1792 \tr{path} to \tr{atime} and \tr{mtime}, respectively.
1795 touchFile :: FilePath -> IO ()
1798 \tr{touchFile path} calls \tr{utime} to
1799 set the access and modification times associated with file
1800 \tr{path} to the current time.
1803 getPathVar :: PathVar -> FilePath -> IO Limit
1806 \tr{getPathVar var path} calls \tr{pathconf} to obtain the
1807 dynamic value of the requested configurable file limit or option associated
1808 with file or directory \tr{path}. For
1809 defined file limits, \tr{getPathVar} returns the associated
1810 value. For defined file options, the result of \tr{getPathVar}
1811 is undefined, but not failure.
1812 The operation may fail with:
1814 \item[\tr{NoSuchThing}]
1815 The requested file limit or option is undefined.
1816 \item[\tr{SystemError}]
1817 Various other causes.
1822 getChannelVar :: PathVar -> Channel -> IO Limit
1825 \tr{getChannelVar var fd} calls \tr{fpathconf} to obtain the
1826 dynamic value of the requested configurable file limit or option associated
1827 with the file or directory attached to the open channel \tr{fd}.
1828 For defined file limits, \tr{getChannelVar} returns the associated
1829 value. For defined file options, the result of \tr{getChannelVar}
1830 is undefined, but not failure.
1832 The operation may fail with:
1835 \item[\tr{NoSuchThing}]
1836 The requested file limit or option is undefined.
1837 \item[\tr{SystemError}]
1838 Various other causes.
1841 \subsubsection[Inut Output]{Posix Input and Output Primitives}
1842 \index{Posix, input/output}
1845 createPipe :: IO (Channel, Channel)
1848 \tr{createPipe} calls \tr{pipe} to create a pipe and returns a pair of
1849 \tr{Channels}, the first for writing and the second for reading.
1852 dupChannel :: Channel -> IO Channel
1855 \tr{dupChannel fd} calls \tr{dup} to duplicate \tr{Channel} \tr{fd} to
1856 another \tr{Channel}.
1859 dupChannelTo :: Channel -> Channel -> IO ()
1862 \tr{dupChannelTo src dst} calls \tr{dup2} to duplicate \tr{Channel}
1863 \tr{src} to \tr{Channel} \tr{dst}.
1866 closeChannel :: Channel -> IO ()
1869 \tr{closeChannel fd} calls \tr{close} to close \tr{Channel} \tr{fd}.
1872 readChannel :: Channel -> ByteCount -> IO (String, ByteCount)
1875 \tr{readChannel fd nbytes} calls \tr{read} to read at most \tr{nbytes}
1876 bytes from \tr{Channel} \tr{fd}, and returns the result as a string
1877 paired with the number of bytes actually read.
1879 The operation may fail with:
1883 End of file has been reached.
1884 \item[\tr{SystemError}]
1885 Various other causes.
1889 writeChannel :: Channel -> String -> IO ByteCount
1892 \tr{writeChannel fd s} calls \tr{write} to write
1893 the string \tr{s} to \tr{Channel} \tr{fd} as a
1894 contiguous sequence of bytes. It returns the number of bytes successfully
1898 queryChannelOption :: ChannelOption -> Channel -> IO Bool
1901 \tr{getChannelOption opt fd} calls \tr{fcntl} to determine whether or
1902 not the flag associated with \tr{ChannelOption} \tr{opt} is set for
1903 \tr{Channel} \tr{fd}.
1906 setChannelOption :: ChannelOption -> Bool -> Channel -> IO ()
1909 \tr{setChannelOption opt val fd} calls \tr{fcntl} to set the flag
1910 associated with \tr{ChannelOption} \tr{opt} on \tr{Channel} \tr{fd} to
1914 getLock :: Channel -> FileLock -> IO (Maybe (ProcessID, FileLock))
1917 \tr{getLock fd lock} calls \tr{fcntl} to get the first \tr{FileLock}
1918 for \tr{Channel} \tr{fd} which blocks the \tr{FileLock} \tr{lock}. If
1919 no such \tr{FileLock} exists, \tr{getLock} returns \tr{Nothing}.
1920 Otherwise, it returns \tr{Just (pid, block)}, where \tr{block} is the
1921 blocking \tr{FileLock} and \tr{pid} is the \tr{ProcessID} of the
1922 process holding the blocking \tr{FileLock}.
1926 setLock :: Channel -> FileLock -> IO ()
1929 \tr{setLock fd lock} calls \tr{fcntl} with \tr{F_SETLK} to set or
1930 clear a lock segment for \tr{Channel} \tr{fd} as indicated by the
1931 \tr{FileLock} \tr{lock}. \tr{setLock} does not block, but fails with
1932 \tr{SystemError} if the request cannot be satisfied immediately.
1935 waitToSetLock :: Channel -> FileLock -> IO ()
1938 \tr{waitToSetLock fd lock} calls \tr{fcntl} with \tr{F_SETLKW} to set
1939 or clear a lock segment for \tr{Channel} \tr{fd} as indicated by the
1940 \tr{FileLock} \tr{lock}. If the request cannot be satisfied
1941 immediately, \tr{waitToSetLock} blocks until the request can be
1946 seekChannel :: Channel -> SeekMode -> FileOffset -> IO FileOffset
1949 \tr{seekChannel fd whence offset} calls \tr{lseek} to position the
1950 \tr{Channel} at the given \tr{offset} from the starting location
1951 indicated by \tr{whence}. It returns the resulting offset from the
1952 start of the file in bytes.
1954 \subsubsection[Device Specific Functions]{Posix, Device- and Class-Specific Functions}
1955 \index{Posix, device and class-specific functions}
1958 terminalMode :: TerminalMode -> TerminalAttributes -> Bool
1959 withMode :: TerminalAttributes -> TerminalMode -> TerminalAttributes
1960 withoutMode :: TerminalAttributes -> TerminalMode -> TerminalAttributes
1962 bitsPerByte :: TerminalAttributes -> Int
1963 withBits :: TerminalAttributes -> Int -> TerminalAttributes
1965 controlChar :: TerminalAttributes -> ControlCharacter -> Maybe Char
1966 withCC :: TerminalAttributes
1967 -> (ControlCharacter, Char)
1968 -> TerminalAttributes
1969 withoutCC :: TerminalAttributes
1971 -> TerminalAttributes
1973 inputTime :: TerminalAttributes -> Int
1974 withTime :: TerminalAttributes -> Int -> TerminalAttributes
1976 minInput :: TerminalAttributes -> Int
1977 withMinInput :: TerminalAttributes -> Int -> TerminalAttributes
1979 inputSpeed :: TerminalAttributes -> BaudRate
1980 withInputSpeed :: TerminalAttributes -> BaudRate -> TerminalAttributes
1982 outputSpeed :: TerminalAttributes -> BaudRate
1983 withOutputSpeed :: TerminalAttributes -> BaudRate -> TerminalAttributes
1985 getTerminalAttributes :: Channel -> IO TerminalAttributes
1988 \tr{getTerminalAttributes fd} calls \tr{tcgetattr} to obtain
1989 the \tr{TerminalAttributes} associated with \tr{Channel}
1993 setTerminalAttributes :: Channel
1994 -> TerminalAttributes
1999 \tr{setTerminalAttributes fd attr ts} calls \tr{tcsetattr} to change
2000 the \tr{TerminalAttributes} associated with \tr{Channel} \tr{fd} to
2001 \tr{attr}, when the terminal is in the state indicated by \tr{ts}.
2004 sendBreak :: Channel -> Int -> IO ()
2007 \tr{sendBreak fd duration} calls \tr{tcsendbreak} to transmit a
2008 continuous stream of zero-valued bits on \tr{Channel} \tr{fd} for the
2009 specified implementation-dependent \tr{duration}.
2012 drainOutput :: Channel -> IO ()
2015 \tr{drainOutput fd} calls \tr{tcdrain} to block until all output
2016 written to \tr{Channel} \tr{fd} has been transmitted.
2019 discardData :: Channel -> QueueSelector -> IO ()
2022 \tr{discardData fd queues} calls \tr{tcflush} to discard
2023 pending input and/or output for \tr{Channel} \tr{fd},
2024 as indicated by the \tr{QueueSelector} \tr{queues}.
2027 controlFlow :: Channel -> FlowAction -> IO ()
2030 \tr{controlFlow fd action} calls \tr{tcflow} to control the
2031 flow of data on \tr{Channel} \tr{fd}, as indicated by
2035 getTerminalProcessGroupID :: Channel -> IO ProcessGroupID
2038 \tr{getTerminalProcessGroupID fd} calls \tr{tcgetpgrp} to
2039 obtain the \tr{ProcessGroupID} of the foreground process group
2040 associated with the terminal attached to \tr{Channel}
2044 setTerminalProcessGroupID :: Channel -> ProcessGroupID -> IO ()
2047 \tr{setTerminalProcessGroupID fd pgid} calls \tr{tcsetpgrp} to
2048 set the \tr{ProcessGroupID} of the foreground process group
2049 associated with the terminal attached to \tr{Channel}
2050 \tr{fd} to \tr{pgid}.
2052 \subsubsection[System Database]{Posix System Databases}
2053 \index{Posix, system databases}
2056 groupName :: GroupEntry -> String
2057 groupID :: GroupEntry -> GroupID
2058 groupMembers :: GroupEntry -> [String]
2060 getGroupEntryForID :: GroupID -> IO GroupEntry
2063 \tr{getGroupEntryForID gid} calls \tr{getgrgid} to obtain
2064 the \tr{GroupEntry} information associated with \tr{GroupID}
2067 The operation may fail with:
2070 \item[\tr{NoSuchThing}]
2071 There is no group entry for the GroupID.
2075 getGroupEntryForName :: String -> IO GroupEntry
2078 \tr{getGroupEntryForName name} calls \tr{getgrnam} to obtain
2079 the \tr{GroupEntry} information associated with the group called
2082 The operation may fail with:
2085 \item[\tr{NoSuchThing}]
2086 There is no group entry for the name.
2090 userName :: UserEntry -> String
2091 userID :: UserEntry -> UserID
2092 userGroupID :: UserEntry -> GroupID
2093 homeDirectory :: UserEntry -> String
2094 userShell :: UserEntry -> String
2096 getUserEntryForID :: UserID -> IO UserEntry
2099 \tr{getUserEntryForID gid} calls \tr{getpwuid} to obtain
2100 the \tr{UserEntry} information associated with \tr{UserID}
2102 The operation may fail with:
2105 \item[\tr{NoSuchThing}]
2106 There is no user entry for the UserID.
2110 getUserEntryForName :: String -> IO UserEntry
2113 \tr{getUserEntryForName name} calls \tr{getpwnam} to obtain
2114 the \tr{UserEntry} information associated with the user login
2117 The operation may fail with:
2120 \item[\tr{NoSuchThing}]
2121 There is no user entry for the name.
2124 \subsubsection[Error reporting and handling]{POSIX Errors}
2125 \index{Posix, errors}
2128 getErrorCode :: IO ErrorCode
2131 \tr{getErrorCode} returns the current value of the external
2132 variable \tr{errno}. It never fails.
2135 setErrorCode :: ErrorCode -> IO ()
2138 \tr{setErrorCode err} sets the external
2139 variable \tr{errno} to \tr{err}. It never fails.
2142 noError :: ErrorCode
2145 argumentListTooLong, e2BIG :: ErrorCode
2146 badChannel, eBADF :: ErrorCode
2147 brokenPipe, ePIPE :: ErrorCode
2148 directoryNotEmpty, eNOTEMPTY :: ErrorCode
2149 execFormatError, eNOEXEC :: ErrorCode
2150 fileAlreadyExists, eEXIST :: ErrorCode
2151 fileTooLarge, eFBIG :: ErrorCode
2152 filenameTooLong, eNAMETOOLONG :: ErrorCode
2153 improperLink, eXDEV :: ErrorCode
2154 inappropriateIOControlOperation, eNOTTY :: ErrorCode
2155 inputOutputError, eIO :: ErrorCode
2156 interruptedOperation, eINTR :: ErrorCode
2157 invalidArgument, eINVAL :: ErrorCode
2158 invalidSeek, eSPIPE :: ErrorCode
2159 isADirectory, eISDIR :: ErrorCode
2160 noChildProcess, eCHILD :: ErrorCode
2161 noLocksAvailable, eNOLCK :: ErrorCode
2162 noSpaceLeftOnDevice, eNOSPC :: ErrorCode
2163 noSuchOperationOnDevice, eNODEV :: ErrorCode
2164 noSuchDeviceOrAddress, eNXIO :: ErrorCode
2165 noSuchFileOrDirectory, eNOENT :: ErrorCode
2166 noSuchProcess, eSRCH :: ErrorCode
2167 notADirectory, eNOTDIR :: ErrorCode
2168 notEnoughMemory, eNOMEM :: ErrorCode
2169 operationNotImplemented, eNOSYS :: ErrorCode
2170 operationNotPermitted, ePERM :: ErrorCode
2171 permissionDenied, eACCES :: ErrorCode
2172 readOnlyFileSystem, eROFS :: ErrorCode
2173 resourceBusy, eBUSY :: ErrorCode
2174 resourceDeadlockAvoided, eDEADLK :: ErrorCode
2175 resourceTemporarilyUnavailable, eAGAIN :: ErrorCode
2176 tooManyLinks, eMLINK :: ErrorCode
2177 tooManyOpenFiles, eMFILE :: ErrorCode
2178 tooManyOpenFilesInSystem, eNFILE :: ErrorCode
2182 %************************************************************************
2184 \subsection[HBC-library]{The HBC system library}
2185 \index{HBC system library}
2186 \index{system library, HBC}
2188 %************************************************************************
2190 This documentation is stolen directly from the HBC distribution. The
2191 modules that GHC does not support (because they require HBC-specific
2192 extensions) are omitted.
2196 \index{Either module (HBC library)}%
2197 A binary sum data type:
2199 data Either a b = Left a | Right b
2201 The constructor \tr{Left} is typically used for errors; it can be
2202 renamed to \tr{Wrong} on import.
2205 \index{Maybe module (HBC library)}%
2206 A type for failure or success:
2208 data Maybe a = Nothing | Just a
2209 thenM :: Maybe a -> (a -> Maybe b) -> Maybe b
2210 -- apply a function that may fail
2214 \index{Option module (HBC library)}%
2215 An alias for \tr{Maybe}:
2217 data Option a = None | Some a
2218 thenO :: Option a -> (a -> Option b) -> Option b
2221 \item[\tr{ListUtil}:]
2222 \index{ListUtil module (HBC library)}%
2223 Various useful functions involving lists that are missing from the
2226 assoc :: (Eq c) => (a -> b) -> b -> [(c, a)] -> c -> b
2227 -- assoc f d l k looks for k in the association list l, if it
2228 -- is found f is applied to the value, otherwise d is returned.
2229 concatMap :: (a -> [b]) -> [a] -> [b]
2230 -- flattening map (LML's concmap)
2231 unfoldr :: (a -> (b, a)) -> (a -> Bool) -> a -> [b]
2232 -- unfoldr f p x repeatedly applies f to x until (p x) holds.
2233 -- (f x) should give a list element and a new x.
2234 mapAccuml :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
2235 -- mapAccuml f s l maps f over l, but also threads the state s
2236 -- through (LML's mapstate).
2237 union :: (Eq a) => [a] -> [a] -> [a]
2238 -- union of two lists
2239 intersection :: (Eq a) => [a] -> [a] -> [a]
2240 -- intersection of two lists
2241 chopList :: ([a] -> (b, [a])) -> [a] -> [b]
2243 assocDef :: (Eq a) => [(a, b)] -> b -> a -> b
2245 lookup :: (Eq a) => [(a, b)] -> a -> Option b
2246 -- lookup l k looks for the key k in the association list l
2247 -- and returns an optional value
2248 tails :: [a] -> [[a]]
2249 -- return all the tails of a list
2250 rept :: (Integral a) => a -> b -> [b]
2251 -- repeat a value a number of times
2252 groupEq :: (a->a->Bool) -> [a] -> [[a]]
2253 -- group list elements according to an equality predicate
2254 group :: (Eq a) => [a] -> [[a]]
2255 -- group according to} ==
2256 readListLazily :: (Text a) => String -> [a]
2257 -- read a list in a lazy fashion
2261 \index{Pretty module (HBC library)}%
2262 John Hughes's pretty printing library.
2264 type Context = (Bool, Int, Int, Int)
2265 type IText = Context -> [String]
2266 text :: String -> IText -- just text
2267 (~.) :: IText -> IText -> IText -- horizontal composition
2268 (^.) :: IText -> IText -> IText -- vertical composition
2269 separate :: [IText] -> IText -- separate by spaces
2270 nest :: Int -> IText -> IText -- indent
2271 pretty :: Int -> Int -> IText -> String -- format it
2275 \index{QSort module (HBC library)}%
2276 A sort function using quicksort.
2278 sortLe :: (a -> a -> Bool) -> [a] -> [a]
2279 -- sort le l sorts l with le as less than predicate
2280 sort :: (Ord a) => [a] -> [a]
2281 -- sort l sorts l using the Ord class
2285 \index{Random module (HBC library)}%
2288 randomInts :: Int -> Int -> [Int]
2289 -- given two seeds gives a list of random Int
2290 randomDoubles :: Int -> Int -> [Double]
2291 -- random Double with uniform distribution in (0,1)
2292 normalRandomDoubles :: Int -> Int -> [Double]
2293 -- random Double with normal distribution, mean 0, variance 1
2297 Simple tracing. (Note: This comes with GHC anyway.)
2299 trace :: String -> a -> a -- trace x y prints x and returns y
2302 \item[\tr{Miranda}:]
2303 \index{Miranda module (HBC library)}%
2304 Functions found in the Miranda library.
2305 (Note: Miranda is a registered trade mark of Research Software Ltd.)
2308 \index{Word module (HBC library)}
2309 Bit manipulation. (GHC doesn't implement absolutely all of this.
2310 And don't count on @Word@ being 32 bits on a Alpha...)
2313 bitAnd :: a -> a -> a -- bitwise and
2314 bitOr :: a -> a -> a -- bitwise or
2315 bitXor :: a -> a -> a -- bitwise xor
2316 bitCompl :: a -> a -- bitwise negation
2317 bitRsh :: a -> Int -> a -- bitwise right shift
2318 bitLsh :: a -> Int -> a -- bitwise left shift
2319 bitSwap :: a -> a -- swap word halves
2320 bit0 :: a -- word with least significant bit set
2321 bitSize :: a -> Int -- number of bits in a word
2323 data Byte -- 8 bit quantity
2324 data Short -- 16 bit quantity
2325 data Word -- 32 bit quantity
2327 instance Bits Byte, Bits Short, Bits Word
2328 instance Eq Byte, Eq Short, Eq Word
2329 instance Ord Byte, Ord Short, Ord Word
2330 instance Text Byte, Text Short, Text Word
2331 instance Num Byte, Num Short, Num Word
2332 wordToShorts :: Word -> [Short] -- convert a Word to two Short
2333 wordToBytes :: Word -> [Byte] -- convert a Word to four Byte
2334 bytesToString :: [Byte] -> String -- convert a list of Byte to a String (bit by bit)
2335 wordToInt :: Word -> Int -- convert a Word to Int
2336 shortToInt :: Short -> Int -- convert a Short to Int
2337 byteToInt :: Byte -> Int -- convert a Byte to Int
2341 \index{Time module (HBC library)}%
2342 Manipulate time values (a Double with seconds since 1970).
2344 -- year mon day hour min sec dec-sec weekday
2345 data Time = Time Int Int Int Int Int Int Double Int
2346 dblToTime :: Double -> Time -- convert a Double to a Time
2347 timeToDbl :: Time -> Double -- convert a Time to a Double
2348 timeToString :: Time -> String -- convert a Time to a readable String
2352 \index{Hash module (HBC library)}%
2355 class Hashable a where
2356 hash :: a -> Int -- hash a value, return an Int
2357 -- instances for all Prelude types
2358 hashToMax :: (Hashable a) => Int -> a -> Int -- hash into interval [0..x-1]
2361 \item[\tr{NameSupply}:]
2362 \index{NameSupply module (HBC library)}%
2363 Functions to generate unique names (Int).
2366 initialNameSupply :: NameSupply
2367 -- The initial name supply (may be different every
2368 -- time the program is run.
2369 splitNameSupply :: NameSupply -> (NameSupply,NameSupply)
2370 -- split the namesupply into two
2371 getName :: NameSupply -> Name
2372 -- get the name associated with a name supply
2376 \index{Parse module (HBC library)}%
2377 Higher order functions to build parsers. With a little care these
2378 combinators can be used to build efficient parsers with good error
2381 infixr 8 +.+ , ..+ , +..
2382 infix 6 `act` , >>> , `into` , .>
2383 infixr 4 ||| , ||! , |!!
2384 data ParseResult a b
2385 type Parser a b = a -> Int -> ParseResult a b
2386 (|||) :: Parser a b -> Parser a b -> Parser a b
2388 (||!) :: Parser a b -> Parser a b -> Parser a b
2389 -- Alternative, but with committed choice
2390 (|!!) :: Parser a b -> Parser a b -> Parser a b
2391 -- Alternative, but with committed choice
2392 (+.+) :: Parser a b -> Parser a c -> Parser a (b,c)
2394 (..+) :: Parser a b -> Parser a c -> Parser a c
2395 -- Sequence, throw away first part
2396 (+..) :: Parser a b -> Parser a c -> Parser a b
2397 -- Sequence, throw away second part
2398 act :: Parser a b -> (b->c) -> Parser a c
2400 (>>>) :: Parser a (b,c) -> (b->c->d) -> Parser a d
2401 -- Action on two items
2402 (.>) :: Parser a b -> c -> Parse a c
2403 -- Action ignoring value
2404 into :: Parser a b -> (b -> Parser a c) -> Parser a c
2405 -- Use a produced value in a parser.
2406 succeed b :: Parser a b
2407 -- Always succeeds without consuming a token
2410 many :: Parser a b -> Parser a [b]
2412 many1 :: Parser a b -> Parser a [b]
2414 count :: Parser a b -> Int -> Parser a [b]
2415 -- Parse an exact number of items
2416 sepBy1 :: Parser a b -> Parser a c -> Parser a [b]
2417 -- Non-empty sequence of items separated by something
2418 sepBy :: Parser a b -> Parser a c -> Parser a [b]
2419 -- Sequence of items separated by something
2420 lit :: (Eq a, Text a) => a -> Parser [a] a
2421 -- Recognise a literal token from a list of tokens
2422 litp :: String -> (a->Bool) -> Parser [a] a
2423 -- Recognise a token with a predicate.
2424 -- The string is a description for error messages.
2425 testp :: String -> (a -> Bool) -> (Parser b a) -> Parser b a
2426 -- Test a semantic value.
2427 token :: (a -> Either String (b, a)) -> Parser a b
2428 -- General token recogniser.
2429 parse :: Parser a b -> a -> Either ([String], a) [(b, a)]
2430 -- Do a parse. Return either error (possible tokens and rest
2431 -- of tokens) or all possible parses.
2432 sParse :: (Text a) => (Parser [a] b) -> [a] -> Either String b
2433 -- Simple parse. Return error message or result.
2436 %%%simpleLex :: String -> [String] -- A simple (but useful) lexical analyzer
2439 \index{Native module (HBC library)}%
2440 Functions to convert the primitive types \tr{Int}, \tr{Float}, and \tr{Double} to
2441 their native representation as a list of bytes (\tr{Char}). If such a list
2442 is read/written to a file it will have the same format as when, e.g.,
2443 C read/writes the same kind of data.
2445 type Bytes = [Char] -- A byte stream is just a list of characters
2447 class Native a where
2448 showBytes :: a -> Bytes -> Bytes
2449 -- prepend the representation of an item the a byte stream
2450 listShowBytes :: [a] -> Bytes -> Bytes
2451 -- prepend the representation of a list of items to a stream
2452 -- (may be more efficient than repeating showBytes).
2453 readBytes :: Bytes -> Maybe (a, Bytes)
2454 -- get an item from the stream and return the rest,
2455 -- or fail if the stream is to short.
2456 listReadBytes :: Int -> Bytes -> Maybe ([a], Bytes)
2457 -- read n items from a stream.
2460 instance Native Float
2461 instance Native Double
2462 instance (Native a, Native b) => Native (a,b)
2463 -- juxtaposition of the two items
2464 instance (Native a, Native b, Native c) => Native (a, b, c)
2465 -- juxtaposition of the three items
2466 instance (Native a) => Native [a]
2467 -- an item count in an Int followed by the items
2469 shortIntToBytes :: Int -> Bytes -> Bytes
2470 -- Convert an Int to what corresponds to a short in C.
2471 bytesToShortInt :: Bytes -> Maybe (Int, Bytes)
2472 -- Get a short from a byte stream and convert to an Int.
2474 showB :: (Native a) => a -> Bytes -- Simple interface to showBytes.
2475 readB :: (Native a) => Bytes -> a -- Simple interface to readBytes.
2479 \index{Number module (HBC library)}%
2480 Simple numbers that belong to all numeric classes and behave like
2481 a naive user would expect (except that printing is still ugly).
2482 (NB: GHC does not provide a magic way to use \tr{Numbers} everywhere,
2483 but you should be able to do it with normal \tr{import}ing and
2486 data Number -- The type itself.
2487 instance ... -- All reasonable instances.
2488 isInteger :: Number -> Bool -- Test if a Number is an integer.