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: STG Hugs _______________________________________________
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), fromDouble,
88 Floating(pi, exp, log, sqrt, (**), logBase, sin, cos, tan,
89 asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh),
90 RealFrac(properFraction, truncate, round, ceiling, floor),
91 RealFloat(floatRadix, floatDigits, floatRange, decodeFloat,
92 encodeFloat, exponent, significand, scaleFloat, isNaN,
93 isInfinite, isDenormalized, isIEEE, isNegativeZero),
94 Monad((>>=), (>>), return, fail),
96 mapM, mapM_, sequence, sequence_, (=<<),
98 (&&), (||), not, otherwise,
99 subtract, even, odd, gcd, lcm, (^), (^^),
100 fromIntegral, realToFrac, atan2,
101 fst, snd, curry, uncurry, id, const, (.), flip, ($), until,
102 asTypeOf, error, undefined,
104 -- Now we have the extra (non standard) thing.
108 , copy_String_to_cstring
128 , prelCleanupAfterRunAction
135 , primUnsafeFreezeArray
137 , primWriteCharOffAddr
144 -- Standard value bindings {Prelude} ----------------------------------------
149 infixl 7 *, /, `quot`, `rem`, `div`, `mod`, :%, %
151 --infixr 5 : -- this fixity declaration is hard-wired into Hugs
153 infix 4 ==, /=, <, <=, >=, >, `elem`, `notElem`
158 infixr 0 $, $!, `seq`
160 -- Equality and Ordered classes ---------------------------------------------
163 (==), (/=) :: a -> a -> Bool
165 -- Minimal complete definition: (==) or (/=)
169 class (Eq a) => Ord a where
170 compare :: a -> a -> Ordering
171 (<), (<=), (>=), (>) :: a -> a -> Bool
172 max, min :: a -> a -> a
174 -- Minimal complete definition: (<=) or compare
175 -- using compare can be more efficient for complex types
176 compare x y | x==y = EQ
180 x <= y = compare x y /= GT
181 x < y = compare x y == LT
182 x >= y = compare x y /= LT
183 x > y = compare x y == GT
190 class Bounded a where
191 minBound, maxBound :: a
192 -- Minimal complete definition: All
194 -- Numeric classes ----------------------------------------------------------
196 class (Eq a, Show a) => Num a where
197 (+), (-), (*) :: a -> a -> a
199 abs, signum :: a -> a
200 fromInteger :: Integer -> a
203 -- Minimal complete definition: All, except negate or (-)
205 fromInt = fromIntegral
208 class (Num a, Ord a) => Real a where
209 toRational :: a -> Rational
211 class (Real a, Enum a) => Integral a where
212 quot, rem, div, mod :: a -> a -> a
213 quotRem, divMod :: a -> a -> (a,a)
214 even, odd :: a -> Bool
215 toInteger :: a -> Integer
218 -- Minimal complete definition: quotRem and toInteger
219 n `quot` d = q where (q,r) = quotRem n d
220 n `rem` d = r where (q,r) = quotRem n d
221 n `div` d = q where (q,r) = divMod n d
222 n `mod` d = r where (q,r) = divMod n d
223 divMod n d = if signum r == - signum d then (q-1, r+d) else qr
224 where qr@(q,r) = quotRem n d
225 even n = n `rem` 2 == 0
227 toInt = toInt . toInteger
229 class (Num a) => Fractional a where
232 fromRational :: Rational -> a
234 -- Minimal complete definition: fromRational and ((/) or recip)
238 fromDouble :: Fractional a => Double -> a
239 fromDouble n = fromRational (toRational n)
241 class (Fractional a) => Floating a where
243 exp, log, sqrt :: a -> a
244 (**), logBase :: a -> a -> a
245 sin, cos, tan :: a -> a
246 asin, acos, atan :: a -> a
247 sinh, cosh, tanh :: a -> a
248 asinh, acosh, atanh :: a -> a
250 -- Minimal complete definition: pi, exp, log, sin, cos, sinh, cosh,
251 -- asinh, acosh, atanh
252 x ** y = exp (log x * y)
253 logBase x y = log y / log x
255 tan x = sin x / cos x
256 sinh x = (exp x - exp (-x)) / 2
257 cosh x = (exp x + exp (-x)) / 2
258 tanh x = sinh x / cosh x
259 asinh x = log (x + sqrt (x*x + 1))
260 acosh x = log (x + sqrt (x*x - 1))
261 atanh x = (log (1 + x) - log (1 - x)) / 2
263 class (Real a, Fractional a) => RealFrac a where
264 properFraction :: (Integral b) => a -> (b,a)
265 truncate, round :: (Integral b) => a -> b
266 ceiling, floor :: (Integral b) => a -> b
268 -- Minimal complete definition: properFraction
269 truncate x = m where (m,_) = properFraction x
271 round x = let (n,r) = properFraction x
272 m = if r < 0 then n - 1 else n + 1
273 in case signum (abs r - 0.5) of
275 0 -> if even n then n else m
278 ceiling x = if r > 0 then n + 1 else n
279 where (n,r) = properFraction x
281 floor x = if r < 0 then n - 1 else n
282 where (n,r) = properFraction x
284 class (RealFrac a, Floating a) => RealFloat a where
285 floatRadix :: a -> Integer
286 floatDigits :: a -> Int
287 floatRange :: a -> (Int,Int)
288 decodeFloat :: a -> (Integer,Int)
289 encodeFloat :: Integer -> Int -> a
291 significand :: a -> a
292 scaleFloat :: Int -> a -> a
293 isNaN, isInfinite, isDenormalized, isNegativeZero, isIEEE
297 -- Minimal complete definition: All, except exponent, signficand,
299 exponent x = if m==0 then 0 else n + floatDigits x
300 where (m,n) = decodeFloat x
301 significand x = encodeFloat m (- floatDigits x)
302 where (m,_) = decodeFloat x
303 scaleFloat k x = encodeFloat m (n+k)
304 where (m,n) = decodeFloat x
308 | x<0 && y>0 = pi + atan (y/x)
310 (x<0 && isNegativeZero y) ||
311 (isNegativeZero x && isNegativeZero y)
313 | y==0 && (x<0 || isNegativeZero x)
314 = pi -- must be after the previous test on zero y
315 | x==0 && y==0 = y -- must be after the other double zero tests
316 | otherwise = x + y -- x or y is a NaN, return a NaN (via +)
318 -- Numeric functions --------------------------------------------------------
320 subtract :: Num a => a -> a -> a
323 gcd :: Integral a => a -> a -> a
324 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
325 gcd x y = gcd' (abs x) (abs y)
327 gcd' x y = gcd' y (x `rem` y)
329 lcm :: (Integral a) => a -> a -> a
332 lcm x y = abs ((x `quot` gcd x y) * y)
334 (^) :: (Num a, Integral b) => a -> b -> a
336 x ^ n | n > 0 = f x (n-1) x
338 f x n y = g x n where
339 g x n | even n = g (x*x) (n`quot`2)
340 | otherwise = f x (n-1) (x*y)
341 _ ^ _ = error "Prelude.^: negative exponent"
343 (^^) :: (Fractional a, Integral b) => a -> b -> a
344 x ^^ n = if n >= 0 then x ^ n else recip (x^(-n))
346 fromIntegral :: (Integral a, Num b) => a -> b
347 fromIntegral = fromInteger . toInteger
349 realToFrac :: (Real a, Fractional b) => a -> b
350 realToFrac = fromRational . toRational
352 -- Index and Enumeration classes --------------------------------------------
354 class (Ord a) => Ix a where
355 range :: (a,a) -> [a]
356 index :: (a,a) -> a -> Int
357 inRange :: (a,a) -> a -> Bool
358 rangeSize :: (a,a) -> Int
362 | otherwise = index r u + 1
368 enumFrom :: a -> [a] -- [n..]
369 enumFromThen :: a -> a -> [a] -- [n,m..]
370 enumFromTo :: a -> a -> [a] -- [n..m]
371 enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m]
373 -- Minimal complete definition: toEnum, fromEnum
374 succ = toEnum . (1+) . fromEnum
375 pred = toEnum . subtract 1 . fromEnum
376 enumFrom x = map toEnum [ fromEnum x .. ]
377 enumFromTo x y = map toEnum [ fromEnum x .. fromEnum y ]
378 enumFromThen x y = map toEnum [ fromEnum x, fromEnum y .. ]
379 enumFromThenTo x y z = map toEnum [ fromEnum x, fromEnum y .. fromEnum z ]
381 -- Read and Show classes ------------------------------------------------------
383 type ReadS a = String -> [(a,String)]
384 type ShowS = String -> String
387 readsPrec :: Int -> ReadS a
388 readList :: ReadS [a]
390 -- Minimal complete definition: readsPrec
391 readList = readParen False (\r -> [pr | ("[",s) <- lex r,
393 where readl s = [([],t) | ("]",t) <- lex s] ++
394 [(x:xs,u) | (x,t) <- reads s,
396 readl' s = [([],t) | ("]",t) <- lex s] ++
397 [(x:xs,v) | (",",t) <- lex s,
403 showsPrec :: Int -> a -> ShowS
404 showList :: [a] -> ShowS
406 -- Minimal complete definition: show or showsPrec
407 show x = showsPrec 0 x ""
408 showsPrec _ x s = show x ++ s
409 showList [] = showString "[]"
410 showList (x:xs) = showChar '[' . shows x . showl xs
411 where showl [] = showChar ']'
412 showl (x:xs) = showChar ',' . shows x . showl xs
414 -- Monad classes ------------------------------------------------------------
416 class Functor f where
417 fmap :: (a -> b) -> (f a -> f b)
421 (>>=) :: m a -> (a -> m b) -> m b
422 (>>) :: m a -> m b -> m b
423 fail :: String -> m a
425 -- Minimal complete definition: (>>=), return
426 p >> q = p >>= \ _ -> q
429 sequence :: Monad m => [m a] -> m [a]
430 sequence [] = return []
431 sequence (c:cs) = do x <- c
435 sequence_ :: Monad m => [m a] -> m ()
436 sequence_ = foldr (>>) (return ())
438 mapM :: Monad m => (a -> m b) -> [a] -> m [b]
439 mapM f = sequence . map f
441 mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
442 mapM_ f = sequence_ . map f
444 (=<<) :: Monad m => (a -> m b) -> m a -> m b
447 -- Evaluation and strictness ------------------------------------------------
450 seq x y = primSeq x y
452 ($!) :: (a -> b) -> a -> b
453 f $! x = x `primSeq` f x
455 -- Trivial type -------------------------------------------------------------
457 -- data () = () deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
462 instance Ord () where
468 inRange ((),()) () = True
470 instance Enum () where
474 enumFromThen () () = [()]
476 instance Read () where
477 readsPrec p = readParen False (\r -> [((),t) | ("(",s) <- lex r,
480 instance Show () where
481 showsPrec p () = showString "()"
483 instance Bounded () where
487 -- Boolean type -------------------------------------------------------------
489 data Bool = False | True
490 deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
492 (&&), (||) :: Bool -> Bool -> Bool
505 -- Character type -----------------------------------------------------------
507 data Char -- builtin datatype of ISO Latin characters
508 type String = [Char] -- strings are lists of characters
510 instance Eq Char where (==) = primEqChar
511 instance Ord Char where (<=) = primLeChar
513 instance Enum Char where
514 toEnum = primIntToChar
515 fromEnum = primCharToInt
516 enumFrom c = map toEnum [fromEnum c .. fromEnum (maxBound::Char)]
517 enumFromThen c d = map toEnum [fromEnum c, fromEnum d .. fromEnum (lastChar::Char)]
518 where lastChar = if d < c then minBound else maxBound
520 instance Ix Char where
521 range (c,c') = [c..c']
523 | inRange b ci = fromEnum ci - fromEnum c
524 | otherwise = error "Ix.index: Index out of range."
525 inRange (c,c') ci = fromEnum c <= i && i <= fromEnum c'
526 where i = fromEnum ci
528 instance Read Char where
529 readsPrec p = readParen False
530 (\r -> [(c,t) | ('\'':s,t) <- lex r,
531 (c,"\'") <- readLitChar s ])
532 readList = readParen False (\r -> [(l,t) | ('"':s, t) <- lex r,
534 where readl ('"':s) = [("",s)]
535 readl ('\\':'&':s) = readl s
536 readl s = [(c:cs,u) | (c ,t) <- readLitChar s,
538 instance Show Char where
539 showsPrec p '\'' = showString "'\\''"
540 showsPrec p c = showChar '\'' . showLitChar c . showChar '\''
542 showList cs = showChar '"' . showl cs
543 where showl "" = showChar '"'
544 showl ('"':cs) = showString "\\\"" . showl cs
545 showl (c:cs) = showLitChar c . showl cs
547 instance Bounded Char where
551 isAscii, isControl, isPrint, isSpace :: Char -> Bool
552 isUpper, isLower, isAlpha, isDigit, isAlphaNum :: Char -> Bool
554 isAscii c = fromEnum c < 128
555 isControl c = c < ' ' || c == '\DEL'
556 isPrint c = c >= ' ' && c <= '~'
557 isSpace c = c == ' ' || c == '\t' || c == '\n' ||
558 c == '\r' || c == '\f' || c == '\v'
559 isUpper c = c >= 'A' && c <= 'Z'
560 isLower c = c >= 'a' && c <= 'z'
561 isAlpha c = isUpper c || isLower c
562 isDigit c = c >= '0' && c <= '9'
563 isAlphaNum c = isAlpha c || isDigit c
565 -- Digit conversion operations
566 digitToInt :: Char -> Int
568 | isDigit c = fromEnum c - fromEnum '0'
569 | c >= 'a' && c <= 'f' = fromEnum c - fromEnum 'a' + 10
570 | c >= 'A' && c <= 'F' = fromEnum c - fromEnum 'A' + 10
571 | otherwise = error "Char.digitToInt: not a digit"
573 intToDigit :: Int -> Char
575 | i >= 0 && i <= 9 = toEnum (fromEnum '0' + i)
576 | i >= 10 && i <= 15 = toEnum (fromEnum 'a' + i - 10)
577 | otherwise = error "Char.intToDigit: not a digit"
579 toUpper, toLower :: Char -> Char
580 toUpper c | isLower c = toEnum (fromEnum c - fromEnum 'a' + fromEnum 'A')
583 toLower c | isUpper c = toEnum (fromEnum c - fromEnum 'A' + fromEnum 'a')
592 -- Maybe type ---------------------------------------------------------------
594 data Maybe a = Nothing | Just a
595 deriving (Eq, Ord, Read, Show)
597 maybe :: b -> (a -> b) -> Maybe a -> b
598 maybe n f Nothing = n
599 maybe n f (Just x) = f x
601 instance Functor Maybe where
602 fmap f Nothing = Nothing
603 fmap f (Just x) = Just (f x)
605 instance Monad Maybe where
607 Nothing >>= k = Nothing
611 -- Either type --------------------------------------------------------------
613 data Either a b = Left a | Right b
614 deriving (Eq, Ord, Read, Show)
616 either :: (a -> c) -> (b -> c) -> Either a b -> c
617 either l r (Left x) = l x
618 either l r (Right y) = r y
620 -- Ordering type ------------------------------------------------------------
622 data Ordering = LT | EQ | GT
623 deriving (Eq, Ord, Ix, Enum, Read, Show, Bounded)
625 -- Lists --------------------------------------------------------------------
627 --data [a] = [] | a : [a] deriving (Eq, Ord)
629 instance Eq a => Eq [a] where
631 (x:xs) == (y:ys) = x==y && xs==ys
634 instance Ord a => Ord [a] where
635 compare [] (_:_) = LT
637 compare (_:_) [] = GT
638 compare (x:xs) (y:ys) = hugsprimCompAux x y (compare xs ys)
640 instance Functor [] where
643 instance Monad [ ] where
644 (x:xs) >>= f = f x ++ (xs >>= f)
649 instance Read a => Read [a] where
650 readsPrec p = readList
652 instance Show a => Show [a] where
653 showsPrec p = showList
655 -- Tuples -------------------------------------------------------------------
657 -- data (a,b) = (a,b) deriving (Eq, Ord, Ix, Read, Show)
660 -- Standard Integral types --------------------------------------------------
662 data Int -- builtin datatype of fixed size integers
663 data Integer -- builtin datatype of arbitrary size integers
665 instance Eq Integer where
666 (==) x y = primCompareInteger x y == 0
668 instance Ord Integer where
669 compare x y = case primCompareInteger x y of
674 instance Eq Int where
678 instance Ord Int where
684 instance Num Int where
687 negate = primNegateInt
691 fromInteger = primIntegerToInt
694 instance Bounded Int where
695 minBound = primMinInt
696 maxBound = primMaxInt
698 instance Num Integer where
699 (+) = primPlusInteger
700 (-) = primMinusInteger
701 negate = primNegateInteger
702 (*) = primTimesInteger
706 fromInt = primIntToInteger
708 absReal x | x >= 0 = x
711 signumReal x | x == 0 = 0
715 instance Real Int where
716 toRational x = toInteger x % 1
718 instance Real Integer where
721 instance Integral Int where
722 quotRem = primQuotRemInt
723 toInteger = primIntToInteger
726 instance Integral Integer where
727 quotRem = primQuotRemInteger
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
857 instance Fractional Double where
858 (/) = primDivideDouble
859 fromRational = rationalToRealFloat
861 rationalToRealFloat x = x'
863 f e = if e' == e then y else f e'
864 where y = encodeFloat (round (x * (1%b)^^e)) e
865 (_,e') = decodeFloat y
866 (_,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'
867 / fromInteger (denominator x))
870 instance Floating Float where
871 pi = 3.14159265358979323846
882 instance Floating Double where
883 pi = 3.14159265358979323846
886 sqrt = primSqrtDouble
890 asin = primAsinDouble
891 acos = primAcosDouble
892 atan = primAtanDouble
894 instance RealFrac Float where
895 properFraction = floatProperFraction
897 instance RealFrac Double where
898 properFraction = floatProperFraction
900 floatProperFraction x
901 | n >= 0 = (fromInteger m * fromInteger b ^ n, 0)
902 | otherwise = (fromInteger w, encodeFloat r n)
903 where (m,n) = decodeFloat x
905 (w,r) = quotRem m (b^(-n))
907 instance RealFloat Float where
908 floatRadix _ = toInteger primRadixFloat
909 floatDigits _ = primDigitsFloat
910 floatRange _ = (primMinExpFloat,primMaxExpFloat)
911 encodeFloat = primEncodeFloatZ
912 decodeFloat = primDecodeFloatZ
913 isNaN = primIsNaNFloat
914 isInfinite = primIsInfiniteFloat
915 isDenormalized= primIsDenormalizedFloat
916 isNegativeZero= primIsNegativeZeroFloat
917 isIEEE = const primIsIEEEFloat
919 instance RealFloat Double where
920 floatRadix _ = toInteger primRadixDouble
921 floatDigits _ = primDigitsDouble
922 floatRange _ = (primMinExpDouble,primMaxExpDouble)
923 encodeFloat = primEncodeDoubleZ
924 decodeFloat = primDecodeDoubleZ
925 isNaN = primIsNaNDouble
926 isInfinite = primIsInfiniteDouble
927 isDenormalized= primIsDenormalizedDouble
928 isNegativeZero= primIsNegativeZeroDouble
929 isIEEE = const primIsIEEEDouble
931 instance Enum Float where
932 toEnum = primIntToFloat
934 enumFrom = numericEnumFrom
935 enumFromThen = numericEnumFromThen
936 enumFromTo n m = numericEnumFromTo n (m+1/2)
937 enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
939 instance Enum Double where
940 toEnum = primIntToDouble
942 enumFrom = numericEnumFrom
943 enumFromThen = numericEnumFromThen
944 enumFromTo n m = numericEnumFromTo n (m+1/2)
945 enumFromThenTo n n' m = numericEnumFromThenTo n n' (m + (n'-n)/2)
947 instance Read Float where
948 readsPrec p = readSigned readFloat
950 instance Show Float where
951 showsPrec p = showSigned showFloat p
953 instance Read Double where
954 readsPrec p = readSigned readFloat
956 instance Show Double where
957 showsPrec p = showSigned showFloat p
960 -- Some standard functions --------------------------------------------------
968 curry :: ((a,b) -> c) -> (a -> b -> c)
969 curry f x y = f (x,y)
971 uncurry :: (a -> b -> c) -> ((a,b) -> c)
972 uncurry f p = f (fst p) (snd p)
980 (.) :: (b -> c) -> (a -> b) -> (a -> c)
983 flip :: (a -> b -> c) -> b -> a -> c
986 ($) :: (a -> b) -> a -> b
989 until :: (a -> Bool) -> (a -> a) -> a -> a
990 until p f x = if p x then x else until p f (f x)
992 asTypeOf :: a -> a -> a
996 error msg = primRaise (ErrorCall msg)
999 undefined | False = undefined
1001 -- Standard functions on rational numbers {PreludeRatio} --------------------
1003 data Integral a => Ratio a = a :% a deriving (Eq)
1004 type Rational = Ratio Integer
1006 (%) :: Integral a => a -> a -> Ratio a
1007 x % y = reduce (x * signum y) (abs y)
1009 reduce :: Integral a => a -> a -> Ratio a
1010 reduce x y | y == 0 = error "Ratio.%: zero denominator"
1011 | otherwise = (x `quot` d) :% (y `quot` d)
1014 numerator, denominator :: Integral a => Ratio a -> a
1015 numerator (x :% y) = x
1016 denominator (x :% y) = y
1018 instance Integral a => Ord (Ratio a) where
1019 compare (x:%y) (x':%y') = compare (x*y') (x'*y)
1021 instance Integral a => Num (Ratio a) where
1022 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
1023 (x:%y) * (x':%y') = reduce (x*x') (y*y')
1024 negate (x :% y) = negate x :% y
1025 abs (x :% y) = abs x :% y
1026 signum (x :% y) = signum x :% 1
1027 fromInteger x = fromInteger x :% 1
1028 fromInt = intToRatio
1030 -- Hugs optimises code of the form fromRational (intToRatio x)
1031 intToRatio :: Integral a => Int -> Ratio a
1032 intToRatio x = fromInt x :% 1
1034 instance Integral a => Real (Ratio a) where
1035 toRational (x:%y) = toInteger x :% toInteger y
1037 instance Integral a => Fractional (Ratio a) where
1038 (x:%y) / (x':%y') = (x*y') % (y*x')
1039 recip (x:%y) = if x < 0 then (-y) :% (-x) else y :% x
1040 fromRational (x:%y) = fromInteger x :% fromInteger y
1042 -- Hugs optimises code of the form fromRational (doubleToRatio x)
1043 doubleToRatio :: Integral a => Double -> Ratio a
1045 | n>=0 = (fromInteger m * fromInteger b ^ n) % 1
1046 | otherwise = fromInteger m % (fromInteger b ^ (-n))
1047 where (m,n) = decodeFloat x
1050 instance Integral a => RealFrac (Ratio a) where
1051 properFraction (x:%y) = (fromIntegral q, r:%y)
1052 where (q,r) = quotRem x y
1054 instance Integral a => Enum (Ratio a) where
1057 enumFrom = numericEnumFrom
1058 enumFromThen = numericEnumFromThen
1060 instance (Read a, Integral a) => Read (Ratio a) where
1061 readsPrec p = readParen (p > 7)
1062 (\r -> [(x%y,u) | (x,s) <- reads r,
1066 instance Integral a => Show (Ratio a) where
1067 showsPrec p (x:%y) = showParen (p > 7)
1068 (shows x . showString " % " . shows y)
1070 approxRational :: RealFrac a => a -> a -> Rational
1071 approxRational x eps = simplest (x-eps) (x+eps)
1072 where simplest x y | y < x = simplest y x
1074 | x > 0 = simplest' n d n' d'
1075 | y < 0 = - simplest' (-n') d' (-n) d
1076 | otherwise = 0 :% 1
1077 where xr@(n:%d) = toRational x
1078 (n':%d') = toRational y
1079 simplest' n d n' d' -- assumes 0 < n%d < n'%d'
1081 | q /= q' = (q+1) :% 1
1082 | otherwise = (q*n''+d'') :% n''
1083 where (q,r) = quotRem n d
1084 (q',r') = quotRem n' d'
1085 (n'':%d'') = simplest' d' r' d r
1087 -- Standard list functions {PreludeList} ------------------------------------
1094 last (_:xs) = last xs
1101 init (x:xs) = x : init xs
1107 (++) :: [a] -> [a] -> [a]
1109 (x:xs) ++ ys = x : (xs ++ ys)
1111 map :: (a -> b) -> [a] -> [b]
1112 --map f xs = [ f x | x <- xs ]
1114 map f (x:xs) = f x : map f xs
1117 filter :: (a -> Bool) -> [a] -> [a]
1118 --filter p xs = [ x | x <- xs, p x ]
1120 filter p (x:xs) = if p x then x : filter p xs else filter p xs
1123 concat :: [[a]] -> [a]
1124 --concat = foldr (++) []
1126 concat (xs:xss) = xs ++ concat xss
1128 length :: [a] -> Int
1129 --length = foldl' (\n _ -> n + 1) 0
1131 length (x:xs) = let n = length xs in primSeq n (1+n)
1133 (!!) :: [b] -> Int -> b
1135 (_:xs) !! n | n>0 = xs !! (n-1)
1136 (_:_) !! _ = error "Prelude.!!: negative index"
1137 [] !! _ = error "Prelude.!!: index too large"
1139 foldl :: (a -> b -> a) -> a -> [b] -> a
1141 foldl f z (x:xs) = foldl f (f z x) xs
1143 foldl' :: (a -> b -> a) -> a -> [b] -> a
1145 foldl' f a (x:xs) = (foldl' f $! f a x) xs
1147 foldl1 :: (a -> a -> a) -> [a] -> a
1148 foldl1 f (x:xs) = foldl f x xs
1150 scanl :: (a -> b -> a) -> a -> [b] -> [a]
1151 scanl f q xs = q : (case xs of
1153 x:xs -> scanl f (f q x) xs)
1155 scanl1 :: (a -> a -> a) -> [a] -> [a]
1156 scanl1 f (x:xs) = scanl f x xs
1158 foldr :: (a -> b -> b) -> b -> [a] -> b
1160 foldr f z (x:xs) = f x (foldr f z xs)
1162 foldr1 :: (a -> a -> a) -> [a] -> a
1164 foldr1 f (x:xs) = f x (foldr1 f xs)
1166 scanr :: (a -> b -> b) -> b -> [a] -> [b]
1167 scanr f q0 [] = [q0]
1168 scanr f q0 (x:xs) = f x q : qs
1169 where qs@(q:_) = scanr f q0 xs
1171 scanr1 :: (a -> a -> a) -> [a] -> [a]
1173 scanr1 f (x:xs) = f x q : qs
1174 where qs@(q:_) = scanr1 f xs
1176 iterate :: (a -> a) -> a -> [a]
1177 iterate f x = x : iterate f (f x)
1180 repeat x = xs where xs = x:xs
1182 replicate :: Int -> a -> [a]
1183 replicate n x = take n (repeat x)
1186 cycle [] = error "Prelude.cycle: empty list"
1187 cycle xs = xs' where xs'=xs++xs'
1189 take :: Int -> [a] -> [a]
1192 take n (x:xs) | n>0 = x : take (n-1) xs
1193 take _ _ = error "Prelude.take: negative argument"
1195 drop :: Int -> [a] -> [a]
1198 drop n (_:xs) | n>0 = drop (n-1) xs
1199 drop _ _ = error "Prelude.drop: negative argument"
1201 splitAt :: Int -> [a] -> ([a], [a])
1202 splitAt 0 xs = ([],xs)
1203 splitAt _ [] = ([],[])
1204 splitAt n (x:xs) | n>0 = (x:xs',xs'') where (xs',xs'') = splitAt (n-1) xs
1205 splitAt _ _ = error "Prelude.splitAt: negative argument"
1207 takeWhile :: (a -> Bool) -> [a] -> [a]
1210 | p x = x : takeWhile p xs
1213 dropWhile :: (a -> Bool) -> [a] -> [a]
1215 dropWhile p xs@(x:xs')
1216 | p x = dropWhile p xs'
1219 span, break :: (a -> Bool) -> [a] -> ([a],[a])
1223 | otherwise = ([],xs)
1224 where (ys,zs) = span p xs'
1225 break p = span (not . p)
1227 lines :: String -> [String]
1229 lines s = let (l,s') = break ('\n'==) s
1230 in l : case s' of [] -> []
1231 (_:s'') -> lines s''
1233 words :: String -> [String]
1234 words s = case dropWhile isSpace s of
1237 where (w,s'') = break isSpace s'
1239 unlines :: [String] -> String
1240 unlines = concatMap (\l -> l ++ "\n")
1242 unwords :: [String] -> String
1244 unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
1246 reverse :: [a] -> [a]
1247 --reverse = foldl (flip (:)) []
1248 reverse xs = ri [] xs
1249 where ri acc [] = acc
1250 ri acc (x:xs) = ri (x:acc) xs
1252 and, or :: [Bool] -> Bool
1253 --and = foldr (&&) True
1254 --or = foldr (||) False
1256 and (x:xs) = if x then and xs else x
1258 or (x:xs) = if x then x else or xs
1260 any, all :: (a -> Bool) -> [a] -> Bool
1261 --any p = or . map p
1262 --all p = and . map p
1264 any p (x:xs) = if p x then True else any p xs
1266 all p (x:xs) = if p x then all p xs else False
1268 elem, notElem :: Eq a => a -> [a] -> Bool
1270 --notElem = all . (/=)
1272 elem x (y:ys) = if x==y then True else elem x ys
1274 notElem x (y:ys) = if x==y then False else notElem x ys
1276 lookup :: Eq a => a -> [(a,b)] -> Maybe b
1277 lookup k [] = Nothing
1278 lookup k ((x,y):xys)
1280 | otherwise = lookup k xys
1282 sum, product :: Num a => [a] -> a
1284 product = foldl' (*) 1
1286 maximum, minimum :: Ord a => [a] -> a
1287 maximum = foldl1 max
1288 minimum = foldl1 min
1290 concatMap :: (a -> [b]) -> [a] -> [b]
1291 concatMap f = concat . map f
1293 zip :: [a] -> [b] -> [(a,b)]
1294 zip = zipWith (\a b -> (a,b))
1296 zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
1297 zip3 = zipWith3 (\a b c -> (a,b,c))
1299 zipWith :: (a->b->c) -> [a]->[b]->[c]
1300 zipWith z (a:as) (b:bs) = z a b : zipWith z as bs
1303 zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
1304 zipWith3 z (a:as) (b:bs) (c:cs)
1305 = z a b c : zipWith3 z as bs cs
1306 zipWith3 _ _ _ _ = []
1308 unzip :: [(a,b)] -> ([a],[b])
1309 unzip = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
1311 unzip3 :: [(a,b,c)] -> ([a],[b],[c])
1312 unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
1315 -- PreludeText ----------------------------------------------------------------
1317 reads :: Read a => ReadS a
1320 shows :: Show a => a -> ShowS
1323 read :: Read a => String -> a
1324 read s = case [x | (x,t) <- reads s, ("","") <- lex t] of
1326 [] -> error "Prelude.read: no parse"
1327 _ -> error "Prelude.read: ambiguous parse"
1329 showChar :: Char -> ShowS
1332 showString :: String -> ShowS
1335 showParen :: Bool -> ShowS -> ShowS
1336 showParen b p = if b then showChar '(' . p . showChar ')' else p
1338 hugsprimShowField :: Show a => String -> a -> ShowS
1339 hugsprimShowField m v = showString m . showChar '=' . shows v
1341 readParen :: Bool -> ReadS a -> ReadS a
1342 readParen b g = if b then mandatory else optional
1343 where optional r = g r ++ mandatory r
1344 mandatory r = [(x,u) | ("(",s) <- lex r,
1345 (x,t) <- optional s,
1349 hugsprimReadField :: Read a => String -> ReadS a
1350 hugsprimReadField m s0 = [ r | (t, s1) <- lex s0, t == m,
1356 lex (c:s) | isSpace c = lex (dropWhile isSpace s)
1357 lex ('\'':s) = [('\'':ch++"'", t) | (ch,'\'':t) <- lexLitChar s,
1359 lex ('"':s) = [('"':str, t) | (str,t) <- lexString s]
1361 lexString ('"':s) = [("\"",s)]
1362 lexString s = [(ch++str, u)
1363 | (ch,t) <- lexStrItem s,
1364 (str,u) <- lexString t ]
1366 lexStrItem ('\\':'&':s) = [("\\&",s)]
1367 lexStrItem ('\\':c:s) | isSpace c
1368 = [("",t) | '\\':t <- [dropWhile isSpace s]]
1369 lexStrItem s = lexLitChar s
1371 lex (c:s) | isSingle c = [([c],s)]
1372 | isSym c = [(c:sym,t) | (sym,t) <- [span isSym s]]
1373 | isAlpha c = [(c:nam,t) | (nam,t) <- [span isIdChar s]]
1374 | isDigit c = [(c:ds++fe,t) | (ds,s) <- [span isDigit s],
1375 (fe,t) <- lexFracExp s ]
1376 | otherwise = [] -- bad character
1378 isSingle c = c `elem` ",;()[]{}_`"
1379 isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
1380 isIdChar c = isAlphaNum c || c `elem` "_'"
1382 lexFracExp ('.':s) = [('.':ds++e,u) | (ds,t) <- lexDigits s,
1384 lexFracExp s = [("",s)]
1386 lexExp (e:s) | e `elem` "eE"
1387 = [(e:c:ds,u) | (c:t) <- [s], c `elem` "+-",
1388 (ds,u) <- lexDigits t] ++
1389 [(e:ds,t) | (ds,t) <- lexDigits s]
1392 lexDigits :: ReadS String
1393 lexDigits = nonnull isDigit
1395 nonnull :: (Char -> Bool) -> ReadS String
1396 nonnull p s = [(cs,t) | (cs@(_:_),t) <- [span p s]]
1398 lexLitChar :: ReadS String
1399 lexLitChar ('\\':s) = [('\\':esc, t) | (esc,t) <- lexEsc s]
1401 lexEsc (c:s) | c `elem` "abfnrtv\\\"'" = [([c],s)] -- "
1402 lexEsc ('^':c:s) | c >= '@' && c <= '_' = [(['^',c],s)]
1403 lexEsc s@(d:_) | isDigit d = lexDigits s
1404 lexEsc s@(c:_) | isUpper c
1405 = let table = ('\DEL',"DEL") : asciiTab
1406 in case [(mne,s') | (c, mne) <- table,
1407 ([],s') <- [lexmatch mne s]]
1411 lexLitChar (c:s) = [([c],s)]
1414 isOctDigit c = c >= '0' && c <= '7'
1415 isHexDigit c = isDigit c || c >= 'A' && c <= 'F'
1416 || c >= 'a' && c <= 'f'
1418 lexmatch :: (Eq a) => [a] -> [a] -> ([a],[a])
1419 lexmatch (x:xs) (y:ys) | x == y = lexmatch xs ys
1420 lexmatch xs ys = (xs,ys)
1422 asciiTab = zip ['\NUL'..' ']
1423 ["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
1424 "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
1425 "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
1426 "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US",
1429 readLitChar :: ReadS Char
1430 readLitChar ('\\':s) = readEsc s
1432 readEsc ('a':s) = [('\a',s)]
1433 readEsc ('b':s) = [('\b',s)]
1434 readEsc ('f':s) = [('\f',s)]
1435 readEsc ('n':s) = [('\n',s)]
1436 readEsc ('r':s) = [('\r',s)]
1437 readEsc ('t':s) = [('\t',s)]
1438 readEsc ('v':s) = [('\v',s)]
1439 readEsc ('\\':s) = [('\\',s)]
1440 readEsc ('"':s) = [('"',s)]
1441 readEsc ('\'':s) = [('\'',s)]
1442 readEsc ('^':c:s) | c >= '@' && c <= '_'
1443 = [(toEnum (fromEnum c - fromEnum '@'), s)]
1444 readEsc s@(d:_) | isDigit d
1445 = [(toEnum n, t) | (n,t) <- readDec s]
1446 readEsc ('o':s) = [(toEnum n, t) | (n,t) <- readOct s]
1447 readEsc ('x':s) = [(toEnum n, t) | (n,t) <- readHex s]
1448 readEsc s@(c:_) | isUpper c
1449 = let table = ('\DEL',"DEL") : asciiTab
1450 in case [(c,s') | (c, mne) <- table,
1451 ([],s') <- [lexmatch mne s]]
1455 readLitChar (c:s) = [(c,s)]
1457 showLitChar :: Char -> ShowS
1458 showLitChar c | c > '\DEL' = showChar '\\' .
1459 protectEsc isDigit (shows (fromEnum c))
1460 showLitChar '\DEL' = showString "\\DEL"
1461 showLitChar '\\' = showString "\\\\"
1462 showLitChar c | c >= ' ' = showChar c
1463 showLitChar '\a' = showString "\\a"
1464 showLitChar '\b' = showString "\\b"
1465 showLitChar '\f' = showString "\\f"
1466 showLitChar '\n' = showString "\\n"
1467 showLitChar '\r' = showString "\\r"
1468 showLitChar '\t' = showString "\\t"
1469 showLitChar '\v' = showString "\\v"
1470 showLitChar '\SO' = protectEsc ('H'==) (showString "\\SO")
1471 showLitChar c = showString ('\\' : snd (asciiTab!!fromEnum c))
1473 protectEsc p f = f . cont
1474 where cont s@(c:_) | p c = "\\&" ++ s
1477 -- Unsigned readers for various bases
1478 readDec, readOct, readHex :: Integral a => ReadS a
1479 readDec = readInt 10 isDigit (\d -> fromEnum d - fromEnum '0')
1480 readOct = readInt 8 isOctDigit (\d -> fromEnum d - fromEnum '0')
1481 readHex = readInt 16 isHexDigit hex
1482 where hex d = fromEnum d -
1485 else fromEnum (if isUpper d then 'A' else 'a') - 10)
1487 -- readInt reads a string of digits using an arbitrary base.
1488 -- Leading minus signs must be handled elsewhere.
1490 readInt :: Integral a => a -> (Char -> Bool) -> (Char -> Int) -> ReadS a
1491 readInt radix isDig digToInt s =
1492 [(foldl1 (\n d -> n * radix + d) (map (fromIntegral . digToInt) ds), r)
1493 | (ds,r) <- nonnull isDig s ]
1495 -- showInt is used for positive numbers only
1496 showInt :: Integral a => a -> ShowS
1499 = error "Numeric.showInt: can't show negative numbers"
1502 = let (n',d) = quotRem n 10
1503 r' = toEnum (fromEnum '0' + fromIntegral d) : r
1504 in if n' == 0 then r' else showInt n' r'
1506 = case quotRem n 10 of { (n',d) ->
1507 let r' = toEnum (fromEnum '0' + fromIntegral d) : r
1508 in if n' == 0 then r' else showInt n' r'
1512 readSigned:: Real a => ReadS a -> ReadS a
1513 readSigned readPos = readParen False read'
1514 where read' r = read'' r ++
1515 [(-x,t) | ("-",s) <- lex r,
1517 read'' r = [(n,s) | (str,s) <- lex r,
1518 (n,"") <- readPos str]
1520 showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS
1521 showSigned showPos p x = if x < 0 then showParen (p > 6)
1522 (showChar '-' . showPos (-x))
1525 readFloat :: RealFloat a => ReadS a
1526 readFloat r = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r,
1528 where readFix r = [(read (ds++ds'), length ds', t)
1529 | (ds, s) <- lexDigits r
1530 , (ds',t) <- lexFrac s ]
1532 lexFrac ('.':s) = lexDigits s
1533 lexFrac s = [("",s)]
1535 readExp (e:s) | e `elem` "eE" = readExp' s
1538 readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s]
1539 readExp' ('+':s) = readDec s
1540 readExp' s = readDec s
1543 -- Hooks for primitives: -----------------------------------------------------
1544 -- Do not mess with these!
1546 hugsprimCompAux :: Ord a => a -> a -> Ordering -> Ordering
1547 hugsprimCompAux x y o = case compare x y of EQ -> o; LT -> LT; GT -> GT
1549 hugsprimEqChar :: Char -> Char -> Bool
1550 hugsprimEqChar c1 c2 = primEqChar c1 c2
1552 hugsprimPmInt :: Num a => Int -> a -> Bool
1553 hugsprimPmInt n x = fromInt n == x
1555 hugsprimPmInteger :: Num a => Integer -> a -> Bool
1556 hugsprimPmInteger n x = fromInteger n == x
1558 hugsprimPmDouble :: Fractional a => Double -> a -> Bool
1559 hugsprimPmDouble n x = fromDouble n == x
1561 -- ToDo: make the message more informative.
1563 hugsprimPmFail = error "Pattern Match Failure"
1565 -- used in desugaring Foreign functions
1566 -- Note: hugsprimMkIO is used as a wrapper to translate a Hugs-created
1567 -- bit of code of type RealWorld -> (a,RealWorld) into a proper IO value.
1568 -- What follows is the version for standalone mode. ghc/lib/std/PrelHugs.lhs
1569 -- contains a version used in combined mode. That version takes care of
1570 -- switching between the GHC and Hugs IO representations, which are different.
1571 hugsprimMkIO :: (RealWorld -> (a,RealWorld)) -> IO a
1574 hugsprimCreateAdjThunk :: (a -> b) -> String -> Char -> IO Addr
1575 hugsprimCreateAdjThunk fun typestr callconv
1576 = do sp <- makeStablePtr fun
1577 p <- copy_String_to_cstring typestr -- is never freed
1578 a <- primCreateAdjThunkARCH sp p callconv
1581 -- The following primitives are only needed if (n+k) patterns are enabled:
1582 hugsprimPmSub :: Integral a => Int -> a -> a
1583 hugsprimPmSub n x = x - fromInt n
1585 hugsprimPmFromInteger :: Integral a => Integer -> a
1586 hugsprimPmFromInteger = fromIntegral
1588 hugsprimPmSubtract :: Integral a => a -> a -> a
1589 hugsprimPmSubtract x y = x - y
1591 hugsprimPmLe :: Integral a => a -> a -> Bool
1592 hugsprimPmLe x y = x <= y
1594 -- Unpack strings generated by the Hugs code generator.
1595 -- Strings can contain \0 provided they're coded right.
1597 -- ToDo: change this (and Hugs code generator) to use ByteArrays
1599 hugsprimUnpackString :: Addr -> String
1600 hugsprimUnpackString a = unpack 0
1602 -- The following decoding is based on evalString in the old machine.c
1605 | c == '\\' = if '\\' == primIndexCharOffAddr a (i+1)
1606 then '\\' : unpack (i+2)
1607 else '\0' : unpack (i+2)
1608 | otherwise = c : unpack (i+1)
1610 c = primIndexCharOffAddr a i
1613 -- Monadic I/O: --------------------------------------------------------------
1615 type FilePath = String
1617 --data IOError = ...
1618 --instance Eq IOError ...
1619 --instance Show IOError ...
1621 data IOError = IOError String
1622 instance Show IOError where
1623 showsPrec _ (IOError s) = showString ("I/O error: " ++ s)
1625 ioError :: IOError -> IO a
1626 ioError e@(IOError _) = primRaise (IOException e)
1628 userError :: String -> IOError
1629 userError s = primRaise (ErrorCall s)
1631 throw :: Exception -> a
1632 throw exception = primRaise exception
1634 catchException :: IO a -> (Exception -> IO a) -> IO a
1635 catchException m k = IO (\s -> unIO m s `primCatch` \ err -> unIO (k err) s)
1637 catch :: IO a -> (IOError -> IO a) -> IO a
1638 catch m k = catchException m handler
1639 where handler (IOException err) = k err
1640 handler other = throw other
1642 putChar :: Char -> IO ()
1643 putChar c = nh_stdout >>= \h -> nh_write h c
1645 putStr :: String -> IO ()
1646 putStr s = nh_stdout >>= \h ->
1647 let loop [] = nh_flush h
1648 loop (c:cs) = nh_write h c >> loop cs
1651 putStrLn :: String -> IO ()
1652 putStrLn s = do { putStr s; putChar '\n' }
1654 print :: Show a => a -> IO ()
1655 print = putStrLn . show
1658 getChar = nh_stdin >>= \h ->
1659 nh_read h >>= \ci ->
1660 return (primIntToChar ci)
1662 getLine :: IO String
1663 getLine = do c <- getChar
1664 if c=='\n' then return ""
1665 else do cs <- getLine
1668 getContents :: IO String
1669 getContents = nh_stdin >>= \h -> readfromhandle h
1671 interact :: (String -> String) -> IO ()
1672 interact f = getContents >>= (putStr . f)
1674 readFile :: FilePath -> IO String
1676 = copy_String_to_cstring fname >>= \ptr ->
1677 nh_open ptr 0 >>= \h ->
1679 nh_errno >>= \errno ->
1680 if (isNullAddr h || errno /= 0)
1681 then (ioError.IOError) ("readFile: can't open file " ++ fname)
1682 else readfromhandle h
1684 writeFile :: FilePath -> String -> IO ()
1685 writeFile fname contents
1686 = copy_String_to_cstring fname >>= \ptr ->
1687 nh_open ptr 1 >>= \h ->
1689 nh_errno >>= \errno ->
1690 if (isNullAddr h || errno /= 0)
1691 then (ioError.IOError) ("writeFile: can't create file " ++ fname)
1692 else writetohandle fname h contents
1694 appendFile :: FilePath -> String -> IO ()
1695 appendFile fname contents
1696 = copy_String_to_cstring fname >>= \ptr ->
1697 nh_open ptr 2 >>= \h ->
1699 nh_errno >>= \errno ->
1700 if (isNullAddr h || errno /= 0)
1701 then (ioError.IOError) ("appendFile: can't open file " ++ fname)
1702 else writetohandle fname h contents
1705 -- raises an exception instead of an error
1706 readIO :: Read a => String -> IO a
1707 readIO s = case [x | (x,t) <- reads s, ("","") <- lex t] of
1709 [] -> ioError (userError "PreludeIO.readIO: no parse")
1710 _ -> ioError (userError
1711 "PreludeIO.readIO: ambiguous parse")
1713 readLn :: Read a => IO a
1714 readLn = do l <- getLine
1719 -- End of Hugs standard prelude ----------------------------------------------
1721 = IOException IOError -- IO exceptions (from 'ioError')
1722 | ArithException ArithException -- Arithmetic exceptions
1723 | ErrorCall String -- Calls to 'error'
1724 | NoMethodError String -- A non-existent method was invoked
1725 | PatternMatchFail String -- A pattern match failed
1726 | NonExhaustiveGuards String -- A guard match failed
1727 | RecSelError String -- Selecting a non-existent field
1728 | RecConError String -- Field missing in record construction
1729 | RecUpdError String -- Record doesn't contain updated field
1730 | AssertionFailed String -- Assertions
1731 | DynException Dynamic -- Dynamic exceptions
1732 | AsyncException AsyncException -- Externally generated errors
1733 | PutFullMVar -- Put on a full MVar
1750 stackOverflow, heapOverflow :: Exception -- for the RTS
1751 stackOverflow = AsyncException StackOverflow
1752 heapOverflow = AsyncException HeapOverflow
1754 instance Show ArithException where
1755 showsPrec _ Overflow = showString "arithmetic overflow"
1756 showsPrec _ Underflow = showString "arithmetic underflow"
1757 showsPrec _ LossOfPrecision = showString "loss of precision"
1758 showsPrec _ DivideByZero = showString "divide by zero"
1759 showsPrec _ Denormal = showString "denormal"
1761 instance Show AsyncException where
1762 showsPrec _ StackOverflow = showString "stack overflow"
1763 showsPrec _ HeapOverflow = showString "heap overflow"
1764 showsPrec _ ThreadKilled = showString "thread killed"
1766 instance Show Exception where
1767 showsPrec _ (IOException err) = shows err
1768 showsPrec _ (ArithException err) = shows err
1769 showsPrec _ (ErrorCall err) = showString err
1770 showsPrec _ (NoMethodError err) = showString err
1771 showsPrec _ (PatternMatchFail err) = showString err
1772 showsPrec _ (NonExhaustiveGuards err) = showString err
1773 showsPrec _ (RecSelError err) = showString err
1774 showsPrec _ (RecConError err) = showString err
1775 showsPrec _ (RecUpdError err) = showString err
1776 showsPrec _ (AssertionFailed err) = showString err
1777 showsPrec _ (AsyncException e) = shows e
1778 showsPrec _ (DynException _err) = showString "unknown exception"
1779 showsPrec _ (PutFullMVar) = showString "putMVar: full MVar"
1780 showsPrec _ (NonTermination) = showString "<<loop>>"
1782 data Dynamic = Dynamic TypeRep Obj
1784 data Obj = Obj -- dummy type to hold the dynamically typed value.
1786 = App TyCon [TypeRep]
1787 | Fun TypeRep TypeRep
1790 data TyCon = TyCon Int String
1792 instance Eq TyCon where
1793 (TyCon t1 _) == (TyCon t2 _) = t1 == t2
1795 data IOResult = IOResult deriving (Show)
1797 type FILE_STAR = Addr -- FILE *
1799 foreign import "nHandle" "nh_stdin" nh_stdin :: IO FILE_STAR
1800 foreign import "nHandle" "nh_stdout" nh_stdout :: IO FILE_STAR
1801 foreign import "nHandle" "nh_stderr" nh_stderr :: IO FILE_STAR
1802 foreign import "nHandle" "nh_write" nh_write :: FILE_STAR -> Char -> IO ()
1803 foreign import "nHandle" "nh_read" nh_read :: FILE_STAR -> IO Int
1804 foreign import "nHandle" "nh_open" nh_open :: Addr -> Int -> IO FILE_STAR
1805 foreign import "nHandle" "nh_flush" nh_flush :: FILE_STAR -> IO ()
1806 foreign import "nHandle" "nh_close" nh_close :: FILE_STAR -> IO ()
1807 foreign import "nHandle" "nh_errno" nh_errno :: IO Int
1809 foreign import "nHandle" "nh_malloc" nh_malloc :: Int -> IO Addr
1810 foreign import "nHandle" "nh_free" nh_free :: Addr -> IO ()
1811 foreign import "nHandle" "nh_store" nh_store :: Addr -> Char -> IO ()
1812 foreign import "nHandle" "nh_load" nh_load :: Addr -> IO Char
1813 foreign import "nHandle" "nh_getenv" nh_getenv :: Addr -> IO Addr
1814 foreign import "nHandle" "nh_filesize" nh_filesize :: FILE_STAR -> IO Int
1815 foreign import "nHandle" "nh_iseof" nh_iseof :: FILE_STAR -> IO Int
1816 foreign import "nHandle" "nh_system" nh_system :: Addr -> IO Int
1817 foreign import "nHandle" "nh_exitwith" nh_exitwith :: Int -> IO ()
1818 foreign import "nHandle" "nh_getPID" nh_getPID :: IO Int
1820 foreign import "nHandle" "nh_getCPUtime" nh_getCPUtime :: IO Double
1821 foreign import "nHandle" "nh_getCPUprec" nh_getCPUprec :: IO Double
1823 copy_String_to_cstring :: String -> IO Addr
1824 copy_String_to_cstring s
1825 = nh_malloc (1 + length s) >>= \ptr0 ->
1826 let loop ptr [] = nh_store ptr (chr 0) >> return ptr0
1827 loop ptr (c:cs) = nh_store ptr c >> loop (incAddr ptr) cs
1830 then error "copy_String_to_cstring: malloc failed"
1833 copy_cstring_to_String :: Addr -> IO String
1834 copy_cstring_to_String ptr
1835 = nh_load ptr >>= \ci ->
1838 else copy_cstring_to_String (incAddr ptr) >>= \cs ->
1841 readfromhandle :: FILE_STAR -> IO String
1843 = unsafeInterleaveIO (
1844 nh_read h >>= \ci ->
1845 if ci == -1 {-EOF-} then return "" else
1846 readfromhandle h >>= \restOfFile -> return ((primIntToChar ci) : restOfFile)
1849 writetohandle :: String -> FILE_STAR -> String -> IO ()
1850 writetohandle fname h []
1852 nh_errno >>= \errno ->
1855 else error ( "writeFile/appendFile: error closing file " ++ fname)
1856 writetohandle fname h (c:cs)
1857 = nh_write h c >> writetohandle fname h cs
1859 primGetRawArgs :: IO [String]
1861 = primGetArgc >>= \argc ->
1862 sequence (map get_one_arg [0 .. argc-1])
1864 get_one_arg :: Int -> IO String
1866 = primGetArgv argno >>= \a ->
1867 copy_cstring_to_String a
1869 primGetEnv :: String -> IO String
1871 = copy_String_to_cstring v >>= \ptr ->
1872 nh_getenv ptr >>= \ptr2 ->
1875 then ioError (IOError "getEnv failed")
1877 copy_cstring_to_String ptr2 >>= \result ->
1881 ------------------------------------------------------------------------------
1882 -- ST ------------------------------------------------------------------------
1883 ------------------------------------------------------------------------------
1885 newtype ST s a = ST (s -> (a,s))
1886 unST :: ST s a -> s -> (a,s)
1888 mkST :: (s -> (a,s)) -> ST s a
1892 runST :: (__forall s . ST s a) -> a
1893 runST m = fst (unST m alpha)
1895 alpha = error "runST: entered the RealWorld"
1897 instance Functor (ST s) where
1898 fmap f x = x >>= (return . f)
1900 instance Monad (ST s) where
1901 m >> k = ST (\s -> case unST m s of { (a,s') -> unST k s' })
1902 return x = ST (\s -> (x,s))
1903 m >>= k = ST (\s -> case unST m s of { (a,s') -> unST (k a) s' })
1905 unsafeInterleaveST :: ST s a -> ST s a
1906 unsafeInterleaveST m = ST (\ s -> (fst (unST m s), s))
1908 ------------------------------------------------------------------------------
1909 -- IO ------------------------------------------------------------------------
1910 ------------------------------------------------------------------------------
1912 newtype IO a = IO (RealWorld -> (a,RealWorld))
1915 stToIO :: ST RealWorld a -> IO a
1916 stToIO (ST fn) = IO fn
1918 ioToST :: IO a -> ST RealWorld a
1919 ioToST (IO fn) = ST fn
1921 unsafePerformIO :: IO a -> a
1922 unsafePerformIO m = fst (unIO m theWorld)
1924 theWorld :: RealWorld
1925 theWorld = error "unsafePerformIO: entered the RealWorld"
1927 instance Functor IO where
1928 fmap f x = x >>= (return . f)
1930 instance Monad IO where
1931 m >> k = IO (\s -> case unIO m s of { (a,s') -> unIO k s' })
1932 return x = IO (\s -> (x,s))
1933 m >>= k = IO (\s -> case unIO m s of { (a,s') -> unIO (k a) s' })
1935 -- Library IO has a global variable which accumulates Handles
1936 -- as they are opened. We keep here a second global variable
1937 -- into which a cleanup action may be specified. When evaluation
1938 -- finishes, either normally or as a result of System.exitWith,
1939 -- this cleanup action is run, closing all known-about Handles.
1940 -- Doing it like this means the Prelude does not have to know
1941 -- anything about the grotty details of the Handle implementation.
1942 prelCleanupAfterRunAction :: IORef (Maybe (IO ()))
1943 prelCleanupAfterRunAction = unsafePerformIO (newIORef Nothing)
1945 -- used when Hugs invokes top level function
1946 hugsprimRunIO_toplevel :: IO a -> ()
1947 hugsprimRunIO_toplevel m
1948 = protect 5 (fst (unIO composite_action realWorld))
1951 = do writeIORef prelCleanupAfterRunAction Nothing
1953 cleanup_handles <- readIORef prelCleanupAfterRunAction
1954 case cleanup_handles of
1955 Nothing -> return ()
1958 realWorld = error "primRunIO: entered the RealWorld"
1959 protect :: Int -> () -> ()
1963 = primCatch (protect (n-1) comp)
1964 (\e -> fst (unIO (putStr (show e ++ "\n")) realWorld))
1966 unsafeInterleaveIO :: IO a -> IO a
1967 unsafeInterleaveIO m = IO (\ s -> (fst (unIO m s), s))
1969 ------------------------------------------------------------------------------
1970 -- Word, Addr, StablePtr, Prim*Array -----------------------------------------
1971 ------------------------------------------------------------------------------
1975 nullAddr = primIntToAddr 0
1976 incAddr a = primIntToAddr (1 + primAddrToInt a)
1977 isNullAddr a = 0 == primAddrToInt a
1979 instance Eq Addr where
1983 instance Ord Addr where
1991 instance Eq Word where
1995 instance Ord Word where
2003 makeStablePtr :: a -> IO (StablePtr a)
2004 makeStablePtr = primMakeStablePtr
2005 deRefStablePtr :: StablePtr a -> IO a
2006 deRefStablePtr = primDeRefStablePtr
2007 freeStablePtr :: StablePtr a -> IO ()
2008 freeStablePtr = primFreeStablePtr
2011 data PrimArray a -- immutable arrays with Int indices
2014 data STRef s a -- mutable variables
2015 data PrimMutableArray s a -- mutable arrays with Int indices
2016 data PrimMutableByteArray s
2018 newSTRef :: a -> ST s (STRef s a)
2019 newSTRef = primNewRef
2020 readSTRef :: STRef s a -> ST s a
2021 readSTRef = primReadRef
2022 writeSTRef :: STRef s a -> a -> ST s ()
2023 writeSTRef = primWriteRef
2025 newtype IORef a = IORef (STRef RealWorld a)
2026 newIORef :: a -> IO (IORef a)
2027 newIORef a = stToIO (primNewRef a >>= \ ref ->return (IORef ref))
2028 readIORef :: IORef a -> IO a
2029 readIORef (IORef ref) = stToIO (primReadRef ref)
2030 writeIORef :: IORef a -> a -> IO ()
2031 writeIORef (IORef ref) a = stToIO (primWriteRef ref a)
2034 ------------------------------------------------------------------------------
2035 -- ThreadId, MVar, concurrency stuff -----------------------------------------
2036 ------------------------------------------------------------------------------
2040 newEmptyMVar :: IO (MVar a)
2041 newEmptyMVar = primNewEmptyMVar
2043 putMVar :: MVar a -> a -> IO ()
2044 putMVar = primPutMVar
2046 takeMVar :: MVar a -> IO a
2048 = IO (\world -> primTakeMVar m cont world)
2050 -- cont :: a -> RealWorld -> (a,RealWorld)
2051 -- where 'a' is as in the top-level signature
2052 cont x world = (x,world)
2054 -- the type of the handwritten BCO (threesome) primTakeMVar is
2055 -- primTakeMVar :: MVar a
2056 -- -> (a -> RealWorld -> (a,RealWorld))
2060 -- primTakeMVar behaves like this:
2062 -- primTakeMVar (MVar# m#) cont world
2063 -- = primTakeMVar_wrk m# cont world
2065 -- primTakeMVar_wrk m# cont world
2066 -- = cont (takeMVar# m#) world
2068 -- primTakeMVar_wrk has the special property that it is
2069 -- restartable by the scheduler, should the MVar be empty.
2071 newMVar :: a -> IO (MVar a)
2073 newEmptyMVar >>= \ mvar ->
2074 putMVar mvar value >>
2077 readMVar :: MVar a -> IO a
2079 takeMVar mvar >>= \ value ->
2080 putMVar mvar value >>
2083 swapMVar :: MVar a -> a -> IO a
2085 takeMVar mvar >>= \ old ->
2089 isEmptyMVar var = error "isEmptyMVar is not (yet) implemented in Hugs"
2091 instance Eq (MVar a) where
2092 m1 == m2 = primSameMVar m1 m2
2096 instance Eq ThreadId where
2097 tid1 == tid2 = primCmpThreadIds tid1 tid2 == 0
2099 instance Ord ThreadId where
2101 = let r = primCmpThreadIds tid1 tid2
2102 in if r < 0 then LT else if r > 0 then GT else EQ
2105 forkIO :: IO a -> IO ThreadId
2106 -- Simple version; doesn't catch exceptions in computation
2107 -- forkIO computation
2108 -- = primForkIO (unsafePerformIO computation)
2113 (unIO computation realWorld `primSeq` ())
2114 (\e -> trace_quiet ("forkIO: uncaught exception: " ++ show e) ())
2117 realWorld = error "primForkIO: entered the RealWorld"
2120 = (unsafePerformIO (putStr (s ++ "\n"))) `seq` x
2123 -- Foreign ------------------------------------------------------------------
2127 -- showFloat ------------------------------------------------------------------
2129 showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
2130 showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
2131 showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
2132 showFloat :: (RealFloat a) => a -> ShowS
2134 showEFloat d x = showString (formatRealFloat FFExponent d x)
2135 showFFloat d x = showString (formatRealFloat FFFixed d x)
2136 showGFloat d x = showString (formatRealFloat FFGeneric d x)
2137 showFloat = showGFloat Nothing
2139 -- These are the format types. This type is not exported.
2141 data FFFormat = FFExponent | FFFixed | FFGeneric
2143 formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
2144 formatRealFloat fmt decs x = s
2148 else if isInfinite x then
2149 if x < 0 then "-Infinity" else "Infinity"
2150 else if x < 0 || isNegativeZero x then
2151 '-' : doFmt fmt (floatToDigits (toInteger base) (-x))
2153 doFmt fmt (floatToDigits (toInteger base) x)
2155 let ds = map intToDigit is
2158 doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
2165 [d] -> d : ".0e" ++ show (e-1)
2166 d:ds -> d : '.' : ds ++ 'e':show (e-1)
2168 let dec' = max dec 1 in
2170 [0] -> '0':'.':take dec' (repeat '0') ++ "e0"
2172 let (ei, is') = roundTo base (dec'+1) is
2173 d:ds = map intToDigit
2174 (if ei > 0 then init is' else is')
2175 in d:'.':ds ++ "e" ++ show (e-1+ei)
2179 let f 0 s ds = mk0 s ++ "." ++ mk0 ds
2180 f n s "" = f (n-1) (s++"0") ""
2181 f n s (d:ds) = f (n-1) (s++[d]) ds
2186 let dec' = max dec 0 in
2188 let (ei, is') = roundTo base (dec' + e) is
2189 (ls, rs) = splitAt (e+ei) (map intToDigit is')
2190 in (if null ls then "0" else ls) ++
2191 (if null rs then "" else '.' : rs)
2193 let (ei, is') = roundTo base dec'
2194 (replicate (-e) 0 ++ is)
2195 d : ds = map intToDigit
2196 (if ei > 0 then is' else 0:is')
2199 roundTo :: Int -> Int -> [Int] -> (Int, [Int])
2200 roundTo base d is = case f d is of
2202 (1, is) -> (1, 1 : is)
2203 where b2 = base `div` 2
2204 f n [] = (0, replicate n 0)
2205 f 0 (i:_) = (if i >= b2 then 1 else 0, [])
2207 let (c, ds) = f (d-1) is
2209 in if i' == base then (1, 0:ds) else (0, i':ds)
2211 -- Based on "Printing Floating-Point Numbers Quickly and Accurately"
2212 -- by R.G. Burger and R. K. Dybvig, in PLDI 96.
2213 -- This version uses a much slower logarithm estimator. It should be improved.
2215 -- This function returns a list of digits (Ints in [0..base-1]) and an
2218 floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
2220 floatToDigits _ 0 = ([0], 0)
2221 floatToDigits base x =
2222 let (f0, e0) = decodeFloat x
2223 (minExp0, _) = floatRange x
2226 minExp = minExp0 - p -- the real minimum exponent
2227 -- Haskell requires that f be adjusted so denormalized numbers
2228 -- will have an impossibly low exponent. Adjust for this.
2229 (f, e) = let n = minExp - e0
2230 in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
2235 if f == b^(p-1) then
2236 (f*be*b*2, 2*b, be*b, b)
2240 if e > minExp && f == b^(p-1) then
2241 (f*b*2, b^(-e+1)*2, b, 1)
2243 (f*2, b^(-e)*2, 1, 1)
2246 if b == 2 && base == 10 then
2247 -- logBase 10 2 is slightly bigger than 3/10 so
2248 -- the following will err on the low side. Ignoring
2249 -- the fraction will make it err even more.
2250 -- Haskell promises that p-1 <= logBase b f < p.
2251 (p - 1 + e0) * 3 `div` 10
2253 ceiling ((log (fromInteger (f+1)) +
2254 fromInt e * log (fromInteger b)) /
2255 log (fromInteger base))
2258 if r + mUp <= expt base n * s then n else fixup (n+1)
2260 if expt base (-n) * (r + mUp) <= s then n
2264 gen ds rn sN mUpN mDnN =
2265 let (dn, rn') = (rn * base) `divMod` sN
2268 in case (rn' < mDnN', rn' + mUpN' > sN) of
2269 (True, False) -> dn : ds
2270 (False, True) -> dn+1 : ds
2271 (True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
2272 (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
2275 gen [] r (s * expt base k) mUp mDn
2277 let bk = expt base (-k)
2278 in gen [] (r * bk) s (mUp * bk) (mDn * bk)
2279 in (map toInt (reverse rds), k)
2282 -- Exponentiation with a cache for the most common numbers.
2285 expt :: Integer -> Int -> Integer
2287 if base == 2 && n >= minExpt && n <= maxExpt then
2288 expts !! (n-minExpt)
2293 expts = [2^n | n <- [minExpt .. maxExpt]]
2297 , noMethodBindingError
2298 , nonExhaustiveGuardsError
2302 , recUpdError :: String -> a
2304 noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
2305 irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
2306 nonExhaustiveGuardsError s = throw (NonExhaustiveGuards (untangle s "Non-exhaustive guards in"))
2307 patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
2308 recSelError s = throw (RecSelError (untangle s "Missing field in record selection"))
2309 recConError s = throw (RecConError (untangle s "Missing field in record construction"))
2310 recUpdError s = throw (RecUpdError (untangle s "Record doesn't contain field(s) to be updated"))
2313 tangleMessage :: String -> Int -> String
2314 tangleMessage "" line = show line
2315 tangleMessage str line = str ++ show line
2317 assertError :: String -> Bool -> a -> a
2318 assertError str pred v
2320 | otherwise = throw (AssertionFailed (untangle str "Assertion failed"))
2323 (untangle coded message) expects "coded" to be of the form
2329 location message details
2332 untangle :: String -> String -> String
2333 untangle coded message
2341 = case (span not_bar coded) of { (loc, rest) ->
2343 ('|':det) -> (loc, ' ' : det)
2346 not_bar c = c /= '|'
2348 -- By default, we ignore asserts, but optionally, Hugs translates
2349 -- assert ==> assertError "<location info>"
2351 assert :: Bool -> a -> a