home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / hugs101o.zip / Progs / HUGS / hugs.prelude < prev    next >
Text File  |  1995-03-02  |  64KB  |  1,692 lines

  1. -----------------------------------------------------------------------------
  2. --        ___    ___   ___    ___   __________   __________           --
  3. --       /  /   /  /  /  /   /  /  /  _______/  /  _______/   Version 1.01 --
  4. --      /  /___/  /  /  /   /  /  /  / _____   /  /______           --
  5. --     /  ____   /  /  /   /  /  /  / /_   /  /______   /     Copyright    --
  6. --    /  /   /  /  /  /___/  /  /  /___/  /  _______/  /      Mark P Jones --
  7. --   /__/   /__/  /_________/  /_________/  /_________/       1994, 1995   --
  8. --                                       --
  9. --   The Haskell User's Gofer System.   Derived from Gofer 2.30b.       --
  10. --                                       --
  11. --   This is the Hugs Standard Prelude, based very closely on the Standard --
  12. --   Prelude for Haskell 1.2.                           --
  13. --                                       --
  14. --   Hugs is subject to conditions of use and distribution; see the file   --
  15. --   "NOTICE" included with the main distribution for further details.     --
  16. --                                                                         --
  17. --   WARNING: This file is an integral part of the Hugs source code.       --
  18. --   Changes to the definitions in this file without corresponding         --
  19. --   modifications in other parts of the program may cause the interpreter --
  20. --   to fail unexpectedly.  Under normal circumstances, you should not       --
  21. --   attempt to modify this file in any way!  If you want to use a system  --
  22. --   where the prelude file can be changed, try Gofer instead.           --
  23. --                                       --
  24. -----------------------------------------------------------------------------
  25.  
  26. -- Standard value bindings {Prelude} ----------------------------------------
  27.  
  28. infixr 9  .
  29. infixl 9  !!, !, //
  30. infixr 8  ^, ^^, **
  31.           -- Fixities for the following operators are taken from the
  32.           -- prelude listing in Appendix A of the Haskell report.
  33.           -- Note that there are some discrepancies w.r.t. Section 5.7.
  34. infixl 7  *, /, `quot`, `rem`, `div`, `mod`, :%, %
  35. infix  6  :+
  36. infixl 6  +, -
  37. infix  5  \\
  38. infixr 5  :, ++
  39. infix  4  ==, /=, <, <=, >=, >, `elem`, `notElem`
  40. infixr 3  &&
  41. infixr 2  ||
  42. infix  1  :=
  43. infixr 0  $
  44.  
  45. -- Binary functions ---------------------------------------------------------
  46.  
  47. nullBin   :: Bin
  48. nullBin    = noBinTypeInHugs
  49.  
  50. isNullBin :: Bin -> Bool
  51. isNullBin  = noBinTypeInHugs
  52.  
  53. appendBin :: Bin -> Bin -> Bin
  54. appendBin  = noBinTypeInHugs
  55.  
  56. noBinTypeInHugs = error "There is no Bin type in Hugs"
  57.  
  58. -- Boolean functions --------------------------------------------------------
  59.  
  60. (&&), (||)     :: Bool -> Bool -> Bool
  61. False && x      = False
  62. True  && x      = x
  63. False || x      = x
  64. True  || x      = True
  65.  
  66. not            :: Bool -> Bool
  67. not True        = False
  68. not False       = True
  69.  
  70. otherwise      :: Bool
  71. otherwise       = True
  72.  
  73. -- Character functions ------------------------------------------------------
  74.  
  75. minChar, maxChar      :: Char
  76. minChar                = '\0'
  77. maxChar                = '\255'
  78.  
  79. primitive ord "primCharToInt" :: Char -> Int
  80. primitive chr "primIntToChar" :: Int -> Char
  81.  
  82. isAscii, isControl, isPrint, isSpace            :: Char -> Bool
  83. isUpper, isLower, isAlpha, isDigit, isAlphanum  :: Char -> Bool
  84.  
  85. isAscii c              =  ord c < 128
  86. isControl c            =  c < ' ' ||  c == '\DEL'
  87. isPrint c              =  c >= ' ' &&  c <= '~'
  88. isSpace c              =  c == ' ' || c == '\t' || c == '\n' ||
  89.                   c == '\r' || c == '\f' || c == '\v'
  90. isUpper c              =  c >= 'A'   &&  c <= 'Z'
  91. isLower c              =  c >= 'a'   &&  c <= 'z'
  92. isAlpha c              =  isUpper c  ||  isLower c
  93. isDigit c              =  c >= '0'   &&  c <= '9'
  94. isAlphanum c           =  isAlpha c  ||  isDigit c
  95.  
  96. toUpper, toLower      :: Char -> Char
  97. toUpper c | isLower c  = chr (ord c - ord 'a' + ord 'A')
  98.           | otherwise  = c
  99.  
  100. toLower c | isUpper c  = chr (ord c - ord 'A' + ord 'a')
  101.           | otherwise  = c
  102.  
  103. -- Numeric functions --------------------------------------------------------
  104.  
  105. primitive minInt "primMinInt", maxInt "primMaxInt" :: Int
  106.  
  107. subtract       :: Num a => a -> a -> a
  108. subtract        = flip (-)
  109.  
  110. gcd            :: Integral a => a -> a -> a
  111. gcd 0 0         = error "gcd{Prelude}: gcd 0 0 is undefined"
  112. gcd x y         = gcd' (abs x) (abs y)
  113.                   where gcd' x 0 = x
  114.                         gcd' x y = gcd' y (x `rem` y)
  115.  
  116. lcm            :: (Integral a) => a -> a -> a
  117. lcm _ 0         = 0
  118. lcm 0 _         = 0
  119. lcm x y         = abs ((x `quot` gcd x y) * y)
  120.  
  121. (^)            :: (Num a, Integral b) => a -> b -> a
  122. x ^ 0           = 1
  123. x ^ (n+1)       = f x n x
  124.                   where f _ 0 y = y
  125.                         f x n y = g x n where
  126.                                   g x n | even n    = g (x*x) (n`quot`2)
  127.                                         | otherwise = f x (n-1) (x*y)
  128. _ ^ _           = error "(^){Prelude}: negative exponent"
  129.  
  130. (^^)           :: (Fractional a, Integral b) => a -> b -> a
  131. x ^^ n          = if n >= 0 then x ^ n else recip (x^(-n))
  132.  
  133. fromIntegral   :: (Integral a, Num b) => a -> b
  134. fromIntegral    = fromInteger . toInteger
  135.  
  136. fromRealFrac   :: (RealFrac a, Fractional b) => a -> b
  137. fromRealFrac    = fromRational . toRational
  138.  
  139. atan2          :: (RealFloat a) => a -> a -> a
  140. atan2 y x       = case (signum y, signum x) of
  141.                     ( 0, 1) ->  0
  142.                     ( 1, 0) ->  pi/2
  143.                     ( 0,-1) ->  pi
  144.                     (-1, 0) -> -pi/2
  145.             ( _, 1) -> atan (y/x)
  146.             ( _,-1) -> atan (y/x) + pi
  147.             ( 0, 0) -> error "atan2{Prelude}: atan2 of origin"
  148.  
  149. -- Some standard functions --------------------------------------------------
  150. -- component projections for pairs:
  151. fst            :: (a,b) -> a
  152. fst (x,_)       = x
  153.  
  154. snd            :: (a,b) -> b
  155. snd (_,y)       = y
  156.  
  157. -- identity function
  158. id             :: a -> a
  159. id    x         = x
  160.  
  161. -- constant function
  162. const          :: a -> b -> a
  163. const k _       = k
  164.  
  165. -- function composition
  166. (.)           :: (b -> c) -> (a -> b) -> (a -> c)
  167. (f . g) x       = f (g x)
  168.  
  169. -- flip f takes its (first) two arguuments in the reverse order of f.
  170. flip           :: (a -> b -> c) -> b -> a -> c
  171. flip  f x y     = f y x
  172.  
  173. -- right associative infix application operator (useful in continuation-
  174. -- passing style)
  175. ($)            :: (a -> b) -> a -> b     -- pronounced as `apply' elsewhere
  176. f $ x           = f x
  177.  
  178. -- until p f  yields the result of applying f until p holds
  179. until                  :: (a -> Bool) -> (a -> a) -> a -> a
  180. until p f x | p x       = x
  181.             | otherwise = until p f (f x)
  182.  
  183. -- asTypeOf is a type restricted version of const.  It is usually used
  184. -- as an infix operator, and its typing forces its first argument
  185. -- (which is usually overloaded) to have the same type as the second.
  186. asTypeOf               :: a -> a -> a
  187. asTypeOf                = const
  188.  
  189. -- error is applied to a string, returns any type, and is everywhere
  190. -- undefined.  Operationally, the intent is that its application
  191. -- terminates execution of the program and displays the argument
  192. -- string in some appropriate way.
  193. primitive error "primError" :: String -> a
  194.  
  195. -- strict is not defined in the Haskell prelude, but Hugs doesn't have a
  196. -- strictness analyzer and it's occasionally useful to be able to exercise
  197. -- some added degree over the order of evaluation.
  198. primitive strict "primStrict" :: (a -> b) -> a -> b
  199.  
  200. -- Standard types, classes and instances {PreludeCore} ----------------------
  201.  
  202. -- Equality and Ordered classes ---------------------------------------------
  203.  
  204. class Eq a where
  205.     (==), (/=) :: a -> a -> Bool
  206.     x /= y      = not (x==y)
  207.  
  208. -- ordcmp is a new variation on an old idea;  ordcmp x y r  returns
  209. -- True if x>y, False if x<y and r otherwise.  The conventional ordering
  210. -- operators are defined in terms of ordcmp, but a default definition of
  211. -- ordcmp is also provided just in case.  It is an error (but not detected
  212. -- by the compiler) for the programmer to omit definitions both for <=
  213. -- and for ordcmp.  It will also be assumed that the ordering is consistent
  214. -- with the equality.
  215. --        e.g. ordcmp (x:xs) (y:ys) = ordcmp x y . ordcmp xs ys
  216. --
  217. -- Unlike Haskell 1.2, we now assume that orderings are total.
  218.  
  219. class (Eq a) => Ord a where
  220.     ordcmp               :: a -> a -> Bool -> Bool
  221.     (<), (<=), (>=), (>) :: a -> a -> Bool
  222.     max, min             :: a -> a -> a
  223.  
  224. --  ordcmp x y r          = ... define in terms of <= and == only and be
  225. --                careful not to eval r until it is needed ...
  226.     ordcmp x y r          = if x<=y then (x==y && r) else True
  227.  
  228.     x >  y                = ordcmp x y False
  229.     x >= y                = ordcmp x y True
  230.     x <  y                = ordcmp y x False
  231.     x <= y                = ordcmp y x True
  232.  
  233.     max x y | x >= y      = x
  234.             | otherwise   = y
  235.     min x y | x <= y      = x
  236.             | otherwise   = y
  237.  
  238. -- Numeric classes ----------------------------------------------------------
  239.  
  240. class (Eq a, Text a) => Num a where
  241.     (+), (-), (*)  :: a -> a -> a
  242.     negate         :: a -> a
  243.     abs, signum    :: a -> a
  244.     fromInteger    :: Integer -> a
  245.     fromInt        :: Int -> a
  246.  
  247.     x - y           = x + negate y
  248.  
  249. class (Num a, Enum a) => Real a where
  250.     toRational     :: a -> Rational
  251.  
  252. class (Real a, Ix a) => Integral a where
  253.     quot, rem, div, mod :: a -> a -> a
  254.     quotRem, divMod     :: a -> a -> (a,a)
  255.     even, odd           :: a -> Bool
  256.     toInteger           :: a -> Integer
  257.     toInt               :: a -> Int
  258.  
  259.     n `quot` d           = q where (q,r) = quotRem n d
  260.     n `rem` d            = r where (q,r) = quotRem n d
  261.     n `div` d            = q where (q,r) = divMod n d
  262.     n `mod` d            = r where (q,r) = divMod n d
  263.     divMod n d           = if signum r == - signum d then (q-1, r+d) else qr
  264.                where qr@(q,r) = quotRem n d
  265.     even n               = n `rem` 2 == 0 
  266.     odd                  = not . even
  267.  
  268. class (Num a) => Fractional a where
  269.     (/)          :: a -> a -> a
  270.     recip        :: a -> a
  271.     fromRational :: Rational -> a
  272.     fromDouble   :: Double -> a
  273.  
  274.     recip x       = 1 / x
  275.  
  276. class (Fractional a) => Floating a where
  277.     pi                  :: a
  278.     exp, log, sqrt      :: a -> a
  279.     (**), logBase       :: a -> a -> a
  280.     sin, cos, tan       :: a -> a
  281.     asin, acos, atan    :: a -> a
  282.     sinh, cosh, tanh    :: a -> a
  283.     asinh, acosh, atanh :: a -> a
  284.  
  285.     x ** y               = exp (log x * y)
  286.     logBase x y          = log y / log x
  287.     sqrt x               = x ** 0.5
  288.     tan x                = sin x / cos x
  289.     sinh x               = (exp x - exp (-x)) / 2
  290.     cosh x               = (exp x + exp (-x)) / 2
  291.     tanh x               = sinh x / cosh x
  292.     asinh x              = log (x + sqrt (x*x + 1))
  293.     acosh x              = log (x + sqrt (x*x - 1))
  294.     atanh x              = (log (1 + x) - log (1 - x)) / 2
  295.  
  296. class (Real a, Fractional a) => RealFrac a where
  297.     properFraction   :: (Integral b) => a -> (b,a)
  298.     truncate, round  :: (Integral b) => a -> b
  299.     ceiling, floor   :: (Integral b) => a -> b
  300.  
  301.     truncate x        = m where (m,_) = properFraction x
  302.  
  303.     round x           = let (n,r) = properFraction x
  304.                             m     = if r < 0 then n - 1 else n + 1
  305.                         in case signum (abs r - 0.5) of
  306.                             -1 -> n
  307.                             0  -> if even n then n else m
  308.                             1  -> m
  309.  
  310.     ceiling x         = if r > 0 then n + 1 else n
  311.                         where (n,r) = properFraction x
  312.  
  313.     floor x           = if r < 0 then n - 1 else n
  314.                         where (n,r) = properFraction x
  315.  
  316. class (RealFrac a, Floating a) => RealFloat a where
  317.     floatRadix       :: a -> Integer
  318.     floatDigits      :: a -> Int
  319.     floatRange       :: a -> (Int,Int)
  320.     decodeFloat      :: a -> (Integer,Int)
  321.     encodeFloat      :: Integer -> Int -> a
  322.     exponent         :: a -> Int
  323.     significand      :: a -> a
  324.     scaleFloat       :: Int -> a -> a
  325.  
  326.     exponent x        = if m==0 then 0 else n + floatDigits x
  327.                         where (m,n) = decodeFloat x
  328.     significand x     = encodeFloat m (- floatDigits x)
  329.                         where (m,_) = decodeFloat x
  330.     scaleFloat k x    = encodeFloat m (n+k)
  331.                         where (m,n) = decodeFloat x
  332.  
  333. -- Index and Enumeration classes --------------------------------------------
  334.  
  335. class (Ord a) => Ix a where
  336.     range                :: (a,a) -> [a]
  337.     index                :: (a,a) -> a -> Int
  338.     inRange              :: (a,a) -> a -> Bool
  339.  
  340. class (Ord a) => Enum a where
  341.     enumFrom             :: a -> [a]              -- [n..]
  342.     enumFromThen         :: a -> a -> [a]         -- [n,m..]
  343.     enumFromTo           :: a -> a -> [a]         -- [n..m]
  344.     enumFromThenTo       :: a -> a -> a -> [a]    -- [n,n'..m]
  345.  
  346.     enumFromTo n m        = takeWhile (m>=) (enumFrom n)
  347.     enumFromThenTo n n' m = takeWhile ((if n'>=n then (>=) else (<=)) m)
  348.                                       (enumFromThen n n')
  349.  
  350. -- Text class ---------------------------------------------------------------
  351.  
  352. type  ReadS a = String -> [(a,String)]
  353. type  ShowS   = String -> String
  354.  
  355. class Text a where 
  356.     readsPrec :: Int -> ReadS a
  357.     showsPrec :: Int -> a -> ShowS
  358.     readList  :: ReadS [a]
  359.     showList  :: [a] -> ShowS
  360.  
  361.     readList        = readParen False (\r -> [pr | ("[",s) <- lex r,
  362.                            pr      <- readl s ])
  363.               where readl  s = [([],t)   | ("]",t) <- lex s] ++
  364.                                        [(x:xs,u) | (x,t)   <- reads s,
  365.                            (xs,u)  <- readl' t]
  366.                     readl' s = [([],t)   | ("]",t) <- lex s] ++
  367.                                        [(x:xs,v) | (",",t) <- lex s,
  368.                            (x,u)   <- reads t,
  369.                            (xs,v)  <- readl' u]
  370.  
  371.     showList []     = showString "[]"
  372.     showList (x:xs) = showChar '[' . shows x . showl xs
  373.                       where showl []     = showChar ']'
  374.                             showl (x:xs) = showChar ',' . shows x . showl xs
  375.  
  376. -- Binary class -------------------------------------------------------------
  377.  
  378. -- Although Hugs does not provide any operations on the binary datatype, Bin,
  379. -- we include the definition of the Binary class here for compatibility with
  380. -- Haskell ... all of this may go in later versions of Haskell and Hugs.
  381. class Binary a where
  382.     readBin :: Bin -> (a,Bin)
  383.     showBin :: a -> Bin -> Bin
  384.  
  385.     readBin  = noBinTypeInHugs
  386.     showBin  = noBinTypeInHugs
  387.  
  388. -- Trivial type -------------------------------------------------------------
  389.  
  390. -- data () = () deriving (Eq, Ord, Ix, Enum, Text, Binary)
  391.  
  392. instance Eq () where
  393.     () == ()  =  True
  394.  
  395. instance Ord () where
  396.     ordcmp () () s = s
  397.  
  398. instance Ix () where
  399.     range ((),())      = [()]
  400.     index ((),()) ()   = 0
  401.     inRange ((),()) () = True
  402.  
  403. instance Enum () where
  404.     enumFrom ()        = [()]
  405.     enumFromThen () () = [()]
  406.  
  407. instance Text () where
  408.     readsPrec p    = readParen False
  409.                             (\r -> [((),t) | ("(",s) <- lex r,
  410.                                              (")",t) <- lex s ])
  411.     showsPrec p () = showString "()"
  412.  
  413. instance Binary ()
  414.  
  415. -- Binary type --------------------------------------------------------------
  416.  
  417. instance Text Bin where
  418.     readsPrec p s = error "readsPrec{PreludeText}: Cannot read Bin"
  419.     showsPrec d b = showString "<<Bin>>>"
  420.  
  421. -- Boolean type -------------------------------------------------------------
  422.  
  423. data Bool = False | True deriving (Eq, Ord, Ix, Enum, Text, Binary)
  424.  
  425. -- Character type -----------------------------------------------------------
  426.  
  427. primitive primEqChar   "primEqChar",
  428.       primLeChar   "primLeChar"  :: Char -> Char -> Bool
  429.  
  430. instance Eq Char  where (==) = primEqChar   -- c == d  =  ord c == ord d
  431. instance Ord Char where (<=) = primLeChar   -- c <= d  =  ord c <= ord d
  432.  
  433. instance Ix Char where
  434.     range (c,c')      = [c..c']
  435.     index b@(c,c') ci
  436.        | inRange b ci = ord ci - ord c
  437.        | otherwise    = error "index{PreludeCore}: Index out of range"
  438.     inRange (c,c') ci = ord c <= i && i <= ord c'
  439.                         where i = ord ci
  440.  
  441. instance Enum Char where
  442.     enumFrom c        = map chr [ord c .. ord maxChar]
  443.     enumFromThen c c' = map chr [ord c, ord c' .. ord lastChar]
  444.                         where lastChar = if c' < c then minChar else maxChar
  445.   
  446. instance Text Char where
  447.     readsPrec p      = readParen False
  448.                             (\r -> [(c,t) | ('\'':s,t) <- lex r,
  449.                                             (c,_)      <- readLitChar s])
  450.     showsPrec p '\'' = showString "'\\''"
  451.     showsPrec p c    = showChar '\'' . showLitChar c . showChar '\''
  452.  
  453.     readList = readParen False (\r -> [(l,t) | ('"':s, t) <- lex r,
  454.                                                (l,_)      <- readl s ])
  455.                where readl ('"':s)      = [("",s)]
  456.                      readl ('\\':'&':s) = readl s
  457.                      readl s            = [(c:cs,u) | (c ,t) <- readLitChar s,
  458.                                                       (cs,u) <- readl t ]
  459.  
  460.     showList cs   = showChar '"' . showl cs
  461.                     where showl ""       = showChar '"'
  462.                           showl ('"':cs) = showString "\\\"" . showl cs
  463.                           showl (c:cs)   = showChar c . showl cs
  464.               -- Haskell has   showLitChar c . showl cs
  465.  
  466. type String = [Char]
  467.  
  468. -- Standard Integral types --------------------------------------------------
  469.  
  470. primitive primEqInt      "primEqInt"     :: Int -> Int -> Bool
  471. primitive primCmpInt     "primCmpInt"    :: Int -> Int -> Bool -> Bool
  472. primitive primEqInteger  "primEqInteger" :: Integer -> Integer -> Bool
  473. primitive primCmpInteger "primCmpInteger":: Integer -> Integer -> Bool -> Bool
  474.  
  475. instance Eq  Int     where (==)   = primEqInt
  476. instance Eq  Integer where (==)   = primEqInteger
  477. instance Ord Int     where ordcmp = primCmpInt
  478. instance Ord Integer where ordcmp = primCmpInteger
  479.  
  480. primitive primPlusInt      "primPlusInt",
  481.       primMinusInt     "primMinusInt",
  482.       primMulInt       "primMulInt"       :: Int -> Int -> Int
  483. primitive primNegInt       "primNegInt"       :: Int -> Int
  484. primitive primIntegerToInt "primIntegerToInt" :: Integer -> Int
  485.  
  486. instance Num Int where
  487.     (+)           = primPlusInt
  488.     (-)           = primMinusInt
  489.     negate        = primNegInt
  490.     (*)           = primMulInt
  491.     abs           = absReal
  492.     signum        = signumReal
  493.     fromInteger   = primIntegerToInt
  494.     fromInt x     = x
  495.  
  496. primitive primPlusInteger  "primPlusInteger",
  497.       primMinusInteger "primMinusInteger",
  498.       primMulInteger   "primMulInteger"   :: Integer -> Integer -> Integer
  499. primitive primNegInteger   "primNegInteger"   :: Integer -> Integer
  500. primitive primIntToInteger "primIntToInteger" :: Int -> Integer
  501.  
  502. instance Num Integer where
  503.     (+)           = primPlusInteger
  504.     (-)           = primMinusInteger
  505.     negate        = primNegInteger
  506.     (*)           = primMulInteger
  507.     abs           = absReal
  508.     signum        = signumReal
  509.     fromInteger x = x
  510.     fromInt       = primIntToInteger
  511.  
  512. absReal x    | x >= 0    = x
  513.              | otherwise = -x
  514.  
  515. signumReal x | x == 0    =  0
  516.              | x > 0     =  1
  517.              | otherwise = -1
  518.  
  519. instance Real Int where
  520.     toRational x = toInteger x % 1
  521.  
  522. instance Real Integer where
  523.     toRational x = x % 1
  524.  
  525. primitive primDivInt  "primDivInt",
  526.       primQuotInt "primQuotInt",
  527.           primRemInt  "primRemInt",
  528.           primModInt  "primModInt"    :: Int -> Int -> Int
  529.  
  530. instance Integral Int where
  531.     div         = primDivInt
  532.     quot        = primQuotInt
  533.     rem         = primRemInt
  534.     mod         = primModInt
  535.     quotRem n d = (n `quot` d, n `rem` d)
  536.     toInteger   = primIntToInteger
  537.     toInt x     = x
  538.  
  539. primitive primQrmInteger  "primQrmInteger"
  540.         :: Integer -> Integer -> (Integer,Integer)
  541. primitive primEvenInteger  "primEvenInteger"  :: Integer -> Bool
  542.  
  543. instance Integral Integer where
  544.     quotRem     = primQrmInteger
  545.     even        = primEvenInteger
  546.     toInteger x = x
  547.     toInt       = primIntegerToInt
  548.  
  549. instance Ix Int where
  550.     range (m,n)          = [m..n]
  551.     index b@(m,n) i
  552.            | inRange b i = i - m
  553.            | otherwise   = error "index{PreludeCore}: Index out of range"
  554.     inRange (m,n) i      = m <= i && i <= n
  555.  
  556. instance Ix Integer where
  557.     range (m,n)          = [m..n]
  558.     index b@(m,n) i
  559.            | inRange b i = fromInteger (i - m)
  560.            | otherwise   = error "index{PreludeCore}: Index out of range"
  561.     inRange (m,n) i      = m <= i && i <= n
  562.  
  563. instance Enum Int where
  564.     enumFrom     = numericEnumFrom
  565.     enumFromThen = numericEnumFromThen
  566.  
  567. instance Enum Integer where
  568.     enumFrom     = numericEnumFrom
  569.     enumFromThen = numericEnumFromThen
  570.  
  571. numericEnumFrom        :: Real a => a -> [a]
  572. numericEnumFromThen    :: Real a => a -> a -> [a]
  573. numericEnumFrom         = iterate (1+)
  574. numericEnumFromThen n m = iterate ((m-n)+) n
  575.  
  576. primitive primShowsInt "primShowsInt" :: Int -> Int -> ShowS
  577.  
  578. instance Text Int where
  579.     readsPrec p = readSigned readDec
  580.     showsPrec   = primShowsInt
  581.  
  582. primitive primShowsInteger "primShowsInteger" :: Int -> Integer -> ShowS
  583.  
  584. instance Text Integer where
  585.     readsPrec p = readSigned readDec
  586.     showsPrec   = primShowsInteger
  587.  
  588. -- Standard Floating types --------------------------------------------------
  589.  
  590. primitive primEqFloat    "primEqFloat",
  591.           primLeFloat    "primLeFloat"    :: Float -> Float -> Bool
  592. primitive primEqDouble   "primEqDouble",
  593.           primLeDouble   "primLeDouble"   :: Double -> Double -> Bool
  594.  
  595. instance Eq  Float  where (==) = primEqFloat
  596. instance Eq  Double where (==) = primEqDouble
  597.  
  598. instance Ord Float  where (<=) = primLeFloat
  599. instance Ord Double where (<=) = primLeDouble
  600.  
  601. primitive primPlusFloat  "primPlusFloat",
  602.           primMinusFloat "primMinusFloat",
  603.           primMulFloat   "primMulFloat"   :: Float -> Float -> Float
  604. primitive primNegFloat   "primNegFloat"   :: Float -> Float
  605. primitive primIntToFloat "primIntToFloat" :: Int -> Float
  606. primitive primIntegerToFloat "primIntegerToFloat" :: Integer -> Float
  607.  
  608. instance Num Float where
  609.     (+)           = primPlusFloat
  610.     (-)           = primMinusFloat
  611.     negate        = primNegFloat
  612.     (*)           = primMulFloat
  613.     abs           = absReal
  614.     signum        = signumReal
  615.     fromInteger   = primIntegerToFloat
  616.     fromInt       = primIntToFloat
  617.  
  618. primitive primPlusDouble  "primPlusDouble",
  619.           primMinusDouble "primMinusDouble",
  620.           primMulDouble   "primMulDouble"   :: Double -> Double -> Double
  621. primitive primNegDouble   "primNegDouble"   :: Double -> Double
  622. primitive primIntToDouble "primIntToDouble" :: Int -> Double
  623. primitive primIntegerToDouble "primIntegerToDouble" :: Integer -> Double
  624.  
  625. instance Num Double where
  626.     (+)         = primPlusDouble
  627.     (-)         = primMinusDouble
  628.     negate      = primNegDouble
  629.     (*)         = primMulDouble
  630.     abs         = absReal
  631.     signum      = signumReal
  632.     fromInteger = primIntegerToDouble
  633.     fromInt     = primIntToDouble
  634.  
  635. instance Real Float where
  636.     toRational = realFloatToRational
  637.  
  638. instance Real Double where
  639.     toRational = realFloatToRational
  640.  
  641. realFloatToRational x = (m%1)*(b%1)^^n
  642.                         where (m,n) = decodeFloat x
  643.                               b     = floatRadix x
  644.  
  645. primitive primDivFloat      "primDivFloat"      :: Float -> Float -> Float
  646. primitive primDoubleToFloat "primDoubleToFloat" :: Double -> Float
  647.  
  648. instance Fractional Float where
  649.     (/)          = primDivFloat
  650.     fromRational = rationalToRealFloat
  651.     fromDouble   = primDoubleToFloat
  652.  
  653. primitive primDivDouble   "primDivDouble" :: Double -> Double -> Double
  654.  
  655. instance Fractional Double where
  656.     (/)          = primDivDouble
  657.     fromRational = rationalToRealFloat
  658.     fromDouble x = x
  659.  
  660. rationalToRealFloat x = x'
  661.  where x'    = f e
  662.        f e   = if e' == e then y else f e'
  663.                where y      = encodeFloat (round (x * (1%b)^^e)) e
  664.                      (_,e') = decodeFloat y
  665.        (_,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
  666.                              / fromInteger (denominator x))
  667.        b     = floatRadix x'
  668.  
  669. primitive primPiFloat   "primPiFloat" :: Float
  670. primitive primSinFloat  "primSinFloat",  primAsinFloat  "primAsinFloat",
  671.           primCosFloat  "primCosFloat",  primAcosFloat  "primAcosFloat",
  672.       primTanFloat  "primTanFloat",  primAtanFloat  "primAtanFloat",
  673.           primLogFloat  "primLogFloat",  primExpFloat   "primExpFloat",
  674.       primSqrtFloat "primSqrtFloat" :: Float -> Float
  675.  
  676. instance Floating Float where
  677.     pi    = primPiFloat
  678.     exp   = primExpFloat
  679.     log   = primLogFloat
  680.     sqrt  = primSqrtFloat
  681.     sin   = primSinFloat
  682.     cos   = primCosFloat
  683.     tan   = primTanFloat
  684.     asin  = primAsinFloat
  685.     acos  = primAcosFloat
  686.     atan  = primAtanFloat
  687.  
  688. primitive primPiDouble   "primPiDouble" :: Double
  689. primitive primSinDouble  "primSinDouble",  primAsinDouble  "primAsinDouble",
  690.           primCosDouble  "primCosDouble",  primAcosDouble  "primAcosDouble",
  691.       primTanDouble  "primTanDouble",  primAtanDouble  "primAtanDouble",
  692.           primLogDouble  "primLogDouble",  primExpDouble   "primExpDouble",
  693.       primSqrtDouble "primSqrtDouble" :: Double -> Double
  694.  
  695. instance Floating Double where
  696.     pi    = primPiDouble
  697.     exp   = primExpDouble
  698.     log   = primLogDouble
  699.     sqrt  = primSqrtDouble
  700.     sin   = primSinDouble
  701.     cos   = primCosDouble
  702.     tan   = primTanDouble
  703.     asin  = primAsinDouble
  704.     acos  = primAcosDouble
  705.     atan  = primAtanDouble
  706.  
  707. instance RealFrac Float where
  708.     properFraction = floatProperFraction
  709.  
  710. instance RealFrac Double where
  711.     properFraction = floatProperFraction
  712.  
  713. floatProperFraction x
  714.    | n >= 0      = (fromInteger m * fromInteger b ^ n, 0)
  715.    | otherwise   = (fromInteger w, encodeFloat r n)
  716.                    where (m,n) = decodeFloat x
  717.                          b     = floatRadix x
  718.                          (w,r) = quotRem m (b^(-n))
  719.  
  720. primitive primFloatRadix  "primFloatRadix"  :: Float -> Integer
  721. primitive primFloatDigits "primFloatDigits" :: Float -> Int
  722. primitive primFloatRange  "primFloatRange"  :: Float -> (Int,Int)
  723. primitive primFloatEncode "primFloatEncode" :: Integer -> Int -> Float
  724. primitive primFloatDecode "primFloatDecode" :: Float -> (Integer, Int)
  725.  
  726. instance RealFloat Float where
  727.     floatRadix  = primFloatRadix
  728.     floatDigits = primFloatDigits
  729.     floatRange  = primFloatRange
  730.     encodeFloat = primFloatEncode
  731.     decodeFloat = primFloatDecode
  732.  
  733. primitive primDoubleRadix  "primDoubleRadix"  :: Double -> Integer
  734. primitive primDoubleDigits "primDoubleDigits" :: Double -> Int
  735. primitive primDoubleRange  "primDoubleRange"  :: Double -> (Int,Int)
  736. primitive primDoubleEncode "primDoubleEncode" :: Integer -> Int -> Double
  737. primitive primDoubleDecode "primDoubleDecode" :: Double -> (Integer, Int)
  738.  
  739. instance RealFloat Double where
  740.     floatRadix  = primDoubleRadix
  741.     floatDigits = primDoubleDigits
  742.     floatRange  = primDoubleRange
  743.     encodeFloat = primDoubleEncode
  744.     decodeFloat = primDoubleDecode
  745.  
  746. instance Enum Float where
  747.     enumFrom     = numericEnumFrom
  748.     enumFromThen = numericEnumFromThen
  749.  
  750. instance Enum Double where
  751.     enumFrom     = numericEnumFrom
  752.     enumFromThen = numericEnumFromThen
  753.  
  754. primitive primShowsFloat "primShowsFloat" :: Int -> Float -> ShowS
  755.  
  756. instance Text Float where
  757.     readsPrec p = readSigned readFloat
  758.     showsPrec   = primShowsFloat
  759.  
  760. primitive primShowsDouble "primShowsDouble" :: Int -> Double -> ShowS
  761.  
  762. instance Text Double where
  763.     readsPrec p = readSigned readFloat
  764.     showsPrec   = primShowsDouble
  765.  
  766. -- Lists --------------------------------------------------------------------
  767.  
  768. instance Eq a => Eq [a] where
  769.     []     == []     =  True
  770.     (x:xs) == (y:ys) =  x==y && xs==ys
  771.     _      == _      =  False
  772.  
  773. instance Ord a => Ord [a] where
  774.     []     <= _      =  True
  775.     (_:_)  <= []     =  False
  776.     (x:xs) <= (y:ys) =  x<y || (x==y && xs<=ys)
  777.  
  778. instance Text a => Text [a]  where
  779.     readsPrec p = readList
  780.     showsPrec p = showList
  781.  
  782. -- Tuples -------------------------------------------------------------------
  783.  
  784. -- data (a,b) = (a,b) deriving (Eq, Ord, Ix, Text, Binary)
  785. -- etc..
  786.  
  787. -- Functions ----------------------------------------------------------------
  788.  
  789. instance Text (a -> b) where
  790.     readsPrec p s = error "readsPrec{PreludeCore}: Cannot read functions"
  791.     showsPrec p f = showString "<<function>>"
  792.  
  793. -- Standard functions on rational numbers {PreludeRatio} --------------------
  794.  
  795. data Integral a => Ratio a = a :% a deriving (Eq, Binary)
  796. type Rational              =  Ratio Integer
  797.  
  798. (%)                       :: Integral a => a -> a -> Ratio a
  799. x % y                      = reduce (x * signum y) (abs y)
  800.  
  801. reduce                    :: Integral a => a -> a -> Ratio a
  802. reduce x y | y== 0         = error "(%){PreludeRatio}: zero denominator"
  803.            | otherwise     = (x `quot` d) :% (y `quot` d)
  804.                              where d = gcd x y
  805.  
  806. numerator, denominator    :: Integral a => Ratio a -> a
  807. numerator (x :% y)         = x
  808. denominator (x :% y)       = y
  809.  
  810. instance Integral a => Ord (Ratio a) where
  811.     ordcmp (x:%y) (x':%y') = ordcmp (x*y') (x'*y)
  812.  
  813. instance Integral a => Num (Ratio a) where
  814.     (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
  815.     (x:%y) * (x':%y') = reduce (x*x') (y*y')
  816.     negate (x :% y)   = negate x :% y
  817.     abs (x :% y)      = abs x :% y
  818.     signum (x :% y)   = signum x :% 1
  819.     fromInteger x     = fromInteger x :% 1
  820.     fromInt x         = fromInt x :% 1
  821.  
  822. instance Integral a => Real (Ratio a) where
  823.     toRational (x:%y) = toInteger x :% toInteger y
  824.  
  825. instance Integral a => Fractional (Ratio a) where
  826.     (x:%y) / (x':%y')   = (x*y') % (y*x')
  827.     recip (x:%y)        = if x < 0 then (-y) :% (-x) else y :% x
  828.     fromRational (x:%y) = fromInteger x :% fromInteger y
  829.     fromDouble x
  830.             | n>=0      = (fromInteger m * fromInteger b ^ n) % 1
  831.             | otherwise = fromInteger m % (fromInteger b ^ (-n))
  832.                           where (m,n) = decodeFloat x
  833.                                 b     = floatRadix x
  834.  
  835. instance Integral a => RealFrac (Ratio a) where
  836.     properFraction (x:%y) = (fromIntegral q, r:%y)
  837.                 where (q,r) = quotRem x y
  838.  
  839. instance Integral a => Enum (Ratio a) where
  840.     enumFrom     = numericEnumFrom
  841.     enumFromThen = numericEnumFromThen
  842.  
  843. instance Integral a => Text (Ratio a) where
  844.     readsPrec p        = readParen (p > 7)
  845.                                    (\r -> [(x%y,u) | (x,s)   <- reads r,
  846.                                                      ("%",t) <- lex s,
  847.                                                      (y,u)   <- reads t ])
  848.     showsPrec p (x:%y) = showParen (p > 7)
  849.                              (shows x . showString " % " . shows y)
  850.  
  851. approxRational      :: RealFrac a => a -> a -> Rational
  852. approxRational x eps = simplest (x-eps) (x+eps)
  853.  where simplest x y | y < x     = simplest y x
  854.                     | x == y    = xr
  855.                     | x > 0     = simplest' n d n' d'
  856.                     | y < 0     = - simplest' (-n') d' (-n) d
  857.                     | otherwise = 0 :% 1
  858.                   where xr@(n:%d) = toRational x
  859.                     (n':%d')  = toRational y
  860.        simplest' n d n' d'        -- assumes 0 < n%d < n'%d'
  861.             | r == 0    = q :% 1
  862.             | q /= q'   = (q+1) :% 1
  863.                     | otherwise = (q*n''+d'') :% n''
  864.                   where (q,r)       = quotRem n d
  865.                     (q',r')       = quotRem n' d'
  866.                     (n'':%d'') = simplest' d' r' d r
  867.  
  868. -- Complex numbers {PreludeComplex} -----------------------------------------
  869.  
  870. data RealFloat a => Complex a = a :+ a deriving (Eq, Binary, Text)
  871.  
  872. instance RealFloat a => Num (Complex a) where
  873.     (x:+y) + (x':+y')  = (x+x') :+ (y+y')
  874.     (x:+y) - (x':+y')  = (x-x') :+ (y-y')
  875.     (x:+y) * (x':+y')  = (x*x'-y*y') :+ (x*y'+y*x')
  876.     negate (x:+y)      = negate x :+ negate y
  877.     abs z              = magnitude z :+ 0
  878.     signum 0           = 0
  879.     signum z@(x:+y)    = x/r :+ y/r where r = magnitude z
  880.     fromInteger n      = fromInteger n :+ 0
  881.     fromInt n          = fromInt n :+ 0
  882.  
  883. instance RealFloat a => Fractional (Complex a) where
  884.     (x:+y) / (x':+y')  = (x*x''+y*y'')/d :+ (y*x''-x*y'')/d
  885.              where x'' = scaleFloat k x'
  886.                    y'' = scaleFloat k y'
  887.                    k   = - max (exponent x') (exponent y')
  888.                    d   = x'*x'' + y'*y''
  889.     fromRational a     = fromRational a :+ 0
  890.     fromDouble a       = fromDouble a :+ 0
  891.  
  892. instance RealFloat a => Floating (Complex a) where
  893.     pi            = pi :+ 0
  894.     exp (x:+y)    = expx * cos y :+ expx * sin y
  895.                     where expx = exp x
  896.     log z         = log (magnitude z) :+ phase z
  897.     sqrt 0        = 0
  898.     sqrt z@(x:+y) = u :+ (if y < 0 then -v else v)
  899.             where (u,v) = if x<0 then (v',u') else (u',v')
  900.               v'    = abs y / (u'*2)
  901.               u'    = sqrt ((magnitude z + abs x) / 2)
  902.     sin (x:+y)    = sin x * cosh y :+ cos x * sinh y
  903.     cos (x:+y)    = cos x * cosh y :+ (- sin x * sinh y)
  904.     tan (x:+y)    = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))
  905.             where sinx  = sin x
  906.               cosx    = cos x
  907.               sinhy = sinh y
  908.               coshy = cosh y
  909.     sinh (x:+y)   = sinh x * cos y :+ cosh x * sin y
  910.     cosh (x:+y)   = cosh x * cos y :+ sinh x * sin y
  911.     tanh (x:+y)   = (sinhx*cosy:+coshx*siny)/(coshx*cosy:+sinhx*siny)
  912.             where siny  = sin y
  913.               cosy    = cos y
  914.               sinhx = sinh x
  915.               coshx = cosh x
  916.     asin z@(x:+y) = y' :+ (-x')
  917.                     where (x':+y') = log ((-y:+x) + sqrt (1 - z*z))
  918.     acos z@(x:+y) = y'':+(-x'')
  919.             where (x'':+y'') = log (z + ((-y'):+x'))
  920.               (x' :+ y') = sqrt (1 - z*z)
  921.     atan z@(x:+y) = y' :+ (-x')
  922.                     where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))
  923.     asinh z       = log (z + sqrt (1+z*z))
  924.     acosh z       = log (z + (z+1) * sqrt ((z-1)/(z+1)))
  925.     atanh z       = log ((1+z) / sqrt (1 - z*z))
  926.  
  927. realPart, imagPart :: RealFloat a => Complex a -> a
  928. realPart (x :+ y)   = x
  929. imagPart (x :+ y)   = y
  930.  
  931. conjugate          :: RealFloat a => Complex a -> Complex a
  932. conjugate (x :+ y)  = x :+ (-y)
  933.  
  934. mkPolar            :: RealFloat a => a -> a -> Complex a
  935. mkPolar r theta     = r * cos theta :+ r * sin theta
  936.  
  937. cis                :: RealFloat a => a -> Complex a
  938. cis theta           = cos theta :+ sin theta
  939.  
  940. polar              :: RealFloat a => Complex a -> (a, a)
  941. polar z             = (magnitude z, phase z)
  942.  
  943. magnitude, phase   :: RealFloat a => Complex a -> a
  944. magnitude (x :+ y)  = scaleFloat k
  945.                        (sqrt ((scaleFloat mk x)^2 + (scaleFloat mk y)^2))
  946.                       where k  = max (exponent x) (exponent y)
  947.                             mk = -k
  948. phase (x :+ y)      = atan2 y x
  949.  
  950. -- Standard list functions {PreludeList} ------------------------------------
  951.  
  952. head             :: [a] -> a
  953. head (x:_)        = x
  954.  
  955. last             :: [a] -> a
  956. last [x]          = x
  957. last (_:xs)       = last xs
  958.  
  959. tail             :: [a] -> [a]
  960. tail (_:xs)       = xs
  961.  
  962. init             :: [a] -> [a]
  963. init [x]          = []
  964. init (x:xs)       = x : init xs
  965.  
  966. -- null provides a simple and efficient way of determining whether a given
  967. -- list is empty, without using (==) and hence avoiding an Eq a constraint.
  968. null             :: [a] -> Bool
  969. null []           = True
  970. null (_:_)        = False
  971.  
  972. (++)             :: [a] -> [a] -> [a]    -- append lists.  Associative with
  973. []     ++ ys      = ys                   -- left and right identity [].
  974. (x:xs) ++ ys      = x:(xs++ys)
  975.  
  976. -- (\\) is used to remove the first occurrence of each element in the second
  977. -- list from the first list.  It is a kind of inverse of (++) in the sense
  978. -- that  (xs ++ ys) \\ xs = ys for any finite list xs of proper values xs.
  979. (\\)             :: Eq a => [a] -> [a] -> [a]
  980. (\\)              = foldl del
  981.                     where []     `del` _  = []
  982.                           (x:xs) `del` y
  983.                              | x == y     = xs
  984.                              | otherwise  = x : xs `del` y
  985.  
  986. -- length returns the length of a finite list as an Int; it is an instance
  987. -- of the more general genericLength, the result type of which may be
  988. -- any kind of number
  989.  
  990. genericLength    :: Num a => [b] -> a
  991. genericLength     = foldl' (\n _ -> n + 1) 0
  992.  
  993. length         :: [a] -> Int
  994. length            = genericLength
  995.  
  996. -- List index (subscript) operator, 0-origin
  997. (!!)             :: (Integral a) => [b] -> a -> b
  998. (x:_)  !! 0       = x
  999. (_:xs) !! (n+1)   = xs !! n
  1000.  
  1001. -- map f xs applies the function f to each element of the list xs returning
  1002. -- the corresponding list of results.  filter p xs returns the sublist of xs
  1003. -- containing those elements which satisfy the predicate p.
  1004.  
  1005. map              :: (a -> b) -> [a] -> [b]
  1006. map f []          = []
  1007. map f (x:xs)      = f x : map f xs
  1008.  
  1009. filter           :: (a -> Bool) -> [a] -> [a]
  1010. filter p          = foldr (\x xs -> if p x then x:xs else xs) []
  1011.  
  1012. -- partition takes a predicate and a list and returns a pair of lists:
  1013. -- those elements of the argument list that do and do not satisfy the
  1014. -- predicate, respectively.
  1015. partition        :: (a -> Bool) -> [a] -> ([a],[a])
  1016. partition p       = foldr select ([],[])
  1017.                     where select x (ts,fs) | p x       = (x:ts,fs)
  1018.                                            | otherwise = (ts,x:fs)
  1019.  
  1020. -- Fold primitives:  The foldl and scanl functions, variants foldl1 and
  1021. -- scanl1 for non-empty lists, and strict variants foldl' scanl' describe
  1022. -- common patterns of recursion over lists.  Informally:
  1023. --
  1024. --  foldl f a [x1, x2, ..., xn]  = f (...(f (f a x1) x2)...) xn
  1025. --                               = (...((a `f` x1) `f` x2)...) `f` xn
  1026. -- etc...
  1027. --
  1028. -- The functions foldr, scanr and variants foldr1, scanr1 are duals of these
  1029. -- functions:
  1030. -- e.g.  foldr f a xs = foldl (flip f) a (reverse xs)  for finite lists xs.
  1031.  
  1032. foldl            :: (a -> b -> a) -> a -> [b] -> a
  1033. foldl f z []      = z
  1034. foldl f z (x:xs)  = foldl f (f z x) xs
  1035.  
  1036. foldl'           :: (a -> b -> a) -> a -> [b] -> a
  1037. foldl' f a []     =  a
  1038. foldl' f a (x:xs) =  strict (foldl' f) (f a x) xs
  1039.  
  1040. foldl1           :: (a -> a -> a) -> [a] -> a
  1041. foldl1 f (x:xs)   = foldl f x xs
  1042.  
  1043. scanl            :: (a -> b -> a) -> a -> [b] -> [a]
  1044. scanl f q xs      = q : (case xs of
  1045.                          []   -> []
  1046.                          x:xs -> scanl f (f q x) xs)
  1047.  
  1048. scanl1           :: (a -> a -> a) -> [a] -> [a]
  1049. scanl1 f (x:xs)   = scanl f x xs
  1050.  
  1051. foldr            :: (a -> b -> b) -> b -> [a] -> b
  1052. foldr f z []      = z
  1053. foldr f z (x:xs)  = f x (foldr f z xs)
  1054.  
  1055. foldr1           :: (a -> a -> a) -> [a] -> a
  1056. foldr1 f [x]      = x
  1057. foldr1 f (x:xs)   = f x (foldr1 f xs)
  1058.  
  1059. scanr            :: (a -> b -> b) -> b -> [a] -> [b]
  1060. scanr f q0 []     = [q0]
  1061. scanr f q0 (x:xs) = f x q : qs
  1062.                     where qs@(q:_) = scanr f q0 xs
  1063.  
  1064. scanr1           :: (a -> a -> a) -> [a] -> [a]
  1065. scanr1 f [x]      = [x]
  1066. scanr1 f (x:xs)   = f x q : qs
  1067.                     where qs@(q:_) = scanr1 f xs
  1068.  
  1069. iterate          :: (a -> a) -> a -> [a] -- generate the infinite list
  1070. iterate f x       = x : iterate f (f x)  -- [x, f x, f (f x), ...
  1071.  
  1072. repeat           :: a -> [a]             -- generate the infinite list
  1073. repeat x          = xs where xs = x:xs   -- [x, x, x, x, ...
  1074.  
  1075. cycle            :: [a] -> [a]           -- generate the infinite list
  1076. cycle xs          = xs' where xs'=xs++xs'-- xs ++ xs ++ xs ++ ...
  1077.  
  1078. -- List breaking functions:
  1079. --
  1080. --   take n xs       returns the first n elements of xs
  1081. --   drop n xs       returns the remaining elements of xs
  1082. --   splitAt n xs    = (take n xs, drop n xs)
  1083. --
  1084. --   takeWhile p xs  returns the longest initial segment of xs whose
  1085. --                   elements satisfy p
  1086. --   dropWhile p xs  returns the remaining portion of the list
  1087. --   span p xs       = (takeWhile p xs, dropWhile p xs)
  1088. --
  1089. --   takeUntil p xs  returns the list of elements upto and including the
  1090. --                   first element of xs which satisfies p
  1091.  
  1092. take                :: Integral a => a -> [b] -> [b]
  1093. take 0     _         = []
  1094. take _     []        = []
  1095. take (n+1) (x:xs)    = x : take n xs
  1096.  
  1097. drop                :: Integral a => a -> [b] -> [b]
  1098. drop 0     xs        = xs
  1099. drop _     []        = []
  1100. drop (n+1) (_:xs)    = drop n xs
  1101.  
  1102. splitAt             :: Integral a => a -> [b] -> ([b], [b])
  1103. splitAt 0     xs     = ([],xs)
  1104. splitAt _     []     = ([],[])
  1105. splitAt (n+1) (x:xs) = (x:xs',xs'') where (xs',xs'') = splitAt n xs
  1106.  
  1107. takeWhile           :: (a -> Bool) -> [a] -> [a]
  1108. takeWhile p []       = []
  1109. takeWhile p (x:xs)
  1110.          | p x       = x : takeWhile p xs
  1111.          | otherwise = []
  1112.  
  1113. dropWhile           :: (a -> Bool) -> [a] -> [a]
  1114. dropWhile p []       = []
  1115. dropWhile p xs@(x:xs')
  1116.          | p x       = dropWhile p xs'
  1117.          | otherwise = xs
  1118.  
  1119. span, break         :: (a -> Bool) -> [a] -> ([a],[a])
  1120. span p []            = ([],[])
  1121. span p xs@(x:xs')
  1122.          | p x       = let (ys,zs) = span p xs' in (x:ys,zs)
  1123.          | otherwise = ([],xs)
  1124. break p              = span (not . p)
  1125.  
  1126. -- Text processing:
  1127. --   lines s     returns the list of lines in the string s.
  1128. --   words s     returns the list of words in the string s.
  1129. --   unlines ls  joins the list of lines ls into a single string
  1130. --               with lines separated by newline characters.
  1131. --   unwords ws  joins the list of words ws into a single string
  1132. --               with words separated by spaces.
  1133.  
  1134. lines     :: String -> [String]
  1135. lines ""   = []
  1136. lines s    = l : (if null s' then [] else lines (tail s'))
  1137.              where (l, s') = break ('\n'==) s
  1138.  
  1139. words     :: String -> [String]
  1140. words s    = case dropWhile isSpace s of
  1141.                   "" -> []
  1142.                   s' -> w : words s''
  1143.                         where (w,s'') = break isSpace s'
  1144.  
  1145. unlines   :: [String] -> String
  1146. unlines    = concat . map (\l -> l ++ "\n")
  1147.  
  1148. unwords   :: [String] -> String
  1149. unwords [] = []
  1150. unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
  1151.  
  1152. nub              :: Eq a => [a] -> [a]   -- remove duplicates from list
  1153. nub []            = []
  1154. nub (x:xs)        = x : nub (filter (x/=) xs)
  1155.  
  1156. reverse          :: [a] -> [a]           -- reverse elements of list
  1157. reverse           = foldl (flip (:)) []
  1158.  
  1159. and, or        :: [Bool] -> Bool
  1160. and             = foldr (&&) True     -- returns conjunction of boolean list
  1161. or              = foldr (||) False     -- returns disjunction of boolean list
  1162.  
  1163. any, all       :: (a -> Bool) -> [a] -> Bool
  1164. any p           = or  . map p
  1165. all p           = and . map p
  1166.  
  1167. elem, notElem    :: Eq a => a -> [a] -> Bool
  1168. elem              = any . (==)           -- test for membership in list
  1169. notElem           = all . (/=)           -- test for non-membership
  1170.  
  1171. sum, product     :: Num a => [a] -> a
  1172. sum               = foldl' (+) 0
  1173. product           = foldl' (*) 1
  1174.  
  1175. sums, products     :: Num a => [a] -> [a]
  1176. sums              = scanl (+) 0
  1177. products          = scanl (*) 1
  1178.  
  1179. maximum, minimum :: Ord a => [a] -> a
  1180. maximum           = foldl1 max          -- max element in non-empty list
  1181. minimum           = foldl1 min          -- min element in non-empty list
  1182.  
  1183. concat           :: [[a]] -> [a]        -- concatenate list of lists
  1184. concat            = foldr (++) []
  1185.  
  1186. transpose        :: [[a]] -> [[a]]      -- transpose list of lists
  1187. transpose         = foldr
  1188.                       (\xs xss -> zipWith (:) xs (xss ++ repeat []))
  1189.                       []
  1190.  
  1191. -- zip and zipWith families of functions:
  1192.  
  1193. zip  :: [a] -> [b] -> [(a,b)]
  1194. zip   = zipWith  (\a b -> (a,b))
  1195.  
  1196. zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
  1197. zip3  = zipWith3 (\a b c -> (a,b,c))
  1198.  
  1199. zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
  1200. zip4  = zipWith4 (\a b c d -> (a,b,c,d))
  1201.  
  1202. zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
  1203. zip5  = zipWith5 (\a b c d e -> (a,b,c,d,e))
  1204.  
  1205. zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a,b,c,d,e,f)]
  1206. zip6  = zipWith6 (\a b c d e f -> (a,b,c,d,e,f))
  1207.  
  1208. zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a,b,c,d,e,f,g)]
  1209. zip7  = zipWith7 (\a b c d e f g -> (a,b,c,d,e,f,g))
  1210.  
  1211. zipWith                  :: (a->b->c) -> [a]->[b]->[c]
  1212. zipWith z (a:as) (b:bs)   = z a b : zipWith z as bs
  1213. zipWith _ _      _        = []
  1214.  
  1215. zipWith3                 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
  1216. zipWith3 z (a:as) (b:bs) (c:cs)
  1217.                           = z a b c : zipWith3 z as bs cs
  1218. zipWith3 _ _ _ _          = []
  1219.  
  1220. zipWith4                 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
  1221. zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
  1222.                           = z a b c d : zipWith4 z as bs cs ds
  1223. zipWith4 _ _ _ _ _        = []
  1224.  
  1225. zipWith5                 :: (a->b->c->d->e->f) -> [a]->[b]->[c]->[d]->[e]->[f]
  1226. zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
  1227.                           = z a b c d e : zipWith5 z as bs cs ds es
  1228. zipWith5 _ _ _ _ _ _      = []
  1229.  
  1230. zipWith6                 :: (a->b->c->d->e->f->g)
  1231.                             -> [a]->[b]->[c]->[d]->[e]->[f]->[g]
  1232. zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
  1233.                           = z a b c d e f : zipWith6 z as bs cs ds es fs
  1234. zipWith6 _ _ _ _ _ _ _    = []
  1235.  
  1236. zipWith7                 :: (a->b->c->d->e->f->g->h)
  1237.                              -> [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
  1238. zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
  1239.                           = z a b c d e f g : zipWith7 z as bs cs ds es fs gs
  1240. zipWith7 _ _ _ _ _ _ _ _  = []
  1241.  
  1242. unzip                    :: [(a,b)] -> ([a],[b])
  1243. unzip                     = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
  1244.  
  1245. unzip3                   :: [(a,b,c)] -> ([a],[b],[c])
  1246. unzip3                    = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
  1247.                                   ([],[],[])
  1248.  
  1249. unzip4                   :: [(a,b,c,d)] -> ([a],[b],[c],[d])
  1250. unzip4                    = foldr (\(a,b,c,d) ~(as,bs,cs,ds) ->
  1251.                                        (a:as,b:bs,c:cs,d:ds))
  1252.                                   ([],[],[],[])
  1253.  
  1254. unzip5                   :: [(a,b,c,d,e)] -> ([a],[b],[c],[d],[e])
  1255. unzip5                    = foldr (\(a,b,c,d,e) ~(as,bs,cs,ds,es) ->
  1256.                                        (a:as,b:bs,c:cs,d:ds,e:es))
  1257.                                   ([],[],[],[],[])
  1258.  
  1259. unzip6                   :: [(a,b,c,d,e,f)] -> ([a],[b],[c],[d],[e],[f])
  1260. unzip6                    = foldr (\(a,b,c,d,e,f) ~(as,bs,cs,ds,es,fs) ->
  1261.                                        (a:as,b:bs,c:cs,d:ds,e:es,f:fs))
  1262.                                   ([],[],[],[],[],[])
  1263.  
  1264. unzip7                   :: [(a,b,c,d,e,f,g)] -> ([a],[b],[c],[d],[e],[f],[g])
  1265. unzip7                    = foldr (\(a,b,c,d,e,f,g) ~(as,bs,cs,ds,es,fs,gs) ->
  1266.                                        (a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs))
  1267.                                   ([],[],[],[],[],[],[])
  1268.  
  1269. -- Standard array functions {PreludeArray} ----------------------------------
  1270.  
  1271. data Assoc a b =  a := b deriving (Eq, Ord, Ix, Text, Binary)
  1272.  
  1273. array      :: Ix a => (a,a) -> [Assoc a b] -> Array a b
  1274. listArray  :: Ix a => (a,a) -> [b] -> Array a b
  1275. (!)       :: Ix a => Array a b -> a -> b
  1276. bounds     :: Ix a => Array a b -> (a,a)
  1277. indices       :: Ix a => Array a b -> [a]
  1278. elems      :: Ix a => Array a b -> [b]
  1279. assocs       :: Ix a => Array a b -> [Assoc a b]
  1280. accumArray :: Ix a => (b -> c -> b) -> b -> (a,a) -> [Assoc a c] -> Array a b
  1281. (//)       :: Ix a => Array a b -> [Assoc a b] -> Array a b
  1282. accum      :: Ix a => (b -> c -> b) -> Array a b -> [Assoc a c] -> Array a b
  1283. amap       :: Ix a => (b -> c) -> Array a b -> Array a c
  1284. ixmap       :: (Ix a, Ix b) => (a,a) -> (a -> b) -> Array b c -> Array a c
  1285.  
  1286. primitive primArray "primArray"
  1287.     :: (a -> Int) -> (a,a) -> [Assoc a b] -> Array a b
  1288. primitive primUpdate "primUpdate"
  1289.     :: (a -> Int) -> Array a b -> [Assoc a b] -> Array a b
  1290. primitive primAccum "primAccum"
  1291.     :: (a -> Int) -> (b -> c -> b) -> Array a b -> [Assoc a c] -> Array a b
  1292. primitive primAccumArray "primAccumArray"
  1293.     :: (a -> Int) -> (b -> c -> b) -> b -> (a,a) -> [Assoc a c] -> Array a b
  1294. primitive primBounds    "primBounds"    :: Array a b -> (a,a)
  1295. primitive primElems     "primElems"     :: Array a b -> [b]
  1296. primitive primSubscript "primSubscript" :: (a -> Int) -> Array a b -> a -> b
  1297. primitive primAmap      "primAmap"    :: (b -> c) -> Array a b -> Array a c
  1298.  
  1299. array bounds assocs = primArray (index bounds) bounds assocs
  1300. listArray b vs        = array b (zipWith (:=) (range b) vs)
  1301. (!) a               = primSubscript (index (bounds a)) a 
  1302. bounds              = primBounds
  1303. indices            = range . bounds
  1304. elems               = primElems
  1305. assocs a            = zipWith (:=) (indices a) (elems a)
  1306. accumArray f z b    = primAccumArray (index b) f z b
  1307. a // as             = primUpdate (index (bounds a)) a as
  1308. accum f a           = primAccum (index (bounds a)) f a
  1309. amap                = primAmap
  1310. ixmap b f a         = array b [ i := (a ! f i) | i <- range b ]
  1311.  
  1312. instance (Ix a, Eq b) => Eq (Array a b) where
  1313.     a == a'   =   assocs a == assocs a'
  1314.  
  1315. instance (Ix a, Ord b) => Ord (Array a b) where
  1316.     a <= a'   =   assocs a <= assocs a'
  1317.  
  1318. instance (Ix a, Text a, Text b) => Text (Array a b) where
  1319.     showsPrec p a = showParen (p > 9) (
  1320.                        showString "array " .
  1321.                        shows (bounds a)    .
  1322.                        showChar ' '        .
  1323.                        shows (assocs a))
  1324.  
  1325. instance (Ix a, Binary a, Binary b) => Binary (Array a b)
  1326.  
  1327. rangeSize        :: (Ix a) => (a,a) -> Int
  1328. rangeSize r@(l,u) = index r u + 1
  1329.  
  1330. -- PreludeText ----------------------------------------------------------------
  1331.  
  1332. reads        :: Text a => ReadS a
  1333. reads         = readsPrec 0
  1334.  
  1335. shows        :: Text a => a -> ShowS
  1336. shows         = showsPrec 0
  1337.  
  1338. read         :: Text a => String -> a
  1339. read s        =  case [x | (x,t) <- reads s, ("","") <- lex t] of
  1340.                       [x] -> x
  1341.                       []  -> error "read{PreludeText}: no parse"
  1342.                       _   -> error "read{PreludeText}: ambiguous parse"
  1343.  
  1344. show         :: Text a => a -> String
  1345. show x        = shows x ""
  1346.  
  1347. showChar     :: Char -> ShowS
  1348. showChar      = (:)
  1349.  
  1350. showString   :: String -> ShowS
  1351. showString    = (++)
  1352.  
  1353. showParen    :: Bool -> ShowS -> ShowS
  1354. showParen b p = if b then showChar '(' . p . showChar ')' else p
  1355.  
  1356. readParen    :: Bool -> ReadS a -> ReadS a
  1357. readParen b g = if b then mandatory else optional
  1358.                 where optional r  = g r ++ mandatory r
  1359.                       mandatory r = [(x,u) | ("(",s) <- lex r,
  1360.                                              (x,t)   <- optional s,
  1361.                                              (")",u) <- lex t    ]
  1362.  
  1363. lex                     :: ReadS String
  1364. lex ""                  = [("","")]
  1365. lex (c:s) | isSpace c   = lex (dropWhile isSpace s)
  1366. lex ('-':'-':s)         = case dropWhile (/= '\n') s of
  1367.                                  '\n':t -> lex t
  1368.                                  _      -> [] -- unterminated end-of-line
  1369.                                               -- comment
  1370.  
  1371. lex ('{':'-':s)         = lexNest lex s
  1372.                           where
  1373.                           lexNest f ('-':'}':s) = f s
  1374.                           lexNest f ('{':'-':s) = lexNest (lexNest f) s
  1375.                           lexNest f (c:s)             = lexNest f s
  1376.                           lexNest _ ""          = [] -- unterminated
  1377.                                                      -- nested comment
  1378.  
  1379. lex ('<':'-':s)         = [("<-",s)]
  1380. lex ('\'':s)            = [('\'':ch++"'", t) | (ch,'\'':t)  <- lexLitChar s,
  1381.                                                ch /= "'"                ]
  1382. lex ('"':s)             = [('"':str, t)      | (str,t) <- lexString s]
  1383.                           where
  1384.                           lexString ('"':s) = [("\"",s)]
  1385.                           lexString s = [(ch++str, u)
  1386.                                                 | (ch,t)  <- lexStrItem s,
  1387.                                                   (str,u) <- lexString t  ]
  1388.  
  1389.                           lexStrItem ('\\':'&':s) = [("\\&",s)]
  1390.                           lexStrItem ('\\':c:s) | isSpace c
  1391.                               = [("\\&",t) | '\\':t <- [dropWhile isSpace s]]
  1392.                           lexStrItem s            = lexLitChar s
  1393.  
  1394. lex (c:s) | isSingle c  = [([c],s)]
  1395.           | isSym1 c    = [(c:sym,t)         | (sym,t) <- [span isSym s]]
  1396.           | isAlpha c   = [(c:nam,t)         | (nam,t) <- [span isIdChar s]]
  1397.           | isDigit c   = [(c:ds++fe,t)      | (ds,s)  <- [span isDigit s],
  1398.                                                (fe,t)  <- lexFracExp s     ]
  1399.           | otherwise   = []    -- bad character
  1400.                 where
  1401.                 isSingle c  =  c `elem` ",;()[]{}_"
  1402.                 isSym1 c    =  c `elem` "-~" || isSym c
  1403.                 isSym c     =  c `elem` "!@#$%&*+./<=>?\\^|:"
  1404.                 isIdChar c  =  isAlphanum c || c `elem` "_'"
  1405.  
  1406.                 lexFracExp ('.':s) = [('.':ds++e,u) | (ds,t) <- lexDigits s,
  1407.                                                       (e,u)  <- lexExp t    ]
  1408.                 lexFracExp s       = [("",s)]
  1409.  
  1410.                 lexExp (e:s) | e `elem` "eE"
  1411.                          = [(e:c:ds,u) | (c:t)  <- [s], c `elem` "+-",
  1412.                                                    (ds,u) <- lexDigits t] ++
  1413.                            [(e:ds,t)   | (ds,t) <- lexDigits s]
  1414.                 lexExp s = [("",s)]
  1415.  
  1416. lexDigits               :: ReadS String
  1417. lexDigits               =  nonnull isDigit
  1418.  
  1419. nonnull                 :: (Char -> Bool) -> ReadS String
  1420. nonnull p s             =  [(cs,t) | (cs@(_:_),t) <- [span p s]]
  1421.  
  1422. lexLitChar              :: ReadS String
  1423. lexLitChar ('\\':s)     =  [('\\':esc, t) | (esc,t) <- lexEsc s]
  1424.         where
  1425.         lexEsc (c:s)     | c `elem` "abfnrtv\\\"'" = [([c],s)]
  1426.         lexEsc ('^':c:s) | c >= '@' && c <= '_'  = [(['^',c],s)]
  1427.         lexEsc s@(d:_)   | isDigit d             = lexDigits s
  1428.         lexEsc ('o':s)  =  [('o':os, t) | (os,t) <- nonnull isOctDigit s]
  1429.         lexEsc ('x':s)  =  [('x':xs, t) | (xs,t) <- nonnull isHexDigit s]
  1430.         lexEsc s@(c:_)   | isUpper c
  1431.                         =  case [(mne,s') | mne <- "DEL" : elems asciiTab,
  1432.                                             ([],s') <- [lexmatch mne s]      ]
  1433.                            of (pr:_) -> [pr]
  1434.                               []     -> []
  1435.         lexEsc _        =  []
  1436. lexLitChar (c:s)        =  [([c],s)]
  1437. lexLitChar ""           =  []
  1438.  
  1439. isOctDigit c  =  c >= '0' && c <= '7'
  1440. isHexDigit c  =  isDigit c || c >= 'A' && c <= 'F'
  1441.                            || c >= 'a' && c <= 'f'
  1442.  
  1443. lexmatch                   :: (Eq a) => [a] -> [a] -> ([a],[a])
  1444. lexmatch (x:xs) (y:ys) | x == y  =  lexmatch xs ys
  1445. lexmatch xs     ys               =  (xs,ys)
  1446.  
  1447. asciiTab = listArray ('\NUL', ' ')
  1448.            ["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
  1449.             "BS",  "HT",  "LF",  "VT",  "FF",  "CR",  "SO",  "SI",
  1450.             "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
  1451.             "CAN", "EM",  "SUB", "ESC", "FS",  "GS",  "RS",  "US",
  1452.             "SP"]
  1453.  
  1454. readLitChar             :: ReadS Char
  1455. readLitChar ('\\':s)    =  readEsc s
  1456.  where
  1457.        readEsc ('a':s)  = [('\a',s)]
  1458.        readEsc ('b':s)  = [('\b',s)]
  1459.        readEsc ('f':s)  = [('\f',s)]
  1460.        readEsc ('n':s)  = [('\n',s)]
  1461.        readEsc ('r':s)  = [('\r',s)]
  1462.        readEsc ('t':s)  = [('\t',s)]
  1463.        readEsc ('v':s)  = [('\v',s)]
  1464.        readEsc ('\\':s) = [('\\',s)]
  1465.        readEsc ('"':s)  = [('"',s)]
  1466.        readEsc ('\'':s) = [('\'',s)]
  1467.        readEsc ('^':c:s) | c >= '@' && c <= '_'
  1468.                         = [(chr (ord c - ord '@'), s)]
  1469.        readEsc s@(d:_) | isDigit d
  1470.                         = [(chr n, t) | (n,t) <- readDec s]
  1471.        readEsc ('o':s)  = [(chr n, t) | (n,t) <- readOct s]
  1472.        readEsc ('x':s)  = [(chr n, t) | (n,t) <- readHex s]
  1473.        readEsc s@(c:_) | isUpper c
  1474.                         = let table = ('\DEL':= "DEL") : assocs asciiTab
  1475.                           in case [(c,s') | (c := mne) <- table,
  1476.                                             ([],s') <- [lexmatch mne s]]
  1477.                              of (pr:_) -> [pr]
  1478.                                 []     -> []
  1479.        readEsc _        = []
  1480. readLitChar (c:s)       =  [(c,s)]
  1481.  
  1482. showLitChar               :: Char -> ShowS
  1483. showLitChar c | c > '\DEL' = showChar '\\' . protectEsc isDigit (shows (ord c))
  1484. showLitChar '\DEL'         = showString "\\DEL"
  1485. showLitChar '\\'           = showString "\\\\"
  1486. showLitChar c | c >= ' '   = showChar c
  1487. showLitChar '\a'           = showString "\\a"
  1488. showLitChar '\b'           = showString "\\b"
  1489. showLitChar '\f'           = showString "\\f"
  1490. showLitChar '\n'           = showString "\\n"
  1491. showLitChar '\r'           = showString "\\r"
  1492. showLitChar '\t'           = showString "\\t"
  1493. showLitChar '\v'           = showString "\\v"
  1494. showLitChar '\SO'          = protectEsc ('H'==) (showString "\\SO")
  1495. showLitChar c              = showString ('\\' : asciiTab!c)
  1496.  
  1497. protectEsc p f             = f . cont
  1498.  where cont s@(c:_) | p c  = "\\&" ++ s
  1499.        cont s              = s
  1500.  
  1501. readDec, readOct, readHex :: Integral a => ReadS a
  1502. readDec = readInt 10 isDigit (\d -> ord d - ord '0')
  1503. readOct = readInt  8 isOctDigit (\d -> ord d - ord '0')
  1504. readHex = readInt 16 isHexDigit hex
  1505.             where hex d = ord d - (if isDigit d then ord '0'
  1506.                                    else ord (if isUpper d then 'A' else 'a')
  1507.                                         - 10)
  1508.  
  1509. readInt :: Integral a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
  1510. readInt radix isDig digToInt s =
  1511.     [(foldl1 (\n d -> n * radix + d) (map (fromIntegral . digToInt) ds), r)
  1512.         | (ds,r) <- nonnull isDig s ]
  1513.  
  1514. showInt    :: Integral a => a -> ShowS
  1515. showInt n r = let (n',d) = quotRem n 10
  1516.                   r'     = chr (ord '0' + fromIntegral d) : r
  1517.               in  if n' == 0 then r' else showInt n' r'
  1518.  
  1519. readSigned:: Real a => ReadS a -> ReadS a
  1520. readSigned readPos = readParen False read'
  1521.                      where read' r  = read'' r ++
  1522.                                       [(-x,t) | ("-",s) <- lex r,
  1523.                                                 (x,t)   <- read'' s]
  1524.                            read'' r = [(n,s)  | (str,s) <- lex r,
  1525.                                                 (n,"")  <- readPos str]
  1526.  
  1527. showSigned    :: Real a => (a -> ShowS) -> Int -> a -> ShowS
  1528. showSigned showPos p x = if x < 0 then showParen (p > 6)
  1529.                                                  (showChar '-' . showPos (-x))
  1530.                                   else showPos x
  1531.  
  1532. readFloat     :: RealFloat a => ReadS a
  1533. readFloat r    = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r,
  1534.                                (k,t)   <- readExp s]
  1535.                  where readFix r = [(read (ds++ds'), length ds', t)
  1536.                     | (ds,'.':s) <- lexDigits r,
  1537.                       (ds',t)    <- lexDigits s ]
  1538.  
  1539.                readExp (e:s) | e `elem` "eE" = readExp' s
  1540.                readExp s                     = [(0,s)]
  1541.  
  1542.                readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s]
  1543.                readExp' ('+':s) = readDec s
  1544.                readExp' s       = readDec s
  1545.  
  1546. showFloat     :: RealFloat a => a -> ShowS
  1547. showFloat x    = if x==0 then showString ("0." ++ take (m-1) (repeat '0'))
  1548.                          else if e >= m-1 || e < 0 then showSci else showFix
  1549.  where showFix     = showString whole . showChar '.' . showString frac
  1550.            where (whole,frac) = splitAt (e+1) (show sig)
  1551.        showSci     = showChar d . showChar '.' . showString frac
  1552.             . showChar 'e' . shows e
  1553.            where (d:frac) = show sig
  1554.        (m,sig,e) = if b == 10 then (w, s, n+w-1) else (m',sig',e')
  1555.        m'        = ceiling
  1556.             (fromIntegral w * log (fromInteger b) / log 10 :: Double)
  1557.            + 1
  1558.        (sig',e') = if      sig1 >= 10^m'     then (round (t/10), e1+1)
  1559.            else if sig1 <  10^(m'-1) then (round (t*10), e1-1)
  1560.                          else (sig1, e1)
  1561.        sig1     = round t
  1562.        t     = s%1 * (b%1)^^n * 10^^(m'-e1-1)
  1563.        e1     = floor (logBase 10 x)
  1564.        (s,n)     = decodeFloat x
  1565.        b     = floatRadix x
  1566.        w     = floatDigits x
  1567.  
  1568. -- I/O functions and definitions {PreludeIO} ----------------------------------
  1569.  
  1570. stdin         =  "stdin"
  1571. stdout        =  "stdout"
  1572. stderr        =  "stderr"
  1573. stdecho       =  "stdecho"
  1574.  
  1575. data Request  =  -- file system requests:
  1576.                 ReadFile      String         
  1577.               | WriteFile     String String
  1578.               | AppendFile    String String
  1579.                  -- channel system requests:
  1580.               | ReadChan      String 
  1581.               | AppendChan    String String
  1582.                  -- environment requests:
  1583.               | Echo          Bool
  1584.           | GetArgs
  1585.           | GetProgName
  1586.           | GetEnv        String
  1587.  
  1588. data Response = Success
  1589.               | Str     String 
  1590.               | Failure IOError
  1591.           | StrList [String]
  1592.  
  1593. data IOError  = WriteError   String
  1594.               | ReadError    String
  1595.               | SearchError  String
  1596.               | FormatError  String
  1597.               | OtherError   String
  1598.  
  1599. type Dialogue    =  [Response] -> [Request]
  1600.  
  1601. type SuccCont    =                Dialogue
  1602. type StrCont     =  String     -> Dialogue
  1603. type StrListCont =  [String]   -> Dialogue
  1604. type FailCont    =  IOError    -> Dialogue
  1605.  
  1606. done            ::                                                Dialogue
  1607. readFile        :: String ->           FailCont -> StrCont     -> Dialogue
  1608. writeFile       :: String -> String -> FailCont -> SuccCont    -> Dialogue
  1609. appendFile      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  1610. readChan        :: String ->           FailCont -> StrCont     -> Dialogue
  1611. appendChan      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  1612. echo            :: Bool ->             FailCont -> SuccCont    -> Dialogue
  1613. getArgs         ::                     FailCont -> StrListCont -> Dialogue
  1614. getProgName     ::               FailCont -> StrCont     -> Dialogue
  1615. getEnv        :: String ->           FailCont -> StrCont     -> Dialogue
  1616.  
  1617. done resps    =  []
  1618. readFile name fail succ resps =
  1619.      (ReadFile name) : strDispatch fail succ resps
  1620. writeFile name contents fail succ resps =
  1621.     (WriteFile name contents) : succDispatch fail succ resps
  1622. appendFile name contents fail succ resps =
  1623.     (AppendFile name contents) : succDispatch fail succ resps
  1624. readChan name fail succ resps =
  1625.     (ReadChan name) : strDispatch fail succ resps
  1626. appendChan name contents fail succ resps =
  1627.     (AppendChan name contents) : succDispatch fail succ resps
  1628. echo bool fail succ resps =
  1629.     (Echo bool) : succDispatch fail succ resps
  1630. getArgs fail succ resps =
  1631.     GetArgs : strListDispatch fail succ resps
  1632. getProgName fail succ resps =
  1633.     GetProgName : strDispatch fail succ resps
  1634. getEnv name fail succ resps =
  1635.     (GetEnv name) : strDispatch fail succ resps
  1636.  
  1637. strDispatch fail succ (resp:resps) = 
  1638.             case resp of Str val     -> succ val resps
  1639.                          Failure msg -> fail msg resps
  1640.  
  1641. succDispatch fail succ (resp:resps) = 
  1642.             case resp of Success     -> succ resps
  1643.                          Failure msg -> fail msg resps
  1644.  
  1645. strListDispatch fail succ (resp:resps) =
  1646.         case resp of StrList val -> succ val resps
  1647.              Failure msg -> fail msg resps
  1648.  
  1649. abort           :: FailCont
  1650. abort err        = done
  1651.  
  1652. exit            :: FailCont
  1653. exit err         = appendChan stderr msg abort done
  1654.                    where msg = case err of ReadError s   -> s
  1655.                                            WriteError s  -> s
  1656.                                            SearchError s -> s
  1657.                                            FormatError s -> s
  1658.                                            OtherError s  -> s
  1659.  
  1660. print           :: Text a => a -> Dialogue
  1661. print x          = appendChan stdout (show x) exit done
  1662.  
  1663. prints          :: Text a => a -> String -> Dialogue
  1664. prints x s       = appendChan stdout (shows x s) exit done
  1665.  
  1666. interact    :: (String -> String) -> Dialogue
  1667. interact f     = readChan stdin exit
  1668.                 (\x -> appendChan stdout (f x) exit done)
  1669.  
  1670. -- Hooks for primitives: -----------------------------------------------------
  1671. -- Do not mess with these!
  1672.  
  1673. data HugsMaybe a  = HugsJust a | HugsNothing
  1674.  
  1675. primPmInt        :: Num a => Int -> a -> Bool
  1676. primPmInt n x     = fromInt n == x
  1677.  
  1678. primPmInteger    :: Num a => Integer -> a -> Bool
  1679. primPmInteger n x = fromInteger n == x
  1680.  
  1681. primPmFlt        :: Fractional a => Double -> a -> Bool
  1682. primPmFlt n x     = fromDouble n == x
  1683.  
  1684. primPmNpk        :: Integral a => Int -> a -> HugsMaybe a
  1685. primPmNpk n x     = if n'<=x then HugsJust (x-n') else HugsNothing
  1686.             where n' = fromInt n
  1687.  
  1688. primPmSub        :: Integral a => Int -> a -> a
  1689. primPmSub n x     = x - fromInt n
  1690.  
  1691. -- End of Hugs standard prelude ----------------------------------------------
  1692.