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, newEmptyMVar, newMVar, putMVar, takeMVar, readMVar, swapMVar
110 , STRef, newSTRef, readSTRef, writeSTRef
111 , IORef, newIORef, readIORef, writeIORef
113 -- This lot really shouldn't be exported, but are needed to
114 -- implement various libs.
115 ,primCompAux,PrimArray,primRunST,primNewArray,primWriteArray
116 ,primUnsafeFreezeArray,primIndexArray,primGetRawArgs,primGetEnv
117 ,nh_stdin,nh_stdout,nh_stderr,copy_String_to_cstring,nh_open
118 ,nh_free,nh_close,nh_errno,nh_flush,nh_read,primIntToChar
119 ,unsafeInterleaveIO,nh_write,primCharToInt,
120 nullAddr, incAddr, isNullAddr,
121 nh_filesize, nh_iseof, nh_system, nh_exitwith, nh_getPID,
122 nh_getCPUtime, nh_getCPUprec,
125 primGtWord, primGeWord, primEqWord, primNeWord,
126 primLtWord, primLeWord, primMinWord, primMaxWord,
127 primPlusWord, primMinusWord, primTimesWord, primQuotWord,
128 primRemWord, primQuotRemWord, primNegateWord, primAndWord,
129 primOrWord, primXorWord, primNotWord, primShiftLWord,
130 primShiftRAWord, primShiftRLWord, primIntToWord, primWordToInt,
132 primAndInt, primOrInt, primXorInt, primNotInt,
133 primShiftLInt, primShiftRAInt, primShiftRLInt,
135 primAddrToInt, primIntToAddr,
137 primDoubleToFloat, primFloatToDouble,
145 -- Standard value bindings {Prelude} ----------------------------------------
150 infixl 7 *, /, `quot`, `rem`, `div`, `mod`, :%, %
152 --infixr 5 : -- this fixity declaration is hard-wired into Hugs
154 infix 4 ==, /=, <, <=, >=, >, `elem`, `notElem`
159 infixr 0 $, $!, `seq`
161 -- Equality and Ordered classes ---------------------------------------------
164 (==), (/=) :: a -> a -> Bool
166 -- Minimal complete definition: (==) or (/=)
170 class (Eq a) => Ord a where
171 compare :: a -> a -> Ordering
172 (<), (<=), (>=), (>) :: a -> a -> Bool
173 max, min :: a -> a -> a
175 -- Minimal complete definition: (<=) or compare
176 -- using compare can be more efficient for complex types
177 compare x y | x==y = EQ
181 x <= y = compare x y /= GT
182 x < y = compare x y == LT
183 x >= y = compare x y /= LT
184 x > y = compare x y == GT
191 class Bounded a where
192 minBound, maxBound :: a
193 -- Minimal complete definition: All
195 -- Numeric classes ----------------------------------------------------------
197 class (Eq a, Show a) => Num a where
198 (+), (-), (*) :: a -> a -> a
200 abs, signum :: a -> a
201 fromInteger :: Integer -> a
204 -- Minimal complete definition: All, except negate or (-)
206 fromInt = fromIntegral
209 class (Num a, Ord a) => Real a where
210 toRational :: a -> Rational
212 class (Real a, Enum a) => Integral a where
213 quot, rem, div, mod :: a -> a -> a
214 quotRem, divMod :: a -> a -> (a,a)
215 even, odd :: a -> Bool
216 toInteger :: a -> Integer
219 -- Minimal complete definition: quotRem and toInteger
220 n `quot` d = q where (q,r) = quotRem n d
221 n `rem` d = r where (q,r) = quotRem n d
222 n `div` d = q where (q,r) = divMod n d
223 n `mod` d = r where (q,r) = divMod n d
224 divMod n d = if signum r == - signum d then (q-1, r+d) else qr
225 where qr@(q,r) = quotRem n d
226 even n = n `rem` 2 == 0
228 toInt = toInt . toInteger
230 class (Num a) => Fractional a where
233 fromRational :: Rational -> a
234 fromDouble :: Double -> a
236 -- Minimal complete definition: fromRational and ((/) or recip)
238 fromDouble = fromRational . toRational
242 class (Fractional a) => Floating a where
244 exp, log, sqrt :: a -> a
245 (**), logBase :: a -> a -> a
246 sin, cos, tan :: a -> a
247 asin, acos, atan :: a -> a
248 sinh, cosh, tanh :: a -> a
249 asinh, acosh, atanh :: a -> a
251 -- Minimal complete definition: pi, exp, log, sin, cos, sinh, cosh,
252 -- asinh, acosh, atanh
253 x ** y = exp (log x * y)
254 logBase x y = log y / log x
256 tan x = sin x / cos x
257 sinh x = (exp x - exp (-x)) / 2
258 cosh x = (exp x + exp (-x)) / 2
259 tanh x = sinh x / cosh x
260 asinh x = log (x + sqrt (x*x + 1))
261 acosh x = log (x + sqrt (x*x - 1))
262 atanh x = (log (1 + x) - log (1 - x)) / 2
264 class (Real a, Fractional a) => RealFrac a where
265 properFraction :: (Integral b) => a -> (b,a)
266 truncate, round :: (Integral b) => a -> b
267 ceiling, floor :: (Integral b) => a -> b
269 -- Minimal complete definition: properFraction
270 truncate x = m where (m,_) = properFraction x
272 round x = let (n,r) = properFraction x
273 m = if r < 0 then n - 1 else n + 1
274 in case signum (abs r - 0.5) of
276 0 -> if even n then n else m
279 ceiling x = if r > 0 then n + 1 else n
280 where (n,r) = properFraction x
282 floor x = if r < 0 then n - 1 else n
283 where (n,r) = properFraction x
285 class (RealFrac a, Floating a) => RealFloat a where
286 floatRadix :: a -> Integer
287 floatDigits :: a -> Int
288 floatRange :: a -> (Int,Int)
289 decodeFloat :: a -> (Integer,Int)
290 encodeFloat :: Integer -> Int -> a
292 significand :: a -> a
293 scaleFloat :: Int -> a -> a
294 isNaN, isInfinite, isDenormalized, isNegativeZero, isIEEE
298 -- Minimal complete definition: All, except exponent, signficand,
300 exponent x = if m==0 then 0 else n + floatDigits x
301 where (m,n) = decodeFloat x
302 significand x = encodeFloat m (- floatDigits x)
303 where (m,_) = decodeFloat x
304 scaleFloat k x = encodeFloat m (n+k)
305 where (m,n) = decodeFloat x
309 | x<0 && y>0 = pi + atan (y/x)
311 (x<0 && isNegativeZero y) ||
312 (isNegativeZero x && isNegativeZero y)
314 | y==0 && (x<0 || isNegativeZero x)
315 = pi -- must be after the previous test on zero y
316 | x==0 && y==0 = y -- must be after the other double zero tests
317 | otherwise = x + y -- x or y is a NaN, return a NaN (via +)
319 -- Numeric functions --------------------------------------------------------
321 subtract :: Num a => a -> a -> a
324 gcd :: Integral a => a -> a -> a
325 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
326 gcd x y = gcd' (abs x) (abs y)
328 gcd' x y = gcd' y (x `rem` y)
330 lcm :: (Integral a) => a -> a -> a
333 lcm x y = abs ((x `quot` gcd x y) * y)
335 (^) :: (Num a, Integral b) => a -> b -> a
337 x ^ n | n > 0 = f x (n-1) x
339 f x n y = g x n where
340 g x n | even n = g (x*x) (n`quot`2)
341 | otherwise = f x (n-1) (x*y)
342 _ ^ _ = error "Prelude.^: negative exponent"
344 (^^) :: (Fractional a, Integral b) => a -> b -> a
345 x ^^ n = if n >= 0 then x ^ n else recip (x^(-n))
347 fromIntegral :: (Integral a, Num b) => a -> b
348 fromIntegral = fromInteger . toInteger
350 realToFrac :: (Real a, Fractional b) => a -> b
351 realToFrac = fromRational . toRational
353 -- Index and Enumeration classes --------------------------------------------
355 class (Ord a) => Ix a where
356 range :: (a,a) -> [a]
357 index :: (a,a) -> a -> Int
358 inRange :: (a,a) -> a -> Bool
359 rangeSize :: (a,a) -> Int
363 | otherwise = index r u + 1
369 enumFrom :: a -> [a] -- [n..]
370 enumFromThen :: a -> a -> [a] -- [n,m..]
371 enumFromTo :: a -> a -> [a] -- [n..m]
372 enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m]
374 -- Minimal complete definition: toEnum, fromEnum
375 succ = toEnum . (1+) . fromEnum
376 pred = toEnum . subtract 1 . fromEnum
377 enumFromTo x y = map toEnum [ fromEnum x .. fromEnum y ]
378 enumFromThenTo x y z = map toEnum [ fromEnum x, fromEnum y .. fromEnum z ]
380 -- Read and Show classes ------------------------------------------------------
382 type ReadS a = String -> [(a,String)]
383 type ShowS = String -> String
386 readsPrec :: Int -> ReadS a
387 readList :: ReadS [a]
389 -- Minimal complete definition: readsPrec
390 readList = readParen False (\r -> [pr | ("[",s) <- lex r,
392 where readl s = [([],t) | ("]",t) <- lex s] ++
393 [(x:xs,u) | (x,t) <- reads s,
395 readl' s = [([],t) | ("]",t) <- lex s] ++
396 [(x:xs,v) | (",",t) <- lex s,
402 showsPrec :: Int -> a -> ShowS
403 showList :: [a] -> ShowS
405 -- Minimal complete definition: show or showsPrec
406 show x = showsPrec 0 x ""
407 showsPrec _ x s = show x ++ s
408 showList [] = showString "[]"
409 showList (x:xs) = showChar '[' . shows x . showl xs
410 where showl [] = showChar ']'
411 showl (x:xs) = showChar ',' . shows x . showl xs
413 -- Monad classes ------------------------------------------------------------
415 class Functor f where
416 fmap :: (a -> b) -> (f a -> f b)
420 (>>=) :: m a -> (a -> m b) -> m b
421 (>>) :: m a -> m b -> m b
422 fail :: String -> m a
424 -- Minimal complete definition: (>>=), return
425 p >> q = p >>= \ _ -> q
428 sequence :: Monad m => [m a] -> m [a]
429 sequence [] = return []
430 sequence (c:cs) = do x <- c
434 sequence_ :: Monad m => [m a] -> m ()
435 sequence_ = foldr (>>) (return ())
437 mapM :: Monad m => (a -> m b) -> [a] -> m [b]
438 mapM f = sequence . map f
440 mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
441 mapM_ f = sequence_ . map f
443 (=<<) :: Monad m => (a -> m b) -> m a -> m b
446 -- Evaluation and strictness ------------------------------------------------
449 seq x y = primSeq x y
451 ($!) :: (a -> b) -> a -> b
452 f $! x = x `primSeq` f x
454 -- Trivial type -------------------------------------------------------------
456 -- data () = () deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
461 instance Ord () where
467 inRange ((),()) () = True
469 instance Enum () where
473 enumFromThen () () = [()]
475 instance Read () where
476 readsPrec p = readParen False (\r -> [((),t) | ("(",s) <- lex r,
479 instance Show () where
480 showsPrec p () = showString "()"
482 instance Bounded () where
486 -- Boolean type -------------------------------------------------------------
488 data Bool = False | True
489 deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
491 (&&), (||) :: Bool -> Bool -> Bool
504 -- Character type -----------------------------------------------------------
506 data Char -- builtin datatype of ISO Latin characters
507 type String = [Char] -- strings are lists of characters
509 instance Eq Char where (==) = primEqChar
510 instance Ord Char where (<=) = primLeChar
512 instance Enum Char where
513 toEnum = primIntToChar
514 fromEnum = primCharToInt
515 enumFrom c = map toEnum [fromEnum c .. fromEnum (maxBound::Char)]
516 enumFromThen c d = map toEnum [fromEnum c, fromEnum d .. fromEnum (lastChar::Char)]
517 where lastChar = if d < c then minBound else maxBound
519 instance Ix Char where
520 range (c,c') = [c..c']
522 | inRange b ci = fromEnum ci - fromEnum c
523 | otherwise = error "Ix.index: Index out of range."
524 inRange (c,c') ci = fromEnum c <= i && i <= fromEnum c'
525 where i = fromEnum ci
527 instance Read Char where
528 readsPrec p = readParen False
529 (\r -> [(c,t) | ('\'':s,t) <- lex r,
530 (c,"\'") <- readLitChar s ])
531 readList = readParen False (\r -> [(l,t) | ('"':s, t) <- lex r,
533 where readl ('"':s) = [("",s)]
534 readl ('\\':'&':s) = readl s
535 readl s = [(c:cs,u) | (c ,t) <- readLitChar s,
537 instance Show Char where
538 showsPrec p '\'' = showString "'\\''"
539 showsPrec p c = showChar '\'' . showLitChar c . showChar '\''
541 showList cs = showChar '"' . showl cs
542 where showl "" = showChar '"'
543 showl ('"':cs) = showString "\\\"" . showl cs
544 showl (c:cs) = showLitChar c . showl cs
546 instance Bounded Char where
550 isAscii, isControl, isPrint, isSpace :: Char -> Bool
551 isUpper, isLower, isAlpha, isDigit, isAlphaNum :: Char -> Bool
553 isAscii c = fromEnum c < 128
554 isControl c = c < ' ' || c == '\DEL'
555 isPrint c = c >= ' ' && c <= '~'
556 isSpace c = c == ' ' || c == '\t' || c == '\n' ||
557 c == '\r' || c == '\f' || c == '\v'
558 isUpper c = c >= 'A' && c <= 'Z'
559 isLower c = c >= 'a' && c <= 'z'
560 isAlpha c = isUpper c || isLower c
561 isDigit c = c >= '0' && c <= '9'
562 isAlphaNum c = isAlpha c || isDigit c
564 -- Digit conversion operations
565 digitToInt :: Char -> Int
567 | isDigit c = fromEnum c - fromEnum '0'
568 | c >= 'a' && c <= 'f' = fromEnum c - fromEnum 'a' + 10
569 | c >= 'A' && c <= 'F' = fromEnum c - fromEnum 'A' + 10
570 | otherwise = error "Char.digitToInt: not a digit"
572 intToDigit :: Int -> Char
574 | i >= 0 && i <= 9 = toEnum (fromEnum '0' + i)
575 | i >= 10 && i <= 15 = toEnum (fromEnum 'a' + i - 10)
576 | otherwise = error "Char.intToDigit: not a digit"
578 toUpper, toLower :: Char -> Char
579 toUpper c | isLower c = toEnum (fromEnum c - fromEnum 'a' + fromEnum 'A')
582 toLower c | isUpper c = toEnum (fromEnum c - fromEnum 'A' + fromEnum 'a')
591 -- Maybe type ---------------------------------------------------------------
593 data Maybe a = Nothing | Just a
594 deriving (Eq, Ord, Read, Show)
596 maybe :: b -> (a -> b) -> Maybe a -> b
597 maybe n f Nothing = n
598 maybe n f (Just x) = f x
600 instance Functor Maybe where
601 fmap f Nothing = Nothing
602 fmap f (Just x) = Just (f x)
604 instance Monad Maybe where
606 Nothing >>= k = Nothing
610 -- Either type --------------------------------------------------------------
612 data Either a b = Left a | Right b
613 deriving (Eq, Ord, Read, Show)
615 either :: (a -> c) -> (b -> c) -> Either a b -> c
616 either l r (Left x) = l x
617 either l r (Right y) = r y
619 -- Ordering type ------------------------------------------------------------
621 data Ordering = LT | EQ | GT
622 deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
624 -- Lists --------------------------------------------------------------------
626 --data [a] = [] | a : [a] deriving (Eq, Ord)
628 instance Eq a => Eq [a] where
630 (x:xs) == (y:ys) = x==y && xs==ys
633 instance Ord a => Ord [a] where
634 compare [] (_:_) = LT
636 compare (_:_) [] = GT
637 compare (x:xs) (y:ys) = primCompAux x y (compare xs ys)
639 instance Functor [] where
642 instance Monad [ ] where
643 (x:xs) >>= f = f x ++ (xs >>= f)
648 instance Read a => Read [a] where
649 readsPrec p = readList
651 instance Show a => Show [a] where
652 showsPrec p = showList
654 -- Tuples -------------------------------------------------------------------
656 -- data (a,b) = (a,b) deriving (Eq, Ord, Ix, Read, Show)
659 -- Standard Integral types --------------------------------------------------
661 data Int -- builtin datatype of fixed size integers
662 data Integer -- builtin datatype of arbitrary size integers
664 instance Eq Integer where
665 (==) x y = primCompareInteger x y == 0
667 instance Ord Integer where
668 compare x y = case primCompareInteger x y of
673 instance Eq Int where
677 instance Ord Int where
683 instance Num Int where
686 negate = primNegateInt
690 fromInteger = primIntegerToInt
693 instance Bounded Int where
694 minBound = primMinInt
695 maxBound = primMaxInt
697 instance Num Integer where
698 (+) = primPlusInteger
699 (-) = primMinusInteger
700 negate = primNegateInteger
701 (*) = primTimesInteger
705 fromInt = primIntToInteger
707 absReal x | x >= 0 = x
710 signumReal x | x == 0 = 0
714 instance Real Int where
715 toRational x = toInteger x % 1
717 instance Real Integer where
720 instance Integral Int where
721 quotRem = primQuotRemInt
722 toInteger = primIntToInteger
725 instance Integral Integer where
726 quotRem = primQuotRemInteger
727 --divMod = primDivModInteger
729 toInt = primIntegerToInt
731 instance Ix Int where
734 | inRange b i = i - m
735 | otherwise = error "index: Index out of range"
736 inRange (m,n) i = m <= i && i <= n
738 instance Ix Integer where
741 | inRange b i = fromInteger (i - m)
742 | otherwise = error "index: Index out of range"
743 inRange (m,n) i = m <= i && i <= n
745 instance Enum Int where
748 enumFrom = numericEnumFrom
749 enumFromTo = numericEnumFromTo
750 enumFromThen = numericEnumFromThen
751 enumFromThenTo = numericEnumFromThenTo
753 instance Enum Integer where
754 toEnum = primIntToInteger
755 fromEnum = primIntegerToInt
756 enumFrom = numericEnumFrom
757 enumFromTo = numericEnumFromTo
758 enumFromThen = numericEnumFromThen
759 enumFromThenTo = numericEnumFromThenTo
761 numericEnumFrom :: Real a => a -> [a]
762 numericEnumFromThen :: Real a => a -> a -> [a]
763 numericEnumFromTo :: Real a => a -> a -> [a]
764 numericEnumFromThenTo :: Real a => a -> a -> a -> [a]
765 numericEnumFrom n = n : (numericEnumFrom $! (n+1))
766 numericEnumFromThen n m = iterate ((m-n)+) n
767 numericEnumFromTo n m = takeWhile (<= m) (numericEnumFrom n)
768 numericEnumFromThenTo n n' m = takeWhile p (numericEnumFromThen n n')
769 where p | n' >= n = (<= m)
772 instance Read Int where
773 readsPrec p = readSigned readDec
775 instance Show Int where
777 | n == minBound = showSigned showInt p (toInteger n)
778 | otherwise = showSigned showInt p n
780 instance Read Integer where
781 readsPrec p = readSigned readDec
783 instance Show Integer where
784 showsPrec = showSigned showInt
787 -- Standard Floating types --------------------------------------------------
789 data Float -- builtin datatype of single precision floating point numbers
790 data Double -- builtin datatype of double precision floating point numbers
792 instance Eq Float where
796 instance Ord Float where
802 instance Num Float where
805 negate = primNegateFloat
809 fromInteger = primIntegerToFloat
810 fromInt = primIntToFloat
814 instance Eq Double where
818 instance Ord Double where
824 instance Num Double where
826 (-) = primMinusDouble
827 negate = primNegateDouble
828 (*) = primTimesDouble
831 fromInteger = primIntegerToDouble
832 fromInt = primIntToDouble
836 instance Real Float where
837 toRational = floatToRational
839 instance Real Double where
840 toRational = doubleToRational
842 -- Calls to these functions are optimised when passed as arguments to
844 floatToRational :: Float -> Rational
845 doubleToRational :: Double -> Rational
846 floatToRational x = realFloatToRational x
847 doubleToRational x = realFloatToRational x
849 realFloatToRational x = (m%1)*(b%1)^^n
850 where (m,n) = decodeFloat x
853 instance Fractional Float where
854 (/) = primDivideFloat
855 fromRational = rationalToRealFloat
856 fromDouble = primDoubleToFloat
859 instance Fractional Double where
860 (/) = primDivideDouble
861 fromRational = rationalToRealFloat
864 rationalToRealFloat x = x'
866 f e = if e' == e then y else f e'
867 where y = encodeFloat (round (x * (1%b)^^e)) e
868 (_,e') = decodeFloat y
869 (_,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
870 / fromInteger (denominator x))
873 instance Floating Float where
874 pi = 3.14159265358979323846
885 instance Floating Double where
886 pi = 3.14159265358979323846
889 sqrt = primSqrtDouble
893 asin = primAsinDouble
894 acos = primAcosDouble
895 atan = primAtanDouble
897 instance RealFrac Float where
898 properFraction = floatProperFraction
900 instance RealFrac Double where
901 properFraction = floatProperFraction
903 floatProperFraction x
904 | n >= 0 = (fromInteger m * fromInteger b ^ n, 0)
905 | otherwise = (fromInteger w, encodeFloat r n)
906 where (m,n) = decodeFloat x
908 (w,r) = quotRem m (b^(-n))
910 instance RealFloat Float where
911 floatRadix _ = toInteger primRadixFloat
912 floatDigits _ = primDigitsFloat
913 floatRange _ = (primMinExpFloat,primMaxExpFloat)
914 encodeFloat = primEncodeFloatZ
915 decodeFloat = primDecodeFloatZ
916 isNaN = primIsNaNFloat
917 isInfinite = primIsInfiniteFloat
918 isDenormalized= primIsDenormalizedFloat
919 isNegativeZero= primIsNegativeZeroFloat
920 isIEEE = const primIsIEEEFloat
922 instance RealFloat Double where
923 floatRadix _ = toInteger primRadixDouble
924 floatDigits _ = primDigitsDouble
925 floatRange _ = (primMinExpDouble,primMaxExpDouble)
926 encodeFloat = primEncodeDoubleZ
927 decodeFloat = primDecodeDoubleZ
928 isNaN = primIsNaNDouble
929 isInfinite = primIsInfiniteDouble
930 isDenormalized= primIsDenormalizedDouble
931 isNegativeZero= primIsNegativeZeroDouble
932 isIEEE = const primIsIEEEDouble
934 instance Enum Float where
935 toEnum = primIntToFloat
937 enumFrom = numericEnumFrom
938 enumFromThen = numericEnumFromThen
939 enumFromTo n m = numericEnumFromTo n (m+1/2)
940 enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
942 instance Enum Double where
943 toEnum = primIntToDouble
945 enumFrom = numericEnumFrom
946 enumFromThen = numericEnumFromThen
947 enumFromTo n m = numericEnumFromTo n (m+1/2)
948 enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
950 instance Read Float where
951 readsPrec p = readSigned readFloat
953 instance Show Float where
954 showsPrec p = showSigned showFloat p
956 instance Read Double where
957 readsPrec p = readSigned readFloat
959 instance Show Double where
960 showsPrec p = showSigned showFloat p
963 -- Some standard functions --------------------------------------------------
971 curry :: ((a,b) -> c) -> (a -> b -> c)
972 curry f x y = f (x,y)
974 uncurry :: (a -> b -> c) -> ((a,b) -> c)
975 uncurry f p = f (fst p) (snd p)
983 (.) :: (b -> c) -> (a -> b) -> (a -> c)
986 flip :: (a -> b -> c) -> b -> a -> c
989 ($) :: (a -> b) -> a -> b
992 until :: (a -> Bool) -> (a -> a) -> a -> a
993 until p f x = if p x then x else until p f (f x)
995 asTypeOf :: a -> a -> a
999 error msg = primRaise (ErrorCall msg)
1002 undefined | False = undefined
1004 -- Standard functions on rational numbers {PreludeRatio} --------------------
1006 data Integral a => Ratio a = a :% a deriving (Eq)
1007 type Rational = Ratio Integer
1009 (%) :: Integral a => a -> a -> Ratio a
1010 x % y = reduce (x * signum y) (abs y)
1012 reduce :: Integral a => a -> a -> Ratio a
1013 reduce x y | y == 0 = error "Ratio.%: zero denominator"
1014 | otherwise = (x `quot` d) :% (y `quot` d)
1017 numerator, denominator :: Integral a => Ratio a -> a
1018 numerator (x :% y) = x
1019 denominator (x :% y) = y
1021 instance Integral a => Ord (Ratio a) where
1022 compare (x:%y) (x':%y') = compare (x*y') (x'*y)
1024 instance Integral a => Num (Ratio a) where
1025 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
1026 (x:%y) * (x':%y') = reduce (x*x') (y*y')
1027 negate (x :% y) = negate x :% y
1028 abs (x :% y) = abs x :% y
1029 signum (x :% y) = signum x :% 1
1030 fromInteger x = fromInteger x :% 1
1031 fromInt = intToRatio
1033 -- Hugs optimises code of the form fromRational (intToRatio x)
1034 intToRatio :: Integral a => Int -> Ratio a
1035 intToRatio x = fromInt x :% 1
1037 instance Integral a => Real (Ratio a) where
1038 toRational (x:%y) = toInteger x :% toInteger y
1040 instance Integral a => Fractional (Ratio a) where
1041 (x:%y) / (x':%y') = (x*y') % (y*x')
1042 recip (x:%y) = if x < 0 then (-y) :% (-x) else y :% x
1043 fromRational (x:%y) = fromInteger x :% fromInteger y
1044 fromDouble = doubleToRatio
1046 -- Hugs optimises code of the form fromRational (doubleToRatio x)
1047 doubleToRatio :: Integral a => Double -> Ratio a
1049 | n>=0 = (fromInteger m * fromInteger b ^ n) % 1
1050 | otherwise = fromInteger m % (fromInteger b ^ (-n))
1051 where (m,n) = decodeFloat x
1054 instance Integral a => RealFrac (Ratio a) where
1055 properFraction (x:%y) = (fromIntegral q, r:%y)
1056 where (q,r) = quotRem x y
1058 instance Integral a => Enum (Ratio a) where
1061 enumFrom = numericEnumFrom
1062 enumFromThen = numericEnumFromThen
1064 instance (Read a, Integral a) => Read (Ratio a) where
1065 readsPrec p = readParen (p > 7)
1066 (\r -> [(x%y,u) | (x,s) <- reads r,
1070 instance Integral a => Show (Ratio a) where
1071 showsPrec p (x:%y) = showParen (p > 7)
1072 (shows x . showString " % " . shows y)
1074 approxRational :: RealFrac a => a -> a -> Rational
1075 approxRational x eps = simplest (x-eps) (x+eps)
1076 where simplest x y | y < x = simplest y x
1078 | x > 0 = simplest' n d n' d'
1079 | y < 0 = - simplest' (-n') d' (-n) d
1080 | otherwise = 0 :% 1
1081 where xr@(n:%d) = toRational x
1082 (n':%d') = toRational y
1083 simplest' n d n' d' -- assumes 0 < n%d < n'%d'
1085 | q /= q' = (q+1) :% 1
1086 | otherwise = (q*n''+d'') :% n''
1087 where (q,r) = quotRem n d
1088 (q',r') = quotRem n' d'
1089 (n'':%d'') = simplest' d' r' d r
1091 -- Standard list functions {PreludeList} ------------------------------------
1098 last (_:xs) = last xs
1105 init (x:xs) = x : init xs
1111 (++) :: [a] -> [a] -> [a]
1113 (x:xs) ++ ys = x : (xs ++ ys)
1115 map :: (a -> b) -> [a] -> [b]
1116 --map f xs = [ f x | x <- xs ]
1118 map f (x:xs) = f x : map f xs
1121 filter :: (a -> Bool) -> [a] -> [a]
1122 --filter p xs = [ x | x <- xs, p x ]
1124 filter p (x:xs) = if p x then x : filter p xs else filter p xs
1127 concat :: [[a]] -> [a]
1128 --concat = foldr (++) []
1130 concat (xs:xss) = xs ++ concat xss
1132 length :: [a] -> Int
1133 --length = foldl' (\n _ -> n + 1) 0
1135 length (x:xs) = let n = length xs in primSeq n (1+n)
1137 (!!) :: [b] -> Int -> b
1139 (_:xs) !! n | n>0 = xs !! (n-1)
1140 (_:_) !! _ = error "Prelude.!!: negative index"
1141 [] !! _ = error "Prelude.!!: index too large"
1143 foldl :: (a -> b -> a) -> a -> [b] -> a
1145 foldl f z (x:xs) = foldl f (f z x) xs
1147 foldl' :: (a -> b -> a) -> a -> [b] -> a
1149 foldl' f a (x:xs) = (foldl' f $! f a x) xs
1151 foldl1 :: (a -> a -> a) -> [a] -> a
1152 foldl1 f (x:xs) = foldl f x xs
1154 scanl :: (a -> b -> a) -> a -> [b] -> [a]
1155 scanl f q xs = q : (case xs of
1157 x:xs -> scanl f (f q x) xs)
1159 scanl1 :: (a -> a -> a) -> [a] -> [a]
1160 scanl1 f (x:xs) = scanl f x xs
1162 foldr :: (a -> b -> b) -> b -> [a] -> b
1164 foldr f z (x:xs) = f x (foldr f z xs)
1166 foldr1 :: (a -> a -> a) -> [a] -> a
1168 foldr1 f (x:xs) = f x (foldr1 f xs)
1170 scanr :: (a -> b -> b) -> b -> [a] -> [b]
1171 scanr f q0 [] = [q0]
1172 scanr f q0 (x:xs) = f x q : qs
1173 where qs@(q:_) = scanr f q0 xs
1175 scanr1 :: (a -> a -> a) -> [a] -> [a]
1177 scanr1 f (x:xs) = f x q : qs
1178 where qs@(q:_) = scanr1 f xs
1180 iterate :: (a -> a) -> a -> [a]
1181 iterate f x = x : iterate f (f x)
1184 repeat x = xs where xs = x:xs
1186 replicate :: Int -> a -> [a]
1187 replicate n x = take n (repeat x)
1190 cycle [] = error "Prelude.cycle: empty list"
1191 cycle xs = xs' where xs'=xs++xs'
1193 take :: Int -> [a] -> [a]
1196 take n (x:xs) | n>0 = x : take (n-1) xs
1197 take _ _ = error "Prelude.take: negative argument"
1199 drop :: Int -> [a] -> [a]
1202 drop n (_:xs) | n>0 = drop (n-1) xs
1203 drop _ _ = error "Prelude.drop: negative argument"
1205 splitAt :: Int -> [a] -> ([a], [a])
1206 splitAt 0 xs = ([],xs)
1207 splitAt _ [] = ([],[])
1208 splitAt n (x:xs) | n>0 = (x:xs',xs'') where (xs',xs'') = splitAt (n-1) xs
1209 splitAt _ _ = error "Prelude.splitAt: negative argument"
1211 takeWhile :: (a -> Bool) -> [a] -> [a]
1214 | p x = x : takeWhile p xs
1217 dropWhile :: (a -> Bool) -> [a] -> [a]
1219 dropWhile p xs@(x:xs')
1220 | p x = dropWhile p xs'
1223 span, break :: (a -> Bool) -> [a] -> ([a],[a])
1227 | otherwise = ([],xs)
1228 where (ys,zs) = span p xs'
1229 break p = span (not . p)
1231 lines :: String -> [String]
1233 lines s = let (l,s') = break ('\n'==) s
1234 in l : case s' of [] -> []
1235 (_:s'') -> lines s''
1237 words :: String -> [String]
1238 words s = case dropWhile isSpace s of
1241 where (w,s'') = break isSpace s'
1243 unlines :: [String] -> String
1244 unlines = concatMap (\l -> l ++ "\n")
1246 unwords :: [String] -> String
1248 unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
1250 reverse :: [a] -> [a]
1251 --reverse = foldl (flip (:)) []
1252 reverse xs = ri [] xs
1253 where ri acc [] = acc
1254 ri acc (x:xs) = ri (x:acc) xs
1256 and, or :: [Bool] -> Bool
1257 --and = foldr (&&) True
1258 --or = foldr (||) False
1260 and (x:xs) = if x then and xs else x
1262 or (x:xs) = if x then x else or xs
1264 any, all :: (a -> Bool) -> [a] -> Bool
1265 --any p = or . map p
1266 --all p = and . map p
1268 any p (x:xs) = if p x then True else any p xs
1270 all p (x:xs) = if p x then all p xs else False
1272 elem, notElem :: Eq a => a -> [a] -> Bool
1274 --notElem = all . (/=)
1276 elem x (y:ys) = if x==y then True else elem x ys
1278 notElem x (y:ys) = if x==y then False else notElem x ys
1280 lookup :: Eq a => a -> [(a,b)] -> Maybe b
1281 lookup k [] = Nothing
1282 lookup k ((x,y):xys)
1284 | otherwise = lookup k xys
1286 sum, product :: Num a => [a] -> a
1288 product = foldl' (*) 1
1290 maximum, minimum :: Ord a => [a] -> a
1291 maximum = foldl1 max
1292 minimum = foldl1 min
1294 concatMap :: (a -> [b]) -> [a] -> [b]
1295 concatMap f = concat . map f
1297 zip :: [a] -> [b] -> [(a,b)]
1298 zip = zipWith (\a b -> (a,b))
1300 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
1301 zip3 = zipWith3 (\a b c -> (a,b,c))
1303 zipWith :: (a->b->c) -> [a]->[b]->[c]
1304 zipWith z (a:as) (b:bs) = z a b : zipWith z as bs
1307 zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
1308 zipWith3 z (a:as) (b:bs) (c:cs)
1309 = z a b c : zipWith3 z as bs cs
1310 zipWith3 _ _ _ _ = []
1312 unzip :: [(a,b)] -> ([a],[b])
1313 unzip = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
1315 unzip3 :: [(a,b,c)] -> ([a],[b],[c])
1316 unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
1319 -- PreludeText ----------------------------------------------------------------
1321 reads :: Read a => ReadS a
1324 shows :: Show a => a -> ShowS
1327 read :: Read a => String -> a
1328 read s = case [x | (x,t) <- reads s, ("","") <- lex t] of
1330 [] -> error "Prelude.read: no parse"
1331 _ -> error "Prelude.read: ambiguous parse"
1333 showChar :: Char -> ShowS
1336 showString :: String -> ShowS
1339 showParen :: Bool -> ShowS -> ShowS
1340 showParen b p = if b then showChar '(' . p . showChar ')' else p
1342 showField :: Show a => String -> a -> ShowS
1343 showField m v = showString m . showChar '=' . shows v
1345 readParen :: Bool -> ReadS a -> ReadS a
1346 readParen b g = if b then mandatory else optional
1347 where optional r = g r ++ mandatory r
1348 mandatory r = [(x,u) | ("(",s) <- lex r,
1349 (x,t) <- optional s,
1353 readField :: Read a => String -> ReadS a
1354 readField m s0 = [ r | (t, s1) <- lex s0, t == m,
1360 lex (c:s) | isSpace c = lex (dropWhile isSpace s)
1361 lex ('\'':s) = [('\'':ch++"'", t) | (ch,'\'':t) <- lexLitChar s,
1363 lex ('"':s) = [('"':str, t) | (str,t) <- lexString s]
1365 lexString ('"':s) = [("\"",s)]
1366 lexString s = [(ch++str, u)
1367 | (ch,t) <- lexStrItem s,
1368 (str,u) <- lexString t ]
1370 lexStrItem ('\\':'&':s) = [("\\&",s)]
1371 lexStrItem ('\\':c:s) | isSpace c
1372 = [("",t) | '\\':t <- [dropWhile isSpace s]]
1373 lexStrItem s = lexLitChar s
1375 lex (c:s) | isSingle c = [([c],s)]
1376 | isSym c = [(c:sym,t) | (sym,t) <- [span isSym s]]
1377 | isAlpha c = [(c:nam,t) | (nam,t) <- [span isIdChar s]]
1378 | isDigit c = [(c:ds++fe,t) | (ds,s) <- [span isDigit s],
1379 (fe,t) <- lexFracExp s ]
1380 | otherwise = [] -- bad character
1382 isSingle c = c `elem` ",;()[]{}_`"
1383 isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
1384 isIdChar c = isAlphaNum c || c `elem` "_'"
1386 lexFracExp ('.':s) = [('.':ds++e,u) | (ds,t) <- lexDigits s,
1388 lexFracExp s = [("",s)]
1390 lexExp (e:s) | e `elem` "eE"
1391 = [(e:c:ds,u) | (c:t) <- [s], c `elem` "+-",
1392 (ds,u) <- lexDigits t] ++
1393 [(e:ds,t) | (ds,t) <- lexDigits s]
1396 lexDigits :: ReadS String
1397 lexDigits = nonnull isDigit
1399 nonnull :: (Char -> Bool) -> ReadS String
1400 nonnull p s = [(cs,t) | (cs@(_:_),t) <- [span p s]]
1402 lexLitChar :: ReadS String
1403 lexLitChar ('\\':s) = [('\\':esc, t) | (esc,t) <- lexEsc s]
1405 lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = [([c],s)] -- "
1406 lexEsc ('^':c:s) | c >= '@' && c <= '_' = [(['^',c],s)]
1407 lexEsc s@(d:_) | isDigit d = lexDigits s
1408 lexEsc s@(c:_) | isUpper c
1409 = let table = ('\DEL',"DEL") : asciiTab
1410 in case [(mne,s') | (c, mne) <- table,
1411 ([],s') <- [lexmatch mne s]]
1415 lexLitChar (c:s) = [([c],s)]
1418 isOctDigit c = c >= '0' && c <= '7'
1419 isHexDigit c = isDigit c || c >= 'A' && c <= 'F'
1420 || c >= 'a' && c <= 'f'
1422 lexmatch :: (Eq a) => [a] -> [a] -> ([a],[a])
1423 lexmatch (x:xs) (y:ys) | x == y = lexmatch xs ys
1424 lexmatch xs ys = (xs,ys)
1426 asciiTab = zip ['\NUL'..' ']
1427 ["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
1428 "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
1429 "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
1430 "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US",
1433 readLitChar :: ReadS Char
1434 readLitChar ('\\':s) = readEsc s
1436 readEsc ('a':s) = [('\a',s)]
1437 readEsc ('b':s) = [('\b',s)]
1438 readEsc ('f':s) = [('\f',s)]
1439 readEsc ('n':s) = [('\n',s)]
1440 readEsc ('r':s) = [('\r',s)]
1441 readEsc ('t':s) = [('\t',s)]
1442 readEsc ('v':s) = [('\v',s)]
1443 readEsc ('\\':s) = [('\\',s)]
1444 readEsc ('"':s) = [('"',s)]
1445 readEsc ('\'':s) = [('\'',s)]
1446 readEsc ('^':c:s) | c >= '@' && c <= '_'
1447 = [(toEnum (fromEnum c - fromEnum '@'), s)]
1448 readEsc s@(d:_) | isDigit d
1449 = [(toEnum n, t) | (n,t) <- readDec s]
1450 readEsc ('o':s) = [(toEnum n, t) | (n,t) <- readOct s]
1451 readEsc ('x':s) = [(toEnum n, t) | (n,t) <- readHex s]
1452 readEsc s@(c:_) | isUpper c
1453 = let table = ('\DEL',"DEL") : asciiTab
1454 in case [(c,s') | (c, mne) <- table,
1455 ([],s') <- [lexmatch mne s]]
1459 readLitChar (c:s) = [(c,s)]
1461 showLitChar :: Char -> ShowS
1462 showLitChar c | c > '\DEL' = showChar '\\' .
1463 protectEsc isDigit (shows (fromEnum c))
1464 showLitChar '\DEL' = showString "\\DEL"
1465 showLitChar '\\' = showString "\\\\"
1466 showLitChar c | c >= ' ' = showChar c
1467 showLitChar '\a' = showString "\\a"
1468 showLitChar '\b' = showString "\\b"
1469 showLitChar '\f' = showString "\\f"
1470 showLitChar '\n' = showString "\\n"
1471 showLitChar '\r' = showString "\\r"
1472 showLitChar '\t' = showString "\\t"
1473 showLitChar '\v' = showString "\\v"
1474 showLitChar '\SO' = protectEsc ('H'==) (showString "\\SO")
1475 showLitChar c = showString ('\\' : snd (asciiTab!!fromEnum c))
1477 protectEsc p f = f . cont
1478 where cont s@(c:_) | p c = "\\&" ++ s
1481 -- Unsigned readers for various bases
1482 readDec, readOct, readHex :: Integral a => ReadS a
1483 readDec = readInt 10 isDigit (\d -> fromEnum d - fromEnum '0')
1484 readOct = readInt 8 isOctDigit (\d -> fromEnum d - fromEnum '0')
1485 readHex = readInt 16 isHexDigit hex
1486 where hex d = fromEnum d -
1489 else fromEnum (if isUpper d then 'A' else 'a') - 10)
1491 -- readInt reads a string of digits using an arbitrary base.
1492 -- Leading minus signs must be handled elsewhere.
1494 readInt :: Integral a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
1495 readInt radix isDig digToInt s =
1496 [(foldl1 (\n d -> n * radix + d) (map (fromIntegral . digToInt) ds), r)
1497 | (ds,r) <- nonnull isDig s ]
1499 -- showInt is used for positive numbers only
1500 showInt :: Integral a => a -> ShowS
1503 = error "Numeric.showInt: can't show negative numbers"
1506 = let (n',d) = quotRem n 10
1507 r' = toEnum (fromEnum '0' + fromIntegral d) : r
1508 in if n' == 0 then r' else showInt n' r'
1510 = case quotRem n 10 of { (n',d) ->
1511 let r' = toEnum (fromEnum '0' + fromIntegral d) : r
1512 in if n' == 0 then r' else showInt n' r'
1516 readSigned:: Real a => ReadS a -> ReadS a
1517 readSigned readPos = readParen False read'
1518 where read' r = read'' r ++
1519 [(-x,t) | ("-",s) <- lex r,
1521 read'' r = [(n,s) | (str,s) <- lex r,
1522 (n,"") <- readPos str]
1524 showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS
1525 showSigned showPos p x = if x < 0 then showParen (p > 6)
1526 (showChar '-' . showPos (-x))
1529 readFloat :: RealFloat a => ReadS a
1530 readFloat r = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r,
1532 where readFix r = [(read (ds++ds'), length ds', t)
1533 | (ds, s) <- lexDigits r
1534 , (ds',t) <- lexFrac s ]
1536 lexFrac ('.':s) = lexDigits s
1537 lexFrac s = [("",s)]
1539 readExp (e:s) | e `elem` "eE" = readExp' s
1542 readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s]
1543 readExp' ('+':s) = readDec s
1544 readExp' s = readDec s
1547 -- Hooks for primitives: -----------------------------------------------------
1548 -- Do not mess with these!
1550 primCompAux :: Ord a => a -> a -> Ordering -> Ordering
1551 primCompAux x y o = case compare x y of EQ -> o; LT -> LT; GT -> GT
1553 primPmInt :: Num a => Int -> a -> Bool
1554 primPmInt n x = fromInt n == x
1556 primPmInteger :: Num a => Integer -> a -> Bool
1557 primPmInteger n x = fromInteger n == x
1559 primPmDouble :: Fractional a => Double -> a -> Bool
1560 primPmDouble n x = fromDouble n == x
1562 -- ToDo: make the message more informative.
1564 primPmFail = error "Pattern Match Failure"
1566 -- used in desugaring Foreign functions
1567 primMkIO :: (RealWorld -> (a,RealWorld)) -> IO a
1570 primCreateAdjThunk :: (a -> b) -> String -> Char -> IO Addr
1571 primCreateAdjThunk fun typestr callconv
1572 = do sp <- makeStablePtr fun
1573 p <- copy_String_to_cstring typestr -- is never freed
1574 a <- primCreateAdjThunkARCH sp p callconv
1577 -- The following primitives are only needed if (n+k) patterns are enabled:
1578 primPmNpk :: Integral a => Int -> a -> Maybe a
1579 primPmNpk n x = if n'<=x then Just (x-n') else Nothing
1580 where n' = fromInt n
1582 primPmSub :: Integral a => Int -> a -> a
1583 primPmSub n x = x - fromInt n
1585 -- Unpack strings generated by the Hugs code generator.
1586 -- Strings can contain \0 provided they're coded right.
1588 -- ToDo: change this (and Hugs code generator) to use ByteArrays
1590 primUnpackString :: Addr -> String
1591 primUnpackString a = unpack 0
1593 -- The following decoding is based on evalString in the old machine.c
1596 | c == '\\' = if '\\' == primIndexCharOffAddr a (i+1)
1597 then '\\' : unpack (i+2)
1598 else '\0' : unpack (i+2)
1599 | otherwise = c : unpack (i+1)
1601 c = primIndexCharOffAddr a i
1604 -- Monadic I/O: --------------------------------------------------------------
1606 type FilePath = String
1608 --data IOError = ...
1609 --instance Eq IOError ...
1610 --instance Show IOError ...
1612 data IOError = IOError String
1613 instance Show IOError where
1614 showsPrec _ (IOError s) = showString ("I/O error: " ++ s)
1616 ioError :: IOError -> IO a
1617 ioError (IOError s) = primRaise (IOExcept s)
1619 userError :: String -> IOError
1620 userError s = primRaise (ErrorCall s)
1622 catch :: IO a -> (IOError -> IO a) -> IO a
1624 = ST (\s -> unST m s `primCatch` \ err -> unST (k (e2ioe err)) s)
1626 e2ioe (IOExcept s) = IOError s
1627 e2ioe other = IOError (show other)
1629 putChar :: Char -> IO ()
1630 putChar c = nh_stdout >>= \h -> nh_write h c
1632 putStr :: String -> IO ()
1633 putStr s = nh_stdout >>= \h ->
1634 let loop [] = nh_flush h
1635 loop (c:cs) = nh_write h c >> loop cs
1638 putStrLn :: String -> IO ()
1639 putStrLn s = do { putStr s; putChar '\n' }
1641 print :: Show a => a -> IO ()
1642 print = putStrLn . show
1645 getChar = unsafeInterleaveIO (
1647 nh_read h >>= \ci ->
1648 return (primIntToChar ci)
1651 getLine :: IO String
1652 getLine = do c <- getChar
1653 if c=='\n' then return ""
1654 else do cs <- getLine
1657 getContents :: IO String
1658 getContents = nh_stdin >>= \h -> readfromhandle h
1660 interact :: (String -> String) -> IO ()
1661 interact f = getContents >>= (putStr . f)
1663 readFile :: FilePath -> IO String
1665 = copy_String_to_cstring fname >>= \ptr ->
1666 nh_open ptr 0 >>= \h ->
1668 nh_errno >>= \errno ->
1669 if (isNullAddr h || errno /= 0)
1670 then (ioError.IOError) ("readFile: can't open file " ++ fname)
1671 else readfromhandle h
1673 writeFile :: FilePath -> String -> IO ()
1674 writeFile fname contents
1675 = copy_String_to_cstring fname >>= \ptr ->
1676 nh_open ptr 1 >>= \h ->
1678 nh_errno >>= \errno ->
1679 if (isNullAddr h || errno /= 0)
1680 then (ioError.IOError) ("writeFile: can't create file " ++ fname)
1681 else writetohandle fname h contents
1683 appendFile :: FilePath -> String -> IO ()
1684 appendFile fname contents
1685 = copy_String_to_cstring fname >>= \ptr ->
1686 nh_open ptr 2 >>= \h ->
1688 nh_errno >>= \errno ->
1689 if (isNullAddr h || errno /= 0)
1690 then (ioError.IOError) ("appendFile: can't open file " ++ fname)
1691 else writetohandle fname h contents
1694 -- raises an exception instead of an error
1695 readIO :: Read a => String -> IO a
1696 readIO s = case [x | (x,t) <- reads s, ("","") <- lex t] of
1698 [] -> ioError (userError "PreludeIO.readIO: no parse")
1699 _ -> ioError (userError
1700 "PreludeIO.readIO: ambiguous parse")
1702 readLn :: Read a => IO a
1703 readLn = do l <- getLine
1708 -- End of Hugs standard prelude ----------------------------------------------
1714 instance Show Exception where
1715 showsPrec _ (ErrorCall s) = showString ("error: " ++ s)
1716 showsPrec _ (IOExcept s) = showString ("I/O error: " ++ s)
1718 data IOResult = IOResult deriving (Show)
1720 type FILE_STAR = Addr -- FILE *
1722 foreign import "nHandle" "nh_stdin" nh_stdin :: IO FILE_STAR
1723 foreign import "nHandle" "nh_stdout" nh_stdout :: IO FILE_STAR
1724 foreign import "nHandle" "nh_stderr" nh_stderr :: IO FILE_STAR
1725 foreign import "nHandle" "nh_write" nh_write :: FILE_STAR -> Char -> IO ()
1726 foreign import "nHandle" "nh_read" nh_read :: FILE_STAR -> IO Int
1727 foreign import "nHandle" "nh_open" nh_open :: Addr -> Int -> IO FILE_STAR
1728 foreign import "nHandle" "nh_flush" nh_flush :: FILE_STAR -> IO ()
1729 foreign import "nHandle" "nh_close" nh_close :: FILE_STAR -> IO ()
1730 foreign import "nHandle" "nh_errno" nh_errno :: IO Int
1732 foreign import "nHandle" "nh_malloc" nh_malloc :: Int -> IO Addr
1733 foreign import "nHandle" "nh_free" nh_free :: Addr -> IO ()
1734 foreign import "nHandle" "nh_store" nh_store :: Addr -> Char -> IO ()
1735 foreign import "nHandle" "nh_load" nh_load :: Addr -> IO Char
1736 foreign import "nHandle" "nh_getenv" nh_getenv :: Addr -> IO Addr
1737 foreign import "nHandle" "nh_filesize" nh_filesize :: FILE_STAR -> IO Int
1738 foreign import "nHandle" "nh_iseof" nh_iseof :: FILE_STAR -> IO Int
1739 foreign import "nHandle" "nh_system" nh_system :: Addr -> IO Int
1740 foreign import "nHandle" "nh_exitwith" nh_exitwith :: Int -> IO ()
1741 foreign import "nHandle" "nh_getPID" nh_getPID :: IO Int
1743 foreign import "nHandle" "nh_getCPUtime" nh_getCPUtime :: IO Double
1744 foreign import "nHandle" "nh_getCPUprec" nh_getCPUprec :: IO Double
1746 copy_String_to_cstring :: String -> IO Addr
1747 copy_String_to_cstring s
1748 = nh_malloc (1 + length s) >>= \ptr0 ->
1749 let loop ptr [] = nh_store ptr (chr 0) >> return ptr0
1750 loop ptr (c:cs) = nh_store ptr c >> loop (incAddr ptr) cs
1753 then error "copy_String_to_cstring: malloc failed"
1756 copy_cstring_to_String :: Addr -> IO String
1757 copy_cstring_to_String ptr
1758 = nh_load ptr >>= \ci ->
1761 else copy_cstring_to_String (incAddr ptr) >>= \cs ->
1764 readfromhandle :: FILE_STAR -> IO String
1766 = unsafeInterleaveIO (
1767 nh_read h >>= \ci ->
1768 if ci == -1 {-EOF-} then return "" else
1769 readfromhandle h >>= \restOfFile -> return ((primIntToChar ci) : restOfFile)
1772 writetohandle :: String -> FILE_STAR -> String -> IO ()
1773 writetohandle fname h []
1775 nh_errno >>= \errno ->
1778 else error ( "writeFile/appendFile: error closing file " ++ fname)
1779 writetohandle fname h (c:cs)
1780 = nh_write h c >> writetohandle fname h cs
1782 primGetRawArgs :: IO [String]
1784 = primGetArgc >>= \argc ->
1785 sequence (map get_one_arg [0 .. argc-1])
1787 get_one_arg :: Int -> IO String
1789 = primGetArgv argno >>= \a ->
1790 copy_cstring_to_String a
1792 primGetEnv :: String -> IO String
1794 = copy_String_to_cstring v >>= \ptr ->
1795 nh_getenv ptr >>= \ptr2 ->
1800 copy_cstring_to_String ptr2 >>= \result ->
1804 ------------------------------------------------------------------------------
1805 -- ST, IO --------------------------------------------------------------------
1806 ------------------------------------------------------------------------------
1808 newtype ST s a = ST (s -> (a,s))
1811 type IO a = ST RealWorld a
1814 --primRunST :: (forall s. ST s a) -> a
1815 primRunST :: ST RealWorld a -> a
1816 primRunST m = fst (unST m theWorld)
1818 theWorld :: RealWorld
1819 theWorld = error "primRunST: entered the RealWorld"
1823 instance Functor (ST s) where
1824 fmap f x = x >>= (return . f)
1826 instance Monad (ST s) where
1827 m >> k = ST (\s -> case unST m s of { (a,s') -> unST k s' })
1828 return x = ST (\s -> (x,s))
1829 m >>= k = ST (\s -> case unST m s of { (a,s') -> unST (k a) s' })
1832 -- used when Hugs invokes top level function
1833 primRunIO :: IO () -> ()
1835 = protect 5 (fst (unST m realWorld))
1837 realWorld = error "primRunIO: entered the RealWorld"
1838 protect :: Int -> () -> ()
1842 = primCatch (protect (n-1) comp)
1843 (\e -> fst (unST (putStr (show e ++ "\n")) realWorld))
1845 trace, trace_quiet :: String -> a -> a
1847 = trace_quiet ("trace: " ++ s) x
1849 = (primRunST (putStr (s ++ "\n"))) `seq` x
1851 unsafeInterleaveST :: ST s a -> ST s a
1852 unsafeInterleaveST m = ST (\ s -> (fst (unST m s), s))
1854 unsafeInterleaveIO :: IO a -> IO a
1855 unsafeInterleaveIO = unsafeInterleaveST
1858 ------------------------------------------------------------------------------
1859 -- Word, Addr, StablePtr, Prim*Array -----------------------------------------
1860 ------------------------------------------------------------------------------
1864 nullAddr = primIntToAddr 0
1865 incAddr a = primIntToAddr (1 + primAddrToInt a)
1866 isNullAddr a = 0 == primAddrToInt a
1868 instance Eq Addr where
1872 instance Ord Addr where
1880 instance Eq Word where
1884 instance Ord Word where
1892 makeStablePtr :: a -> IO (StablePtr a)
1893 makeStablePtr = primMakeStablePtr
1894 deRefStablePtr :: StablePtr a -> IO a
1895 deRefStablePtr = primDeRefStablePtr
1896 freeStablePtr :: StablePtr a -> IO ()
1897 freeStablePtr = primFreeStablePtr
1900 data PrimArray a -- immutable arrays with Int indices
1903 data STRef s a -- mutable variables
1904 data PrimMutableArray s a -- mutable arrays with Int indices
1905 data PrimMutableByteArray s
1907 newSTRef :: a -> ST s (STRef s a)
1908 newSTRef = primNewRef
1909 readSTRef :: STRef s a -> ST s a
1910 readSTRef = primReadRef
1911 writeSTRef :: STRef s a -> a -> ST s ()
1912 writeSTRef = primWriteRef
1914 type IORef a = STRef RealWorld a
1915 newIORef :: a -> IO (IORef a)
1916 newIORef = primNewRef
1917 readIORef :: IORef a -> IO a
1918 readIORef = primReadRef
1919 writeIORef :: IORef a -> a -> IO ()
1920 writeIORef = primWriteRef
1923 ------------------------------------------------------------------------------
1924 -- ThreadId, MVar, concurrency stuff -----------------------------------------
1925 ------------------------------------------------------------------------------
1929 newEmptyMVar :: IO (MVar a)
1930 newEmptyMVar = primNewEmptyMVar
1932 putMVar :: MVar a -> a -> IO ()
1933 putMVar = primPutMVar
1935 takeMVar :: MVar a -> IO a
1937 = ST (\world -> primTakeMVar m cont world)
1939 -- cont :: a -> RealWorld -> (a,RealWorld)
1940 -- where 'a' is as in the top-level signature
1941 cont x world = (x,world)
1943 -- the type of the handwritten BCO (threesome) primTakeMVar is
1944 -- primTakeMVar :: MVar a
1945 -- -> (a -> RealWorld -> (a,RealWorld))
1949 -- primTakeMVar behaves like this:
1951 -- primTakeMVar (MVar# m#) cont world
1952 -- = primTakeMVar_wrk m# cont world
1954 -- primTakeMVar_wrk m# cont world
1955 -- = cont (takeMVar# m#) world
1957 -- primTakeMVar_wrk has the special property that it is
1958 -- restartable by the scheduler, should the MVar be empty.
1960 newMVar :: a -> IO (MVar a)
1962 newEmptyMVar >>= \ mvar ->
1963 putMVar mvar value >>
1966 readMVar :: MVar a -> IO a
1968 takeMVar mvar >>= \ value ->
1969 putMVar mvar value >>
1972 swapMVar :: MVar a -> a -> IO a
1974 takeMVar mvar >>= \ old ->
1978 instance Eq (MVar a) where
1979 m1 == m2 = primSameMVar m1 m2
1984 instance Eq ThreadId where
1985 tid1 == tid2 = primCmpThreadIds tid1 tid2 == 0
1987 instance Ord ThreadId where
1989 = let r = primCmpThreadIds tid1 tid2
1990 in if r < 0 then LT else if r > 0 then GT else EQ
1993 forkIO :: IO a -> IO ThreadId
1994 -- Simple version; doesn't catch exceptions in computation
1995 -- forkIO computation
1996 -- = primForkIO (primRunST computation)
2001 (unST computation realWorld `primSeq` ())
2002 (\e -> trace_quiet ("forkIO: uncaught exception: " ++ show e) ())
2005 realWorld = error "primForkIO: entered the RealWorld"
2008 -- showFloat ------------------------------------------------------------------
2010 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
2011 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
2012 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
2013 showFloat :: (RealFloat a) => a -> ShowS
2015 showEFloat d x = showString (formatRealFloat FFExponent d x)
2016 showFFloat d x = showString (formatRealFloat FFFixed d x)
2017 showGFloat d x = showString (formatRealFloat FFGeneric d x)
2018 showFloat = showGFloat Nothing
2020 -- These are the format types. This type is not exported.
2022 data FFFormat = FFExponent | FFFixed | FFGeneric
2024 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
2025 formatRealFloat fmt decs x = s
2029 else if isInfinite x then
2030 if x < 0 then "-Infinity" else "Infinity"
2031 else if x < 0 || isNegativeZero x then
2032 '-' : doFmt fmt (floatToDigits (toInteger base) (-x))
2034 doFmt fmt (floatToDigits (toInteger base) x)
2036 let ds = map intToDigit is
2039 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
2046 [d] -> d : ".0e" ++ show (e-1)
2047 d:ds -> d : '.' : ds ++ 'e':show (e-1)
2049 let dec' = max dec 1 in
2051 [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
2053 let (ei, is') = roundTo base (dec'+1) is
2054 d:ds = map intToDigit
2055 (if ei > 0 then init is' else is')
2056 in d:'.':ds ++ "e" ++ show (e-1+ei)
2060 let f 0 s ds = mk0 s ++ "." ++ mk0 ds
2061 f n s "" = f (n-1) (s++"0") ""
2062 f n s (d:ds) = f (n-1) (s++[d]) ds
2067 let dec' = max dec 0 in
2069 let (ei, is') = roundTo base (dec' + e) is
2070 (ls, rs) = splitAt (e+ei) (map intToDigit is')
2071 in (if null ls then "0" else ls) ++
2072 (if null rs then "" else '.' : rs)
2074 let (ei, is') = roundTo base dec'
2075 (replicate (-e) 0 ++ is)
2076 d : ds = map intToDigit
2077 (if ei > 0 then is' else 0:is')
2080 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
2081 roundTo base d is = case f d is of
2083 (1, is) -> (1, 1 : is)
2084 where b2 = base `div` 2
2085 f n [] = (0, replicate n 0)
2086 f 0 (i:_) = (if i >= b2 then 1 else 0, [])
2088 let (c, ds) = f (d-1) is
2090 in if i' == base then (1, 0:ds) else (0, i':ds)
2092 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
2093 -- by R.G. Burger and R. K. Dybvig, in PLDI 96.
2094 -- This version uses a much slower logarithm estimator. It should be improved.
2096 -- This function returns a list of digits (Ints in [0..base-1]) and an
2099 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
2101 floatToDigits _ 0 = ([0], 0)
2102 floatToDigits base x =
2103 let (f0, e0) = decodeFloat x
2104 (minExp0, _) = floatRange x
2107 minExp = minExp0 - p -- the real minimum exponent
2108 -- Haskell requires that f be adjusted so denormalized numbers
2109 -- will have an impossibly low exponent. Adjust for this.
2110 (f, e) = let n = minExp - e0
2111 in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
2116 if f == b^(p-1) then
2117 (f*be*b*2, 2*b, be*b, b)
2121 if e > minExp && f == b^(p-1) then
2122 (f*b*2, b^(-e+1)*2, b, 1)
2124 (f*2, b^(-e)*2, 1, 1)
2127 if b == 2 && base == 10 then
2128 -- logBase 10 2 is slightly bigger than 3/10 so
2129 -- the following will err on the low side. Ignoring
2130 -- the fraction will make it err even more.
2131 -- Haskell promises that p-1 <= logBase b f < p.
2132 (p - 1 + e0) * 3 `div` 10
2134 ceiling ((log (fromInteger (f+1)) +
2135 fromInt e * log (fromInteger b)) /
2136 log (fromInteger base))
2139 if r + mUp <= expt base n * s then n else fixup (n+1)
2141 if expt base (-n) * (r + mUp) <= s then n
2145 gen ds rn sN mUpN mDnN =
2146 let (dn, rn') = (rn * base) `divMod` sN
2149 in case (rn' < mDnN', rn' + mUpN' > sN) of
2150 (True, False) -> dn : ds
2151 (False, True) -> dn+1 : ds
2152 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
2153 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
2156 gen [] r (s * expt base k) mUp mDn
2158 let bk = expt base (-k)
2159 in gen [] (r * bk) s (mUp * bk) (mDn * bk)
2160 in (map toInt (reverse rds), k)
2163 -- Exponentiation with a cache for the most common numbers.
2166 expt :: Integer -> Int -> Integer
2168 if base == 2 && n >= minExpt && n <= maxExpt then
2169 expts !! (n-minExpt)
2174 expts = [2^n | n <- [minExpt .. maxExpt]]