1 {----------------------------------------------------------------------------
2 __ __ __ __ ____ ___ _______________________________________________
3 || || || || || || ||__ Hugs 98: The Nottingham and Yale Haskell system
4 ||___|| ||__|| ||__|| __|| Copyright (c) 1994-1999
5 ||---|| ___|| World Wide Web: http://haskell.org/hugs
6 || || Report bugs to: hugs-bugs@haskell.org
7 || || Version: January 1999 _______________________________________________
9 This is the Hugs 98 Standard Prelude, based very closely on the Standard
10 Prelude for Haskell 98.
12 WARNING: This file is an integral part of the Hugs source code. Changes to
13 the definitions in this file without corresponding modifications in other
14 parts of the program may cause the interpreter to fail unexpectedly. Under
15 normal circumstances, you should not attempt to modify this file in any way!
17 -----------------------------------------------------------------------------
18 Hugs 98 is Copyright (c) Mark P Jones, Alastair Reid and the Yale Haskell
19 Group 1994-99, and is distributed as Open Source software under the
20 Artistic License; see the file "Artistic" that is included in the
21 distribution for details.
22 ----------------------------------------------------------------------------}
25 -- module PreludeList,
26 map, (++), concat, filter,
27 head, last, tail, init, null, length, (!!),
28 foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1,
29 iterate, repeat, replicate, cycle,
30 take, drop, splitAt, takeWhile, dropWhile, span, break,
31 lines, words, unlines, unwords, reverse, and, or,
32 any, all, elem, notElem, lookup,
33 sum, product, maximum, minimum, concatMap,
34 zip, zip3, zipWith, zipWith3, unzip, unzip3,
35 -- module PreludeText,
37 Read(readsPrec, readList),
38 Show(show, showsPrec, showList),
39 reads, shows, read, lex,
40 showChar, showString, readParen, showParen,
42 FilePath, IOError, ioError, userError, catch,
43 putChar, putStr, putStrLn, print,
44 getChar, getLine, getContents, interact,
45 readFile, writeFile, appendFile, readIO, readLn,
47 Ix(range, index, inRange, rangeSize),
49 isAscii, isControl, isPrint, isSpace, isUpper, isLower,
50 isAlpha, isDigit, isOctDigit, isHexDigit, isAlphaNum,
51 digitToInt, intToDigit,
54 readLitChar, showLitChar, lexLitChar,
58 readDec, readOct, readHex, readSigned,
61 Ratio, Rational, (%), numerator, denominator, approxRational,
62 -- Non-standard exports
63 IO(..), IOResult(..), Addr, StablePtr,
64 makeStablePtr, freeStablePtr, deRefStablePtr,
70 Char, String, Int, Integer, Float, Double, IO,
71 -- List type: []((:), [])
73 -- Tuple types: (,), (,,), etc.
76 Rec, EmptyRec, EmptyRow, -- non-standard, should only be exported if TREX
78 Ord(compare, (<), (<=), (>=), (>), max, min),
79 Enum(succ, pred, toEnum, fromEnum, enumFrom, enumFromThen,
80 enumFromTo, enumFromThenTo),
81 Bounded(minBound, maxBound),
82 -- Num((+), (-), (*), negate, abs, signum, fromInteger),
83 Num((+), (-), (*), negate, abs, signum, fromInteger, fromInt),
85 -- Integral(quot, rem, div, mod, quotRem, divMod, toInteger),
86 Integral(quot, rem, div, mod, quotRem, divMod, even, odd, toInteger, toInt),
87 -- Fractional((/), recip, fromRational),
88 Fractional((/), recip, fromRational, fromDouble),
89 Floating(pi, exp, log, sqrt, (**), logBase, sin, cos, tan,
90 asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh),
91 RealFrac(properFraction, truncate, round, ceiling, floor),
92 RealFloat(floatRadix, floatDigits, floatRange, decodeFloat,
93 encodeFloat, exponent, significand, scaleFloat, isNaN,
94 isInfinite, isDenormalized, isIEEE, isNegativeZero),
95 Monad((>>=), (>>), return, fail),
97 mapM, mapM_, sequence, sequence_, (=<<),
99 (&&), (||), not, otherwise,
100 subtract, even, odd, gcd, lcm, (^), (^^),
101 fromIntegral, realToFrac, atan2,
102 fst, snd, curry, uncurry, id, const, (.), flip, ($), until,
103 asTypeOf, error, undefined,
106 , MVar, newMVar, putMVar, takeMVar
109 -- Arrrggghhh!!! Help! Help! Help!
110 -- What?! Prelude.hs doesn't even _define_ most of these things!
111 ,primCompAux,PrimArray,primRunST,primNewArray,primWriteArray
112 ,primUnsafeFreezeArray,primIndexArray,primGetRawArgs,primGetEnv
113 ,nh_stdin,nh_stdout,nh_stderr,copy_String_to_cstring,nh_open
114 ,nh_free,nh_close,nh_errno,nh_flush,nh_read,primIntToChar
115 ,unsafeInterleaveIO,nh_write,primCharToInt,
116 nullAddr, incAddr, isNullAddr,
124 -- Standard value bindings {Prelude} ----------------------------------------
129 infixl 7 *, /, `quot`, `rem`, `div`, `mod`, :%, %
131 --infixr 5 : -- this fixity declaration is hard-wired into Hugs
133 infix 4 ==, /=, <, <=, >=, >, `elem`, `notElem`
138 infixr 0 $, $!, `seq`
140 -- Equality and Ordered classes ---------------------------------------------
143 (==), (/=) :: a -> a -> Bool
145 -- Minimal complete definition: (==) or (/=)
149 class (Eq a) => Ord a where
150 compare :: a -> a -> Ordering
151 (<), (<=), (>=), (>) :: a -> a -> Bool
152 max, min :: a -> a -> a
154 -- Minimal complete definition: (<=) or compare
155 -- using compare can be more efficient for complex types
156 compare x y | x==y = EQ
160 x <= y = compare x y /= GT
161 x < y = compare x y == LT
162 x >= y = compare x y /= LT
163 x > y = compare x y == GT
170 class Bounded a where
171 minBound, maxBound :: a
172 -- Minimal complete definition: All
174 -- Numeric classes ----------------------------------------------------------
176 class (Eq a, Show a) => Num a where
177 (+), (-), (*) :: a -> a -> a
179 abs, signum :: a -> a
180 fromInteger :: Integer -> a
183 -- Minimal complete definition: All, except negate or (-)
185 fromInt = fromIntegral
188 class (Num a, Ord a) => Real a where
189 toRational :: a -> Rational
191 class (Real a, Enum a) => Integral a where
192 quot, rem, div, mod :: a -> a -> a
193 quotRem, divMod :: a -> a -> (a,a)
194 even, odd :: a -> Bool
195 toInteger :: a -> Integer
198 -- Minimal complete definition: quotRem and toInteger
199 n `quot` d = q where (q,r) = quotRem n d
200 n `rem` d = r where (q,r) = quotRem n d
201 n `div` d = q where (q,r) = divMod n d
202 n `mod` d = r where (q,r) = divMod n d
203 divMod n d = if signum r == - signum d then (q-1, r+d) else qr
204 where qr@(q,r) = quotRem n d
205 even n = n `rem` 2 == 0
207 toInt = toInt . toInteger
209 class (Num a) => Fractional a where
212 fromRational :: Rational -> a
213 fromDouble :: Double -> a
215 -- Minimal complete definition: fromRational and ((/) or recip)
217 fromDouble = fromRational . toRational
221 class (Fractional a) => Floating a where
223 exp, log, sqrt :: a -> a
224 (**), logBase :: a -> a -> a
225 sin, cos, tan :: a -> a
226 asin, acos, atan :: a -> a
227 sinh, cosh, tanh :: a -> a
228 asinh, acosh, atanh :: a -> a
230 -- Minimal complete definition: pi, exp, log, sin, cos, sinh, cosh,
231 -- asinh, acosh, atanh
232 x ** y = exp (log x * y)
233 logBase x y = log y / log x
235 tan x = sin x / cos x
236 sinh x = (exp x - exp (-x)) / 2
237 cosh x = (exp x + exp (-x)) / 2
238 tanh x = sinh x / cosh x
239 asinh x = log (x + sqrt (x*x + 1))
240 acosh x = log (x + sqrt (x*x - 1))
241 atanh x = (log (1 + x) - log (1 - x)) / 2
243 class (Real a, Fractional a) => RealFrac a where
244 properFraction :: (Integral b) => a -> (b,a)
245 truncate, round :: (Integral b) => a -> b
246 ceiling, floor :: (Integral b) => a -> b
248 -- Minimal complete definition: properFraction
249 truncate x = m where (m,_) = properFraction x
251 round x = let (n,r) = properFraction x
252 m = if r < 0 then n - 1 else n + 1
253 in case signum (abs r - 0.5) of
255 0 -> if even n then n else m
258 ceiling x = if r > 0 then n + 1 else n
259 where (n,r) = properFraction x
261 floor x = if r < 0 then n - 1 else n
262 where (n,r) = properFraction x
264 class (RealFrac a, Floating a) => RealFloat a where
265 floatRadix :: a -> Integer
266 floatDigits :: a -> Int
267 floatRange :: a -> (Int,Int)
268 decodeFloat :: a -> (Integer,Int)
269 encodeFloat :: Integer -> Int -> a
271 significand :: a -> a
272 scaleFloat :: Int -> a -> a
273 isNaN, isInfinite, isDenormalized, isNegativeZero, isIEEE
277 -- Minimal complete definition: All, except exponent, signficand,
279 exponent x = if m==0 then 0 else n + floatDigits x
280 where (m,n) = decodeFloat x
281 significand x = encodeFloat m (- floatDigits x)
282 where (m,_) = decodeFloat x
283 scaleFloat k x = encodeFloat m (n+k)
284 where (m,n) = decodeFloat x
288 | x<0 && y>0 = pi + atan (y/x)
290 (x<0 && isNegativeZero y) ||
291 (isNegativeZero x && isNegativeZero y)
293 | y==0 && (x<0 || isNegativeZero x)
294 = pi -- must be after the previous test on zero y
295 | x==0 && y==0 = y -- must be after the other double zero tests
296 | otherwise = x + y -- x or y is a NaN, return a NaN (via +)
298 -- Numeric functions --------------------------------------------------------
300 subtract :: Num a => a -> a -> a
303 gcd :: Integral a => a -> a -> a
304 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
305 gcd x y = gcd' (abs x) (abs y)
307 gcd' x y = gcd' y (x `rem` y)
309 lcm :: (Integral a) => a -> a -> a
312 lcm x y = abs ((x `quot` gcd x y) * y)
314 (^) :: (Num a, Integral b) => a -> b -> a
316 x ^ n | n > 0 = f x (n-1) x
318 f x n y = g x n where
319 g x n | even n = g (x*x) (n`quot`2)
320 | otherwise = f x (n-1) (x*y)
321 _ ^ _ = error "Prelude.^: negative exponent"
323 (^^) :: (Fractional a, Integral b) => a -> b -> a
324 x ^^ n = if n >= 0 then x ^ n else recip (x^(-n))
326 fromIntegral :: (Integral a, Num b) => a -> b
327 fromIntegral = fromInteger . toInteger
329 realToFrac :: (Real a, Fractional b) => a -> b
330 realToFrac = fromRational . toRational
332 -- Index and Enumeration classes --------------------------------------------
334 class (Ord a) => Ix a where
335 range :: (a,a) -> [a]
336 index :: (a,a) -> a -> Int
337 inRange :: (a,a) -> a -> Bool
338 rangeSize :: (a,a) -> Int
342 | otherwise = index r u + 1
348 enumFrom :: a -> [a] -- [n..]
349 enumFromThen :: a -> a -> [a] -- [n,m..]
350 enumFromTo :: a -> a -> [a] -- [n..m]
351 enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m]
353 -- Minimal complete definition: toEnum, fromEnum
354 succ = toEnum . (1+) . fromEnum
355 pred = toEnum . subtract 1 . fromEnum
356 enumFromTo x y = map toEnum [ fromEnum x .. fromEnum y ]
357 enumFromThenTo x y z = map toEnum [ fromEnum x, fromEnum y .. fromEnum z ]
359 -- Read and Show classes ------------------------------------------------------
361 type ReadS a = String -> [(a,String)]
362 type ShowS = String -> String
365 readsPrec :: Int -> ReadS a
366 readList :: ReadS [a]
368 -- Minimal complete definition: readsPrec
369 readList = readParen False (\r -> [pr | ("[",s) <- lex r,
371 where readl s = [([],t) | ("]",t) <- lex s] ++
372 [(x:xs,u) | (x,t) <- reads s,
374 readl' s = [([],t) | ("]",t) <- lex s] ++
375 [(x:xs,v) | (",",t) <- lex s,
381 showsPrec :: Int -> a -> ShowS
382 showList :: [a] -> ShowS
384 -- Minimal complete definition: show or showsPrec
385 show x = showsPrec 0 x ""
386 showsPrec _ x s = show x ++ s
387 showList [] = showString "[]"
388 showList (x:xs) = showChar '[' . shows x . showl xs
389 where showl [] = showChar ']'
390 showl (x:xs) = showChar ',' . shows x . showl xs
392 -- Monad classes ------------------------------------------------------------
394 class Functor f where
395 fmap :: (a -> b) -> (f a -> f b)
399 (>>=) :: m a -> (a -> m b) -> m b
400 (>>) :: m a -> m b -> m b
401 fail :: String -> m a
403 -- Minimal complete definition: (>>=), return
404 p >> q = p >>= \ _ -> q
407 sequence :: Monad m => [m a] -> m [a]
408 sequence [] = return []
409 sequence (c:cs) = do x <- c
413 sequence_ :: Monad m => [m a] -> m ()
414 sequence_ = foldr (>>) (return ())
416 mapM :: Monad m => (a -> m b) -> [a] -> m [b]
417 mapM f = sequence . map f
419 mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
420 mapM_ f = sequence_ . map f
422 (=<<) :: Monad m => (a -> m b) -> m a -> m b
425 -- Evaluation and strictness ------------------------------------------------
428 seq x y = primSeq x y
430 ($!) :: (a -> b) -> a -> b
431 f $! x = x `primSeq` f x
433 -- Trivial type -------------------------------------------------------------
435 -- data () = () deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
440 instance Ord () where
446 inRange ((),()) () = True
448 instance Enum () where
452 enumFromThen () () = [()]
454 instance Read () where
455 readsPrec p = readParen False (\r -> [((),t) | ("(",s) <- lex r,
458 instance Show () where
459 showsPrec p () = showString "()"
461 instance Bounded () where
465 -- Boolean type -------------------------------------------------------------
467 data Bool = False | True
468 deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
470 (&&), (||) :: Bool -> Bool -> Bool
483 -- Character type -----------------------------------------------------------
485 data Char -- builtin datatype of ISO Latin characters
486 type String = [Char] -- strings are lists of characters
488 instance Eq Char where (==) = primEqChar
489 instance Ord Char where (<=) = primLeChar
491 instance Enum Char where
492 toEnum = primIntToChar
493 fromEnum = primCharToInt
494 enumFrom c = map toEnum [fromEnum c .. fromEnum (maxBound::Char)]
495 enumFromThen c d = map toEnum [fromEnum c, fromEnum d .. fromEnum (lastChar::Char)]
496 where lastChar = if d < c then minBound else maxBound
498 instance Ix Char where
499 range (c,c') = [c..c']
501 | inRange b ci = fromEnum ci - fromEnum c
502 | otherwise = error "Ix.index: Index out of range."
503 inRange (c,c') ci = fromEnum c <= i && i <= fromEnum c'
504 where i = fromEnum ci
506 instance Read Char where
507 readsPrec p = readParen False
508 (\r -> [(c,t) | ('\'':s,t) <- lex r,
509 (c,"\'") <- readLitChar s ])
510 readList = readParen False (\r -> [(l,t) | ('"':s, t) <- lex r,
512 where readl ('"':s) = [("",s)]
513 readl ('\\':'&':s) = readl s
514 readl s = [(c:cs,u) | (c ,t) <- readLitChar s,
516 instance Show Char where
517 showsPrec p '\'' = showString "'\\''"
518 showsPrec p c = showChar '\'' . showLitChar c . showChar '\''
520 showList cs = showChar '"' . showl cs
521 where showl "" = showChar '"'
522 showl ('"':cs) = showString "\\\"" . showl cs
523 showl (c:cs) = showLitChar c . showl cs
525 instance Bounded Char where
529 isAscii, isControl, isPrint, isSpace :: Char -> Bool
530 isUpper, isLower, isAlpha, isDigit, isAlphaNum :: Char -> Bool
532 isAscii c = fromEnum c < 128
533 isControl c = c < ' ' || c == '\DEL'
534 isPrint c = c >= ' ' && c <= '~'
535 isSpace c = c == ' ' || c == '\t' || c == '\n' ||
536 c == '\r' || c == '\f' || c == '\v'
537 isUpper c = c >= 'A' && c <= 'Z'
538 isLower c = c >= 'a' && c <= 'z'
539 isAlpha c = isUpper c || isLower c
540 isDigit c = c >= '0' && c <= '9'
541 isAlphaNum c = isAlpha c || isDigit c
543 -- Digit conversion operations
544 digitToInt :: Char -> Int
546 | isDigit c = fromEnum c - fromEnum '0'
547 | c >= 'a' && c <= 'f' = fromEnum c - fromEnum 'a' + 10
548 | c >= 'A' && c <= 'F' = fromEnum c - fromEnum 'A' + 10
549 | otherwise = error "Char.digitToInt: not a digit"
551 intToDigit :: Int -> Char
553 | i >= 0 && i <= 9 = toEnum (fromEnum '0' + i)
554 | i >= 10 && i <= 15 = toEnum (fromEnum 'a' + i - 10)
555 | otherwise = error "Char.intToDigit: not a digit"
557 toUpper, toLower :: Char -> Char
558 toUpper c | isLower c = toEnum (fromEnum c - fromEnum 'a' + fromEnum 'A')
561 toLower c | isUpper c = toEnum (fromEnum c - fromEnum 'A' + fromEnum 'a')
570 -- Maybe type ---------------------------------------------------------------
572 data Maybe a = Nothing | Just a
573 deriving (Eq, Ord, Read, Show)
575 maybe :: b -> (a -> b) -> Maybe a -> b
576 maybe n f Nothing = n
577 maybe n f (Just x) = f x
579 instance Functor Maybe where
580 fmap f Nothing = Nothing
581 fmap f (Just x) = Just (f x)
583 instance Monad Maybe where
585 Nothing >>= k = Nothing
589 -- Either type --------------------------------------------------------------
591 data Either a b = Left a | Right b
592 deriving (Eq, Ord, Read, Show)
594 either :: (a -> c) -> (b -> c) -> Either a b -> c
595 either l r (Left x) = l x
596 either l r (Right y) = r y
598 -- Ordering type ------------------------------------------------------------
600 data Ordering = LT | EQ | GT
601 deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
603 -- Lists --------------------------------------------------------------------
605 --data [a] = [] | a : [a] deriving (Eq, Ord)
607 instance Eq a => Eq [a] where
609 (x:xs) == (y:ys) = x==y && xs==ys
612 instance Ord a => Ord [a] where
613 compare [] (_:_) = LT
615 compare (_:_) [] = GT
616 compare (x:xs) (y:ys) = primCompAux x y (compare xs ys)
618 instance Functor [] where
621 instance Monad [ ] where
622 (x:xs) >>= f = f x ++ (xs >>= f)
627 instance Read a => Read [a] where
628 readsPrec p = readList
630 instance Show a => Show [a] where
631 showsPrec p = showList
633 -- Tuples -------------------------------------------------------------------
635 -- data (a,b) = (a,b) deriving (Eq, Ord, Ix, Read, Show)
638 -- Standard Integral types --------------------------------------------------
640 data Int -- builtin datatype of fixed size integers
641 data Integer -- builtin datatype of arbitrary size integers
643 instance Eq Integer where
644 (==) x y = primCompareInteger x y == 0
646 instance Ord Integer where
647 compare x y = case primCompareInteger x y of
652 instance Eq Int where
656 instance Ord Int where
662 instance Num Int where
665 negate = primNegateInt
669 fromInteger = primIntegerToInt
672 instance Bounded Int where
673 minBound = primMinInt
674 maxBound = primMaxInt
676 instance Num Integer where
677 (+) = primPlusInteger
678 (-) = primMinusInteger
679 negate = primNegateInteger
680 (*) = primTimesInteger
684 fromInt = primIntToInteger
686 absReal x | x >= 0 = x
689 signumReal x | x == 0 = 0
693 instance Real Int where
694 toRational x = toInteger x % 1
696 instance Real Integer where
699 instance Integral Int where
700 quotRem = primQuotRemInt
701 toInteger = primIntToInteger
704 instance Integral Integer where
705 quotRem = primQuotRemInteger
706 --divMod = primDivModInteger
708 toInt = primIntegerToInt
710 instance Ix Int where
713 | inRange b i = i - m
714 | otherwise = error "index: Index out of range"
715 inRange (m,n) i = m <= i && i <= n
717 instance Ix Integer where
720 | inRange b i = fromInteger (i - m)
721 | otherwise = error "index: Index out of range"
722 inRange (m,n) i = m <= i && i <= n
724 instance Enum Int where
727 enumFrom = numericEnumFrom
728 enumFromTo = numericEnumFromTo
729 enumFromThen = numericEnumFromThen
730 enumFromThenTo = numericEnumFromThenTo
732 instance Enum Integer where
733 toEnum = primIntToInteger
734 fromEnum = primIntegerToInt
735 enumFrom = numericEnumFrom
736 enumFromTo = numericEnumFromTo
737 enumFromThen = numericEnumFromThen
738 enumFromThenTo = numericEnumFromThenTo
740 numericEnumFrom :: Real a => a -> [a]
741 numericEnumFromThen :: Real a => a -> a -> [a]
742 numericEnumFromTo :: Real a => a -> a -> [a]
743 numericEnumFromThenTo :: Real a => a -> a -> a -> [a]
744 numericEnumFrom n = n : (numericEnumFrom $! (n+1))
745 numericEnumFromThen n m = iterate ((m-n)+) n
746 numericEnumFromTo n m = takeWhile (<= m) (numericEnumFrom n)
747 numericEnumFromThenTo n n' m = takeWhile p (numericEnumFromThen n n')
748 where p | n' >= n = (<= m)
751 instance Read Int where
752 readsPrec p = readSigned readDec
754 instance Show Int where
756 | n == minBound = showSigned showInt p (toInteger n)
757 | otherwise = showSigned showInt p n
759 instance Read Integer where
760 readsPrec p = readSigned readDec
762 instance Show Integer where
763 showsPrec = showSigned showInt
766 -- Standard Floating types --------------------------------------------------
768 data Float -- builtin datatype of single precision floating point numbers
769 data Double -- builtin datatype of double precision floating point numbers
771 instance Eq Float where
775 instance Ord Float where
781 instance Num Float where
784 negate = primNegateFloat
788 fromInteger = primIntegerToFloat
789 fromInt = primIntToFloat
793 instance Eq Double where
797 instance Ord Double where
803 instance Num Double where
805 (-) = primMinusDouble
806 negate = primNegateDouble
807 (*) = primTimesDouble
810 fromInteger = primIntegerToDouble
811 fromInt = primIntToDouble
815 instance Real Float where
816 toRational = floatToRational
818 instance Real Double where
819 toRational = doubleToRational
821 -- Calls to these functions are optimised when passed as arguments to
823 floatToRational :: Float -> Rational
824 doubleToRational :: Double -> Rational
825 floatToRational x = realFloatToRational x
826 doubleToRational x = realFloatToRational x
828 realFloatToRational x = (m%1)*(b%1)^^n
829 where (m,n) = decodeFloat x
832 instance Fractional Float where
833 (/) = primDivideFloat
834 fromRational = rationalToRealFloat
835 fromDouble = primDoubleToFloat
838 instance Fractional Double where
839 (/) = primDivideDouble
840 fromRational = rationalToRealFloat
843 rationalToRealFloat x = x'
845 f e = if e' == e then y else f e'
846 where y = encodeFloat (round (x * (1%b)^^e)) e
847 (_,e') = decodeFloat y
848 (_,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
849 / fromInteger (denominator x))
852 instance Floating Float where
853 pi = 3.14159265358979323846
864 instance Floating Double where
865 pi = 3.14159265358979323846
868 sqrt = primSqrtDouble
872 asin = primAsinDouble
873 acos = primAcosDouble
874 atan = primAtanDouble
876 instance RealFrac Float where
877 properFraction = floatProperFraction
879 instance RealFrac Double where
880 properFraction = floatProperFraction
882 floatProperFraction x
883 | n >= 0 = (fromInteger m * fromInteger b ^ n, 0)
884 | otherwise = (fromInteger w, encodeFloat r n)
885 where (m,n) = decodeFloat x
887 (w,r) = quotRem m (b^(-n))
889 instance RealFloat Float where
890 floatRadix _ = toInteger primRadixFloat
891 floatDigits _ = primDigitsFloat
892 floatRange _ = (primMinExpFloat,primMaxExpFloat)
893 encodeFloat = primEncodeFloatZ
894 decodeFloat = primDecodeFloatZ
895 isNaN = primIsNaNFloat
896 isInfinite = primIsInfiniteFloat
897 isDenormalized= primIsDenormalizedFloat
898 isNegativeZero= primIsNegativeZeroFloat
899 isIEEE = const primIsIEEEFloat
901 instance RealFloat Double where
902 floatRadix _ = toInteger primRadixDouble
903 floatDigits _ = primDigitsDouble
904 floatRange _ = (primMinExpDouble,primMaxExpDouble)
905 encodeFloat = primEncodeDoubleZ
906 decodeFloat = primDecodeDoubleZ
907 isNaN = primIsNaNDouble
908 isInfinite = primIsInfiniteDouble
909 isDenormalized= primIsDenormalizedDouble
910 isNegativeZero= primIsNegativeZeroDouble
911 isIEEE = const primIsIEEEDouble
913 instance Enum Float where
914 toEnum = primIntToFloat
916 enumFrom = numericEnumFrom
917 enumFromThen = numericEnumFromThen
918 enumFromTo n m = numericEnumFromTo n (m+1/2)
919 enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
921 instance Enum Double where
922 toEnum = primIntToDouble
924 enumFrom = numericEnumFrom
925 enumFromThen = numericEnumFromThen
926 enumFromTo n m = numericEnumFromTo n (m+1/2)
927 enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
929 instance Read Float where
930 readsPrec p = readSigned readFloat
932 instance Show Float where
933 showsPrec p = showSigned showFloat p
935 instance Read Double where
936 readsPrec p = readSigned readFloat
938 instance Show Double where
939 showsPrec p = showSigned showFloat p
942 -- Some standard functions --------------------------------------------------
950 curry :: ((a,b) -> c) -> (a -> b -> c)
951 curry f x y = f (x,y)
953 uncurry :: (a -> b -> c) -> ((a,b) -> c)
954 uncurry f p = f (fst p) (snd p)
962 (.) :: (b -> c) -> (a -> b) -> (a -> c)
965 flip :: (a -> b -> c) -> b -> a -> c
968 ($) :: (a -> b) -> a -> b
971 until :: (a -> Bool) -> (a -> a) -> a -> a
972 until p f x = if p x then x else until p f (f x)
974 asTypeOf :: a -> a -> a
978 error msg = primRaise (ErrorCall msg)
981 undefined | False = undefined
983 -- Standard functions on rational numbers {PreludeRatio} --------------------
985 data Integral a => Ratio a = a :% a deriving (Eq)
986 type Rational = Ratio Integer
988 (%) :: Integral a => a -> a -> Ratio a
989 x % y = reduce (x * signum y) (abs y)
991 reduce :: Integral a => a -> a -> Ratio a
992 reduce x y | y == 0 = error "Ratio.%: zero denominator"
993 | otherwise = (x `quot` d) :% (y `quot` d)
996 numerator, denominator :: Integral a => Ratio a -> a
997 numerator (x :% y) = x
998 denominator (x :% y) = y
1000 instance Integral a => Ord (Ratio a) where
1001 compare (x:%y) (x':%y') = compare (x*y') (x'*y)
1003 instance Integral a => Num (Ratio a) where
1004 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
1005 (x:%y) * (x':%y') = reduce (x*x') (y*y')
1006 negate (x :% y) = negate x :% y
1007 abs (x :% y) = abs x :% y
1008 signum (x :% y) = signum x :% 1
1009 fromInteger x = fromInteger x :% 1
1010 fromInt = intToRatio
1012 -- Hugs optimises code of the form fromRational (intToRatio x)
1013 intToRatio :: Integral a => Int -> Ratio a
1014 intToRatio x = fromInt x :% 1
1016 instance Integral a => Real (Ratio a) where
1017 toRational (x:%y) = toInteger x :% toInteger y
1019 instance Integral a => Fractional (Ratio a) where
1020 (x:%y) / (x':%y') = (x*y') % (y*x')
1021 recip (x:%y) = if x < 0 then (-y) :% (-x) else y :% x
1022 fromRational (x:%y) = fromInteger x :% fromInteger y
1023 fromDouble = doubleToRatio
1025 -- Hugs optimises code of the form fromRational (doubleToRatio x)
1026 doubleToRatio :: Integral a => Double -> Ratio a
1028 | n>=0 = (fromInteger m * fromInteger b ^ n) % 1
1029 | otherwise = fromInteger m % (fromInteger b ^ (-n))
1030 where (m,n) = decodeFloat x
1033 instance Integral a => RealFrac (Ratio a) where
1034 properFraction (x:%y) = (fromIntegral q, r:%y)
1035 where (q,r) = quotRem x y
1037 instance Integral a => Enum (Ratio a) where
1040 enumFrom = numericEnumFrom
1041 enumFromThen = numericEnumFromThen
1043 instance (Read a, Integral a) => Read (Ratio a) where
1044 readsPrec p = readParen (p > 7)
1045 (\r -> [(x%y,u) | (x,s) <- reads r,
1049 instance Integral a => Show (Ratio a) where
1050 showsPrec p (x:%y) = showParen (p > 7)
1051 (shows x . showString " % " . shows y)
1053 approxRational :: RealFrac a => a -> a -> Rational
1054 approxRational x eps = simplest (x-eps) (x+eps)
1055 where simplest x y | y < x = simplest y x
1057 | x > 0 = simplest' n d n' d'
1058 | y < 0 = - simplest' (-n') d' (-n) d
1059 | otherwise = 0 :% 1
1060 where xr@(n:%d) = toRational x
1061 (n':%d') = toRational y
1062 simplest' n d n' d' -- assumes 0 < n%d < n'%d'
1064 | q /= q' = (q+1) :% 1
1065 | otherwise = (q*n''+d'') :% n''
1066 where (q,r) = quotRem n d
1067 (q',r') = quotRem n' d'
1068 (n'':%d'') = simplest' d' r' d r
1070 -- Standard list functions {PreludeList} ------------------------------------
1077 last (_:xs) = last xs
1084 init (x:xs) = x : init xs
1090 (++) :: [a] -> [a] -> [a]
1092 (x:xs) ++ ys = x : (xs ++ ys)
1094 map :: (a -> b) -> [a] -> [b]
1095 --map f xs = [ f x | x <- xs ]
1097 map f (x:xs) = f x : map f xs
1100 filter :: (a -> Bool) -> [a] -> [a]
1101 --filter p xs = [ x | x <- xs, p x ]
1103 filter p (x:xs) = if p x then x : filter p xs else filter p xs
1106 concat :: [[a]] -> [a]
1107 --concat = foldr (++) []
1109 concat (xs:xss) = xs ++ concat xss
1111 length :: [a] -> Int
1112 --length = foldl' (\n _ -> n + 1) 0
1114 length (x:xs) = let n = length xs in primSeq n (1+n)
1116 (!!) :: [b] -> Int -> b
1118 (_:xs) !! n | n>0 = xs !! (n-1)
1119 (_:_) !! _ = error "Prelude.!!: negative index"
1120 [] !! _ = error "Prelude.!!: index too large"
1122 foldl :: (a -> b -> a) -> a -> [b] -> a
1124 foldl f z (x:xs) = foldl f (f z x) xs
1126 foldl' :: (a -> b -> a) -> a -> [b] -> a
1128 foldl' f a (x:xs) = (foldl' f $! f a x) xs
1130 foldl1 :: (a -> a -> a) -> [a] -> a
1131 foldl1 f (x:xs) = foldl f x xs
1133 scanl :: (a -> b -> a) -> a -> [b] -> [a]
1134 scanl f q xs = q : (case xs of
1136 x:xs -> scanl f (f q x) xs)
1138 scanl1 :: (a -> a -> a) -> [a] -> [a]
1139 scanl1 f (x:xs) = scanl f x xs
1141 foldr :: (a -> b -> b) -> b -> [a] -> b
1143 foldr f z (x:xs) = f x (foldr f z xs)
1145 foldr1 :: (a -> a -> a) -> [a] -> a
1147 foldr1 f (x:xs) = f x (foldr1 f xs)
1149 scanr :: (a -> b -> b) -> b -> [a] -> [b]
1150 scanr f q0 [] = [q0]
1151 scanr f q0 (x:xs) = f x q : qs
1152 where qs@(q:_) = scanr f q0 xs
1154 scanr1 :: (a -> a -> a) -> [a] -> [a]
1156 scanr1 f (x:xs) = f x q : qs
1157 where qs@(q:_) = scanr1 f xs
1159 iterate :: (a -> a) -> a -> [a]
1160 iterate f x = x : iterate f (f x)
1163 repeat x = xs where xs = x:xs
1165 replicate :: Int -> a -> [a]
1166 replicate n x = take n (repeat x)
1169 cycle [] = error "Prelude.cycle: empty list"
1170 cycle xs = xs' where xs'=xs++xs'
1172 take :: Int -> [a] -> [a]
1175 take n (x:xs) | n>0 = x : take (n-1) xs
1176 take _ _ = error "Prelude.take: negative argument"
1178 drop :: Int -> [a] -> [a]
1181 drop n (_:xs) | n>0 = drop (n-1) xs
1182 drop _ _ = error "Prelude.drop: negative argument"
1184 splitAt :: Int -> [a] -> ([a], [a])
1185 splitAt 0 xs = ([],xs)
1186 splitAt _ [] = ([],[])
1187 splitAt n (x:xs) | n>0 = (x:xs',xs'') where (xs',xs'') = splitAt (n-1) xs
1188 splitAt _ _ = error "Prelude.splitAt: negative argument"
1190 takeWhile :: (a -> Bool) -> [a] -> [a]
1193 | p x = x : takeWhile p xs
1196 dropWhile :: (a -> Bool) -> [a] -> [a]
1198 dropWhile p xs@(x:xs')
1199 | p x = dropWhile p xs'
1202 span, break :: (a -> Bool) -> [a] -> ([a],[a])
1206 | otherwise = ([],xs)
1207 where (ys,zs) = span p xs'
1208 break p = span (not . p)
1210 lines :: String -> [String]
1212 lines s = let (l,s') = break ('\n'==) s
1213 in l : case s' of [] -> []
1214 (_:s'') -> lines s''
1216 words :: String -> [String]
1217 words s = case dropWhile isSpace s of
1220 where (w,s'') = break isSpace s'
1222 unlines :: [String] -> String
1223 unlines = concatMap (\l -> l ++ "\n")
1225 unwords :: [String] -> String
1227 unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
1229 reverse :: [a] -> [a]
1230 --reverse = foldl (flip (:)) []
1231 reverse xs = ri [] xs
1232 where ri acc [] = acc
1233 ri acc (x:xs) = ri (x:acc) xs
1235 and, or :: [Bool] -> Bool
1236 --and = foldr (&&) True
1237 --or = foldr (||) False
1239 and (x:xs) = if x then and xs else x
1241 or (x:xs) = if x then x else or xs
1243 any, all :: (a -> Bool) -> [a] -> Bool
1244 --any p = or . map p
1245 --all p = and . map p
1247 any p (x:xs) = if p x then True else any p xs
1249 all p (x:xs) = if p x then all p xs else False
1251 elem, notElem :: Eq a => a -> [a] -> Bool
1253 --notElem = all . (/=)
1255 elem x (y:ys) = if x==y then True else elem x ys
1257 notElem x (y:ys) = if x==y then False else notElem x ys
1259 lookup :: Eq a => a -> [(a,b)] -> Maybe b
1260 lookup k [] = Nothing
1261 lookup k ((x,y):xys)
1263 | otherwise = lookup k xys
1265 sum, product :: Num a => [a] -> a
1267 product = foldl' (*) 1
1269 maximum, minimum :: Ord a => [a] -> a
1270 maximum = foldl1 max
1271 minimum = foldl1 min
1273 concatMap :: (a -> [b]) -> [a] -> [b]
1274 concatMap f = concat . map f
1276 zip :: [a] -> [b] -> [(a,b)]
1277 zip = zipWith (\a b -> (a,b))
1279 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
1280 zip3 = zipWith3 (\a b c -> (a,b,c))
1282 zipWith :: (a->b->c) -> [a]->[b]->[c]
1283 zipWith z (a:as) (b:bs) = z a b : zipWith z as bs
1286 zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
1287 zipWith3 z (a:as) (b:bs) (c:cs)
1288 = z a b c : zipWith3 z as bs cs
1289 zipWith3 _ _ _ _ = []
1291 unzip :: [(a,b)] -> ([a],[b])
1292 unzip = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
1294 unzip3 :: [(a,b,c)] -> ([a],[b],[c])
1295 unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
1298 -- PreludeText ----------------------------------------------------------------
1300 reads :: Read a => ReadS a
1303 shows :: Show a => a -> ShowS
1306 read :: Read a => String -> a
1307 read s = case [x | (x,t) <- reads s, ("","") <- lex t] of
1309 [] -> error "Prelude.read: no parse"
1310 _ -> error "Prelude.read: ambiguous parse"
1312 showChar :: Char -> ShowS
1315 showString :: String -> ShowS
1318 showParen :: Bool -> ShowS -> ShowS
1319 showParen b p = if b then showChar '(' . p . showChar ')' else p
1321 showField :: Show a => String -> a -> ShowS
1322 showField m v = showString m . showChar '=' . shows v
1324 readParen :: Bool -> ReadS a -> ReadS a
1325 readParen b g = if b then mandatory else optional
1326 where optional r = g r ++ mandatory r
1327 mandatory r = [(x,u) | ("(",s) <- lex r,
1328 (x,t) <- optional s,
1332 readField :: Read a => String -> ReadS a
1333 readField m s0 = [ r | (t, s1) <- lex s0, t == m,
1339 lex (c:s) | isSpace c = lex (dropWhile isSpace s)
1340 lex ('\'':s) = [('\'':ch++"'", t) | (ch,'\'':t) <- lexLitChar s,
1342 lex ('"':s) = [('"':str, t) | (str,t) <- lexString s]
1344 lexString ('"':s) = [("\"",s)]
1345 lexString s = [(ch++str, u)
1346 | (ch,t) <- lexStrItem s,
1347 (str,u) <- lexString t ]
1349 lexStrItem ('\\':'&':s) = [("\\&",s)]
1350 lexStrItem ('\\':c:s) | isSpace c
1351 = [("",t) | '\\':t <- [dropWhile isSpace s]]
1352 lexStrItem s = lexLitChar s
1354 lex (c:s) | isSingle c = [([c],s)]
1355 | isSym c = [(c:sym,t) | (sym,t) <- [span isSym s]]
1356 | isAlpha c = [(c:nam,t) | (nam,t) <- [span isIdChar s]]
1357 | isDigit c = [(c:ds++fe,t) | (ds,s) <- [span isDigit s],
1358 (fe,t) <- lexFracExp s ]
1359 | otherwise = [] -- bad character
1361 isSingle c = c `elem` ",;()[]{}_`"
1362 isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
1363 isIdChar c = isAlphaNum c || c `elem` "_'"
1365 lexFracExp ('.':s) = [('.':ds++e,u) | (ds,t) <- lexDigits s,
1367 lexFracExp s = [("",s)]
1369 lexExp (e:s) | e `elem` "eE"
1370 = [(e:c:ds,u) | (c:t) <- [s], c `elem` "+-",
1371 (ds,u) <- lexDigits t] ++
1372 [(e:ds,t) | (ds,t) <- lexDigits s]
1375 lexDigits :: ReadS String
1376 lexDigits = nonnull isDigit
1378 nonnull :: (Char -> Bool) -> ReadS String
1379 nonnull p s = [(cs,t) | (cs@(_:_),t) <- [span p s]]
1381 lexLitChar :: ReadS String
1382 lexLitChar ('\\':s) = [('\\':esc, t) | (esc,t) <- lexEsc s]
1384 lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = [([c],s)] -- "
1385 lexEsc ('^':c:s) | c >= '@' && c <= '_' = [(['^',c],s)]
1386 lexEsc s@(d:_) | isDigit d = lexDigits s
1387 lexEsc s@(c:_) | isUpper c
1388 = let table = ('\DEL',"DEL") : asciiTab
1389 in case [(mne,s') | (c, mne) <- table,
1390 ([],s') <- [lexmatch mne s]]
1394 lexLitChar (c:s) = [([c],s)]
1397 isOctDigit c = c >= '0' && c <= '7'
1398 isHexDigit c = isDigit c || c >= 'A' && c <= 'F'
1399 || c >= 'a' && c <= 'f'
1401 lexmatch :: (Eq a) => [a] -> [a] -> ([a],[a])
1402 lexmatch (x:xs) (y:ys) | x == y = lexmatch xs ys
1403 lexmatch xs ys = (xs,ys)
1405 asciiTab = zip ['\NUL'..' ']
1406 ["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
1407 "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
1408 "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
1409 "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US",
1412 readLitChar :: ReadS Char
1413 readLitChar ('\\':s) = readEsc s
1415 readEsc ('a':s) = [('\a',s)]
1416 readEsc ('b':s) = [('\b',s)]
1417 readEsc ('f':s) = [('\f',s)]
1418 readEsc ('n':s) = [('\n',s)]
1419 readEsc ('r':s) = [('\r',s)]
1420 readEsc ('t':s) = [('\t',s)]
1421 readEsc ('v':s) = [('\v',s)]
1422 readEsc ('\\':s) = [('\\',s)]
1423 readEsc ('"':s) = [('"',s)]
1424 readEsc ('\'':s) = [('\'',s)]
1425 readEsc ('^':c:s) | c >= '@' && c <= '_'
1426 = [(toEnum (fromEnum c - fromEnum '@'), s)]
1427 readEsc s@(d:_) | isDigit d
1428 = [(toEnum n, t) | (n,t) <- readDec s]
1429 readEsc ('o':s) = [(toEnum n, t) | (n,t) <- readOct s]
1430 readEsc ('x':s) = [(toEnum n, t) | (n,t) <- readHex s]
1431 readEsc s@(c:_) | isUpper c
1432 = let table = ('\DEL',"DEL") : asciiTab
1433 in case [(c,s') | (c, mne) <- table,
1434 ([],s') <- [lexmatch mne s]]
1438 readLitChar (c:s) = [(c,s)]
1440 showLitChar :: Char -> ShowS
1441 showLitChar c | c > '\DEL' = showChar '\\' .
1442 protectEsc isDigit (shows (fromEnum c))
1443 showLitChar '\DEL' = showString "\\DEL"
1444 showLitChar '\\' = showString "\\\\"
1445 showLitChar c | c >= ' ' = showChar c
1446 showLitChar '\a' = showString "\\a"
1447 showLitChar '\b' = showString "\\b"
1448 showLitChar '\f' = showString "\\f"
1449 showLitChar '\n' = showString "\\n"
1450 showLitChar '\r' = showString "\\r"
1451 showLitChar '\t' = showString "\\t"
1452 showLitChar '\v' = showString "\\v"
1453 showLitChar '\SO' = protectEsc ('H'==) (showString "\\SO")
1454 showLitChar c = showString ('\\' : snd (asciiTab!!fromEnum c))
1456 protectEsc p f = f . cont
1457 where cont s@(c:_) | p c = "\\&" ++ s
1460 -- Unsigned readers for various bases
1461 readDec, readOct, readHex :: Integral a => ReadS a
1462 readDec = readInt 10 isDigit (\d -> fromEnum d - fromEnum '0')
1463 readOct = readInt 8 isOctDigit (\d -> fromEnum d - fromEnum '0')
1464 readHex = readInt 16 isHexDigit hex
1465 where hex d = fromEnum d -
1468 else fromEnum (if isUpper d then 'A' else 'a') - 10)
1470 -- readInt reads a string of digits using an arbitrary base.
1471 -- Leading minus signs must be handled elsewhere.
1473 readInt :: Integral a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
1474 readInt radix isDig digToInt s =
1475 [(foldl1 (\n d -> n * radix + d) (map (fromIntegral . digToInt) ds), r)
1476 | (ds,r) <- nonnull isDig s ]
1478 -- showInt is used for positive numbers only
1479 showInt :: Integral a => a -> ShowS
1482 = error "Numeric.showInt: can't show negative numbers"
1485 = let (n',d) = quotRem n 10
1486 r' = toEnum (fromEnum '0' + fromIntegral d) : r
1487 in if n' == 0 then r' else showInt n' r'
1489 = case quotRem n 10 of { (n',d) ->
1490 let r' = toEnum (fromEnum '0' + fromIntegral d) : r
1491 in if n' == 0 then r' else showInt n' r'
1495 readSigned:: Real a => ReadS a -> ReadS a
1496 readSigned readPos = readParen False read'
1497 where read' r = read'' r ++
1498 [(-x,t) | ("-",s) <- lex r,
1500 read'' r = [(n,s) | (str,s) <- lex r,
1501 (n,"") <- readPos str]
1503 showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS
1504 showSigned showPos p x = if x < 0 then showParen (p > 6)
1505 (showChar '-' . showPos (-x))
1508 readFloat :: RealFloat a => ReadS a
1509 readFloat r = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r,
1511 where readFix r = [(read (ds++ds'), length ds', t)
1512 | (ds, s) <- lexDigits r
1513 , (ds',t) <- lexFrac s ]
1515 lexFrac ('.':s) = lexDigits s
1516 lexFrac s = [("",s)]
1518 readExp (e:s) | e `elem` "eE" = readExp' s
1521 readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s]
1522 readExp' ('+':s) = readDec s
1523 readExp' s = readDec s
1526 -- Hooks for primitives: -----------------------------------------------------
1527 -- Do not mess with these!
1529 primCompAux :: Ord a => a -> a -> Ordering -> Ordering
1530 primCompAux x y o = case compare x y of EQ -> o; LT -> LT; GT -> GT
1532 primPmInt :: Num a => Int -> a -> Bool
1533 primPmInt n x = fromInt n == x
1535 primPmInteger :: Num a => Integer -> a -> Bool
1536 primPmInteger n x = fromInteger n == x
1538 primPmDouble :: Fractional a => Double -> a -> Bool
1539 primPmDouble n x = fromDouble n == x
1541 -- ToDo: make the message more informative.
1543 primPmFail = error "Pattern Match Failure"
1545 -- used in desugaring Foreign functions
1546 primMkIO :: (RealWorld -> (a,RealWorld)) -> IO a
1549 primCreateAdjThunk :: (a -> b) -> String -> Char -> IO Addr
1550 primCreateAdjThunk fun typestr callconv
1551 = do sp <- makeStablePtr fun
1552 p <- copy_String_to_cstring typestr -- is never freed
1553 a <- primCreateAdjThunkARCH sp p callconv
1556 -- The following primitives are only needed if (n+k) patterns are enabled:
1557 primPmNpk :: Integral a => Int -> a -> Maybe a
1558 primPmNpk n x = if n'<=x then Just (x-n') else Nothing
1559 where n' = fromInt n
1561 primPmSub :: Integral a => Int -> a -> a
1562 primPmSub n x = x - fromInt n
1564 -- Unpack strings generated by the Hugs code generator.
1565 -- Strings can contain \0 provided they're coded right.
1567 -- ToDo: change this (and Hugs code generator) to use ByteArrays
1569 primUnpackString :: Addr -> String
1570 primUnpackString a = unpack 0
1572 -- The following decoding is based on evalString in the old machine.c
1575 | c == '\\' = if '\\' == primIndexCharOffAddr a (i+1)
1576 then '\\' : unpack (i+2)
1577 else '\0' : unpack (i+2)
1578 | otherwise = c : unpack (i+1)
1580 c = primIndexCharOffAddr a i
1583 -- Monadic I/O: --------------------------------------------------------------
1585 type FilePath = String
1587 --data IOError = ...
1588 --instance Eq IOError ...
1589 --instance Show IOError ...
1591 data IOError = IOError String
1592 instance Show IOError where
1593 showsPrec _ (IOError s) = showString ("I/O error: " ++ s)
1595 ioError :: IOError -> IO a
1596 ioError (IOError s) = primRaise (IOExcept s)
1598 userError :: String -> IOError
1599 userError s = primRaise (ErrorCall s)
1601 catch :: IO a -> (IOError -> IO a) -> IO a
1603 = ST (\s -> unST m s `primCatch` \ err -> unST (k (e2ioe err)) s)
1605 e2ioe (IOExcept s) = IOError s
1606 e2ioe other = IOError (show other)
1608 putChar :: Char -> IO ()
1609 putChar c = nh_stdout >>= \h -> nh_write h c
1611 putStr :: String -> IO ()
1612 putStr s = nh_stdout >>= \h ->
1613 let loop [] = nh_flush h
1614 loop (c:cs) = nh_write h c >> loop cs
1617 putStrLn :: String -> IO ()
1618 putStrLn s = do { putStr s; putChar '\n' }
1620 print :: Show a => a -> IO ()
1621 print = putStrLn . show
1624 getChar = unsafeInterleaveIO (
1626 nh_read h >>= \ci ->
1627 return (primIntToChar ci)
1630 getLine :: IO String
1631 getLine = do c <- getChar
1632 if c=='\n' then return ""
1633 else do cs <- getLine
1636 getContents :: IO String
1637 getContents = nh_stdin >>= \h -> readfromhandle h
1639 interact :: (String -> String) -> IO ()
1640 interact f = getContents >>= (putStr . f)
1642 readFile :: FilePath -> IO String
1644 = copy_String_to_cstring fname >>= \ptr ->
1645 nh_open ptr 0 >>= \h ->
1647 nh_errno >>= \errno ->
1648 if (isNullAddr h || errno /= 0)
1649 then (ioError.IOError) ("readFile: can't open file " ++ fname)
1650 else readfromhandle h
1652 writeFile :: FilePath -> String -> IO ()
1653 writeFile fname contents
1654 = copy_String_to_cstring fname >>= \ptr ->
1655 nh_open ptr 1 >>= \h ->
1657 nh_errno >>= \errno ->
1658 if (isNullAddr h || errno /= 0)
1659 then (ioError.IOError) ("writeFile: can't create file " ++ fname)
1660 else writetohandle fname h contents
1662 appendFile :: FilePath -> String -> IO ()
1663 appendFile fname contents
1664 = copy_String_to_cstring fname >>= \ptr ->
1665 nh_open ptr 2 >>= \h ->
1667 nh_errno >>= \errno ->
1668 if (isNullAddr h || errno /= 0)
1669 then (ioError.IOError) ("appendFile: can't open file " ++ fname)
1670 else writetohandle fname h contents
1673 -- raises an exception instead of an error
1674 readIO :: Read a => String -> IO a
1675 readIO s = case [x | (x,t) <- reads s, ("","") <- lex t] of
1677 [] -> ioError (userError "PreludeIO.readIO: no parse")
1678 _ -> ioError (userError
1679 "PreludeIO.readIO: ambiguous parse")
1681 readLn :: Read a => IO a
1682 readLn = do l <- getLine
1687 -- End of Hugs standard prelude ----------------------------------------------
1693 instance Show Exception where
1694 showsPrec _ (ErrorCall s) = showString ("error: " ++ s)
1695 showsPrec _ (IOExcept s) = showString ("I/O error: " ++ s)
1697 data IOResult = IOResult deriving (Show)
1699 type FILE_STAR = Addr -- FILE *
1701 foreign import "nHandle" "nh_stdin" nh_stdin :: IO FILE_STAR
1702 foreign import "nHandle" "nh_stdout" nh_stdout :: IO FILE_STAR
1703 foreign import "nHandle" "nh_stderr" nh_stderr :: IO FILE_STAR
1704 foreign import "nHandle" "nh_write" nh_write :: FILE_STAR -> Char -> IO ()
1705 foreign import "nHandle" "nh_read" nh_read :: FILE_STAR -> IO Int
1706 foreign import "nHandle" "nh_open" nh_open :: Addr -> Int -> IO FILE_STAR
1707 foreign import "nHandle" "nh_flush" nh_flush :: FILE_STAR -> IO ()
1708 foreign import "nHandle" "nh_close" nh_close :: FILE_STAR -> IO ()
1709 foreign import "nHandle" "nh_errno" nh_errno :: IO Int
1711 foreign import "nHandle" "nh_malloc" nh_malloc :: Int -> IO Addr
1712 foreign import "nHandle" "nh_free" nh_free :: Addr -> IO ()
1713 foreign import "nHandle" "nh_store" nh_store :: Addr -> Char -> IO ()
1714 foreign import "nHandle" "nh_load" nh_load :: Addr -> IO Char
1715 foreign import "nHandle" "nh_getenv" nh_getenv :: Addr -> IO Addr
1717 copy_String_to_cstring :: String -> IO Addr
1718 copy_String_to_cstring s
1719 = nh_malloc (1 + length s) >>= \ptr0 ->
1720 let loop ptr [] = nh_store ptr (chr 0) >> return ptr0
1721 loop ptr (c:cs) = nh_store ptr c >> loop (incAddr ptr) cs
1724 then error "copy_String_to_cstring: malloc failed"
1727 copy_cstring_to_String :: Addr -> IO String
1728 copy_cstring_to_String ptr
1729 = nh_load ptr >>= \ci ->
1732 else copy_cstring_to_String (incAddr ptr) >>= \cs ->
1735 readfromhandle :: FILE_STAR -> IO String
1737 = unsafeInterleaveIO (
1738 nh_read h >>= \ci ->
1739 if ci == -1 {-EOF-} then return "" else
1740 readfromhandle h >>= \restOfFile -> return ((primIntToChar ci) : restOfFile)
1743 writetohandle :: String -> FILE_STAR -> String -> IO ()
1744 writetohandle fname h []
1746 nh_errno >>= \errno ->
1749 else error ( "writeFile/appendFile: error closing file " ++ fname)
1750 writetohandle fname h (c:cs)
1751 = nh_write h c >> writetohandle fname h cs
1753 primGetRawArgs :: IO [String]
1755 = primGetArgc >>= \argc ->
1756 sequence (map get_one_arg [0 .. argc-1])
1758 get_one_arg :: Int -> IO String
1760 = primGetArgv argno >>= \a ->
1761 copy_cstring_to_String a
1763 primGetEnv :: String -> IO String
1765 = copy_String_to_cstring v >>= \ptr ->
1766 nh_getenv ptr >>= \ptr2 ->
1771 copy_cstring_to_String ptr2 >>= \result ->
1775 ------------------------------------------------------------------------------
1776 -- ST, IO --------------------------------------------------------------------
1777 ------------------------------------------------------------------------------
1779 -- Do not change this newtype to a data, or MVars will stop
1780 -- working. In general the MVar stuff is pretty fragile: do
1781 -- not mess with it.
1782 newtype ST s a = ST (s -> (a,s))
1785 type IO a = ST RealWorld a
1788 --primRunST :: (forall s. ST s a) -> a
1789 primRunST :: ST RealWorld a -> a
1790 primRunST m = fst (unST m theWorld)
1792 theWorld :: RealWorld
1793 theWorld = error "primRunST: entered the RealWorld"
1797 instance Functor (ST s) where
1798 fmap f x = x >>= (return . f)
1800 instance Monad (ST s) where
1801 m >> k = ST (\s -> case unST m s of { (a,s') -> unST k s' })
1802 return x = ST (\s -> (x,s))
1803 m >>= k = ST (\s -> case unST m s of { (a,s') -> unST (k a) s' })
1806 -- used when Hugs invokes top level function
1807 primRunIO :: IO () -> ()
1809 = protect (fst (unST m realWorld))
1811 realWorld = error "primRunIO: entered the RealWorld"
1814 = primCatch comp (\e -> fst (unST (putStr (show e ++ "\n")) realWorld))
1816 trace :: String -> a -> a
1818 = (primRunST (putStr ("trace: " ++ s ++ "\n"))) `seq` x
1820 unsafeInterleaveST :: ST s a -> ST s a
1821 unsafeInterleaveST m = ST (\ s -> (fst (unST m s), s))
1823 unsafeInterleaveIO :: IO a -> IO a
1824 unsafeInterleaveIO = unsafeInterleaveST
1827 ------------------------------------------------------------------------------
1828 -- Word, Addr, StablePtr, Prim*Array, ThreadId, MVar -------------------------
1829 ------------------------------------------------------------------------------
1833 nullAddr = primIntToAddr 0
1834 incAddr a = primIntToAddr (1 + primAddrToInt a)
1835 isNullAddr a = 0 == primAddrToInt a
1837 instance Eq Addr where
1841 instance Ord Addr where
1850 instance Eq Word where
1854 instance Ord Word where
1863 makeStablePtr :: a -> IO (StablePtr a)
1864 makeStablePtr = primMakeStablePtr
1865 deRefStablePtr :: StablePtr a -> IO a
1866 deRefStablePtr = primDeRefStablePtr
1867 freeStablePtr :: StablePtr a -> IO ()
1868 freeStablePtr = primFreeStablePtr
1871 data PrimArray a -- immutable arrays with Int indices
1874 data Ref s a -- mutable variables
1875 data PrimMutableArray s a -- mutable arrays with Int indices
1876 data PrimMutableByteArray s
1883 newMVar :: IO (MVar a)
1884 newMVar = primNewMVar
1886 putMVar :: MVar a -> a -> IO ()
1887 putMVar = primPutMVar
1889 takeMVar :: MVar a -> IO a
1891 = ST (\world -> primTakeMVar m cont world)
1893 -- cont :: a -> RealWorld -> (a,RealWorld)
1894 -- where 'a' is as in the top-level signature
1895 cont x world = (x,world)
1897 -- the type of the handwritten BCO (threesome) primTakeMVar is
1898 -- primTakeMVar :: MVar a
1899 -- -> (a -> RealWorld -> (a,RealWorld))
1903 -- primTakeMVar behaves like this:
1905 -- primTakeMVar (MVar# m#) cont world
1906 -- = primTakeMVar_wrk m# cont world
1908 -- primTakeMVar_wrk m# cont world
1909 -- = cont (takeMVar# m#) world
1911 -- primTakeMVar_wrk has the special property that it is
1912 -- restartable by the scheduler, should the MVar be empty.
1915 -- showFloat ------------------------------------------------------------------
1917 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
1918 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
1919 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
1920 showFloat :: (RealFloat a) => a -> ShowS
1922 showEFloat d x = showString (formatRealFloat FFExponent d x)
1923 showFFloat d x = showString (formatRealFloat FFFixed d x)
1924 showGFloat d x = showString (formatRealFloat FFGeneric d x)
1925 showFloat = showGFloat Nothing
1927 -- These are the format types. This type is not exported.
1929 data FFFormat = FFExponent | FFFixed | FFGeneric
1931 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
1932 formatRealFloat fmt decs x = s
1936 else if isInfinite x then
1937 if x < 0 then "-Infinity" else "Infinity"
1938 else if x < 0 || isNegativeZero x then
1939 '-' : doFmt fmt (floatToDigits (toInteger base) (-x))
1941 doFmt fmt (floatToDigits (toInteger base) x)
1943 let ds = map intToDigit is
1946 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
1953 [d] -> d : ".0e" ++ show (e-1)
1954 d:ds -> d : '.' : ds ++ 'e':show (e-1)
1956 let dec' = max dec 1 in
1958 [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
1960 let (ei, is') = roundTo base (dec'+1) is
1961 d:ds = map intToDigit
1962 (if ei > 0 then init is' else is')
1963 in d:'.':ds ++ "e" ++ show (e-1+ei)
1967 let f 0 s ds = mk0 s ++ "." ++ mk0 ds
1968 f n s "" = f (n-1) (s++"0") ""
1969 f n s (d:ds) = f (n-1) (s++[d]) ds
1974 let dec' = max dec 0 in
1976 let (ei, is') = roundTo base (dec' + e) is
1977 (ls, rs) = splitAt (e+ei) (map intToDigit is')
1978 in (if null ls then "0" else ls) ++
1979 (if null rs then "" else '.' : rs)
1981 let (ei, is') = roundTo base dec'
1982 (replicate (-e) 0 ++ is)
1983 d : ds = map intToDigit
1984 (if ei > 0 then is' else 0:is')
1987 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
1988 roundTo base d is = case f d is of
1990 (1, is) -> (1, 1 : is)
1991 where b2 = base `div` 2
1992 f n [] = (0, replicate n 0)
1993 f 0 (i:_) = (if i >= b2 then 1 else 0, [])
1995 let (c, ds) = f (d-1) is
1997 in if i' == base then (1, 0:ds) else (0, i':ds)
1999 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
2000 -- by R.G. Burger and R. K. Dybvig, in PLDI 96.
2001 -- This version uses a much slower logarithm estimator. It should be improved.
2003 -- This function returns a list of digits (Ints in [0..base-1]) and an
2006 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
2008 floatToDigits _ 0 = ([0], 0)
2009 floatToDigits base x =
2010 let (f0, e0) = decodeFloat x
2011 (minExp0, _) = floatRange x
2014 minExp = minExp0 - p -- the real minimum exponent
2015 -- Haskell requires that f be adjusted so denormalized numbers
2016 -- will have an impossibly low exponent. Adjust for this.
2017 (f, e) = let n = minExp - e0
2018 in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
2023 if f == b^(p-1) then
2024 (f*be*b*2, 2*b, be*b, b)
2028 if e > minExp && f == b^(p-1) then
2029 (f*b*2, b^(-e+1)*2, b, 1)
2031 (f*2, b^(-e)*2, 1, 1)
2034 if b == 2 && base == 10 then
2035 -- logBase 10 2 is slightly bigger than 3/10 so
2036 -- the following will err on the low side. Ignoring
2037 -- the fraction will make it err even more.
2038 -- Haskell promises that p-1 <= logBase b f < p.
2039 (p - 1 + e0) * 3 `div` 10
2041 ceiling ((log (fromInteger (f+1)) +
2042 fromInt e * log (fromInteger b)) /
2043 log (fromInteger base))
2046 if r + mUp <= expt base n * s then n else fixup (n+1)
2048 if expt base (-n) * (r + mUp) <= s then n
2052 gen ds rn sN mUpN mDnN =
2053 let (dn, rn') = (rn * base) `divMod` sN
2056 in case (rn' < mDnN', rn' + mUpN' > sN) of
2057 (True, False) -> dn : ds
2058 (False, True) -> dn+1 : ds
2059 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
2060 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
2063 gen [] r (s * expt base k) mUp mDn
2065 let bk = expt base (-k)
2066 in gen [] (r * bk) s (mUp * bk) (mDn * bk)
2067 in (map toInt (reverse rds), k)
2070 -- Exponentiation with a cache for the most common numbers.
2073 expt :: Integer -> Int -> Integer
2075 if base == 2 && n >= minExpt && n <= maxExpt then
2076 expts !! (n-minExpt)
2081 expts = [2^n | n <- [minExpt .. maxExpt]]