235c41b128b5219e7d3e69221e2d4e00e1d81538
[ghc-hetmet.git] / ghc / lib / std / PrelBase.lhs
1 % -----------------------------------------------------------------------------
2 % $Id: PrelBase.lhs,v 1.34 2000/08/02 14:13:27 rrt Exp $
3 %
4 % (c) The University of Glasgow, 1992-2000
5 %
6 \section[PrelBase]{Module @PrelBase@}
7
8
9 The overall structure of the GHC Prelude is a bit tricky.
10
11   a) We want to avoid "orphan modules", i.e. ones with instance
12         decls that don't belong either to a tycon or a class
13         defined in the same module
14
15   b) We want to avoid giant modules
16
17 So the rough structure is as follows, in (linearised) dependency order
18
19
20 PrelGHC         Has no implementation.  It defines built-in things, and
21                 by importing it you bring them into scope.
22                 The source file is PrelGHC.hi-boot, which is just
23                 copied to make PrelGHC.hi
24
25                 Classes: CCallable, CReturnable
26
27 PrelBase        Classes: Eq, Ord, Functor, Monad
28                 Types:   list, (), Int, Bool, Ordering, Char, String
29
30 PrelTup         Types: tuples, plus instances for PrelBase classes
31
32 PrelShow        Class: Show, plus instances for PrelBase/PrelTup types
33
34 PrelEnum        Class: Enum,  plus instances for PrelBase/PrelTup types
35
36 PrelMaybe       Type: Maybe, plus instances for PrelBase classes
37
38 PrelNum         Class: Num, plus instances for Int
39                 Type:  Integer, plus instances for all classes so far (Eq, Ord, Num, Show)
40
41                 Integer is needed here because it is mentioned in the signature
42                 of 'fromInteger' in class Num
43
44 PrelReal        Classes: Real, Integral, Fractional, RealFrac
45                          plus instances for Int, Integer
46                 Types:  Ratio, Rational
47                         plus intances for classes so far
48
49                 Rational is needed here because it is mentioned in the signature
50                 of 'toRational' in class Real
51
52 Ix              Classes: Ix, plus instances for Int, Bool, Char, Integer, Ordering, tuples
53
54 PrelArr         Types: Array, MutableArray, MutableVar
55
56                 Does *not* contain any ByteArray stuff (see PrelByteArr)
57                 Arrays are used by a function in PrelFloat
58
59 PrelFloat       Classes: Floating, RealFloat
60                 Types:   Float, Double, plus instances of all classes so far
61
62                 This module contains everything to do with floating point.
63                 It is a big module (900 lines)
64                 With a bit of luck, many modules can be compiled without ever reading PrelFloat.hi
65
66 PrelByteArr     Types: ByteArray, MutableByteArray
67                 
68                 We want this one to be after PrelFloat, because it defines arrays
69                 of unboxed floats.
70
71
72 Other Prelude modules are much easier with fewer complex dependencies.
73
74
75 \begin{code}
76 {-# OPTIONS -fno-implicit-prelude #-}
77
78 module PrelBase
79         (
80         module PrelBase,
81         module PrelGHC,         -- Re-export PrelGHC, PrelErr & PrelNum, to avoid lots
82         module PrelErr,         -- of people having to import it explicitly
83         module PrelNum
84   ) 
85         where
86
87 import PrelGHC
88 import {-# SOURCE #-} PrelErr
89 import {-# SOURCE #-} PrelNum
90
91 infixr 9  .
92 infixr 5  ++, :
93 infix  4  ==, /=, <, <=, >=, >
94 infixr 3  &&
95 infixr 2  ||
96 infixl 1  >>, >>=
97 infixr 0  $
98
99 default ()              -- Double isn't available yet
100 \end{code}
101
102
103 %*********************************************************
104 %*                                                      *
105 \subsection{DEBUGGING STUFF}
106 %*  (for use when compiling PrelBase itself doesn't work)
107 %*                                                      *
108 %*********************************************************
109
110 \begin{code}
111 {-              
112 data  Bool  =  False | True
113 data Ordering = LT | EQ | GT 
114 data Char = C# Char#
115 type  String = [Char]
116 data Int = I# Int#
117 data  ()  =  ()
118 -- data [] a = MkNil
119
120 not True = False
121 (&&) True True = True
122 otherwise = True
123
124 build = error "urk"
125 foldr = error "urk"
126
127 unpackCString#  :: Addr# -> [Char]
128 unpackFoldrCString#  :: Addr# -> (Char  -> a -> a) -> a -> a 
129 unpackAppendCString# :: Addr# -> [Char] -> [Char]
130 unpackNBytes#      :: Addr# -> Int#   -> [Char]
131 unpackNBytes# a b = error "urk"
132 unpackCString# a = error "urk"
133 unpackFoldrCString# a = error "urk"
134 unpackAppendCString# a = error "urk"
135 -}
136 \end{code}
137
138
139 %*********************************************************
140 %*                                                      *
141 \subsection{Standard classes @Eq@, @Ord@}
142 %*                                                      *
143 %*********************************************************
144
145 \begin{code}
146 class  Eq a  where
147     (==), (/=)          :: a -> a -> Bool
148
149 --    x /= y            = not (x == y)
150 --    x == y            = not (x /= y)
151 --    x /= y            =  True
152     (/=) x y            = not  ((==) x y)
153     x == y              =  True
154
155 class  (Eq a) => Ord a  where
156     compare             :: a -> a -> Ordering
157     (<), (<=), (>=), (>):: a -> a -> Bool
158     max, min            :: a -> a -> a
159
160 -- An instance of Ord should define either compare or <=
161 -- Using compare can be more efficient for complex types.
162     compare x y
163             | x == y    = EQ
164             | x <= y    = LT    -- NB: must be '<=' not '<' to validate the
165                                 -- above claim about the minimal things that can
166                                 -- be defined for an instance of Ord
167             | otherwise = GT
168
169     x <= y  = case compare x y of { GT -> False; _other -> True }
170     x <  y  = case compare x y of { LT -> True;  _other -> False }
171     x >= y  = case compare x y of { LT -> False; _other -> True }
172     x >  y  = case compare x y of { GT -> True;  _other -> False }
173
174         -- These two default methods use '>' rather than compare
175         -- because the latter is often more expensive
176     max x y = if x > y then x else y
177     min x y = if x > y then y else x
178 \end{code}
179
180 %*********************************************************
181 %*                                                      *
182 \subsection{Monadic classes @Functor@, @Monad@ }
183 %*                                                      *
184 %*********************************************************
185
186 \begin{code}
187 class  Functor f  where
188     fmap         :: (a -> b) -> f a -> f b
189
190 class  Monad m  where
191     (>>=)       :: m a -> (a -> m b) -> m b
192     (>>)        :: m a -> m b -> m b
193     return      :: a -> m a
194     fail        :: String -> m a
195
196     m >> k      =  m >>= \_ -> k
197     fail s      = error s
198
199 \end{code}
200
201
202 %*********************************************************
203 %*                                                      *
204 \subsection{The list type}
205 %*                                                      *
206 %*********************************************************
207
208 \begin{code}
209 data [] a = [] | a : [a]  -- do explicitly: deriving (Eq, Ord)
210                           -- to avoid weird names like con2tag_[]#
211
212
213 instance (Eq a) => Eq [a]  where
214 {-
215     {-# SPECIALISE instance Eq [Char] #-}
216 -}
217     []     == []     = True     
218     (x:xs) == (y:ys) = x == y && xs == ys
219     _xs    == _ys    = False                    
220
221     xs     /= ys     = if (xs == ys) then False else True
222
223 instance (Ord a) => Ord [a] where
224 {-
225     {-# SPECIALISE instance Ord [Char] #-}
226 -}
227     a <  b  = case compare a b of { LT -> True;  EQ -> False; GT -> False }
228     a <= b  = case compare a b of { LT -> True;  EQ -> True;  GT -> False }
229     a >= b  = case compare a b of { LT -> False; EQ -> True;  GT -> True  }
230     a >  b  = case compare a b of { LT -> False; EQ -> False; GT -> True  }
231
232     compare []     []     = EQ
233     compare (_:_)  []     = GT
234     compare []     (_:_)  = LT
235     compare (x:xs) (y:ys) = case compare x y of
236                                  LT -> LT       
237                                  GT -> GT               
238                                  EQ -> compare xs ys
239
240 instance Functor [] where
241     fmap = map
242
243 instance  Monad []  where
244     m >>= k             = foldr ((++) . k) [] m
245     m >> k              = foldr ((++) . (\ _ -> k)) [] m
246     return x            = [x]
247     fail _              = []
248 \end{code}
249
250 A few list functions that appear here because they are used here.
251 The rest of the prelude list functions are in PrelList.
252
253 ----------------------------------------------
254 --      foldr/build/augment
255 ----------------------------------------------
256   
257 \begin{code}
258 foldr            :: (a -> b -> b) -> b -> [a] -> b
259 -- foldr _ z []     =  z
260 -- foldr f z (x:xs) =  f x (foldr f z xs)
261 {-# INLINE foldr #-}
262 foldr k z xs = go xs
263              where
264                go []     = z
265                go (x:xs) = x `k` go xs
266
267 build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
268 {-# INLINE 2 build #-}
269         -- The INLINE is important, even though build is tiny,
270         -- because it prevents [] getting inlined in the version that
271         -- appears in the interface file.  If [] *is* inlined, it
272         -- won't match with [] appearing in rules in an importing module.
273         --
274         -- The "2" says to inline in phase 2
275
276 build g = g (:) []
277
278 augment :: forall a. (forall b. (a->b->b) -> b -> b) -> [a] -> [a]
279 {-# INLINE 2 augment #-}
280 augment g xs = g (:) xs
281
282 {-# RULES
283 "fold/build"    forall k z (g::forall b. (a->b->b) -> b -> b) . 
284                 foldr k z (build g) = g k z
285
286 "foldr/augment" forall k z xs (g::forall b. (a->b->b) -> b -> b) . 
287                 foldr k z (augment g xs) = g k (foldr k z xs)
288
289 "foldr/id"      foldr (:) [] = \x->x
290 "foldr/app"     forall xs ys. foldr (:) ys xs = append xs ys
291
292 "foldr/cons"    forall k z x xs. foldr k z (x:xs) = k x (foldr k z xs)
293 "foldr/nil"     forall k z.      foldr k z []     = z 
294
295 "augment/build" forall (g::forall b. (a->b->b) -> b -> b)
296                        (h::forall b. (a->b->b) -> b -> b) .
297                        augment g (build h) = build (\c n -> g c (h c n))
298 "augment/nil"   forall (g::forall b. (a->b->b) -> b -> b) .
299                         augment g [] = build g
300  #-}
301
302 -- This rule is true, but not (I think) useful:
303 --      augment g (augment h t) = augment (\cn -> g c (h c n)) t
304 \end{code}
305
306
307 ----------------------------------------------
308 --              map     
309 ----------------------------------------------
310
311 \begin{code}
312 map :: (a -> b) -> [a] -> [b]
313 map = mapList
314
315 -- Note eta expanded
316 mapFB c f x ys = c (f x) ys
317
318 mapList :: (a -> b) -> [a] -> [b]
319 mapList _ []     = []
320 mapList f (x:xs) = f x : mapList f xs
321
322 {-# RULES
323 "map"       forall f xs.        map f xs                = build (\c n -> foldr (mapFB c f) n xs)
324 "mapFB"     forall c f g.       mapFB (mapFB c f) g     = mapFB c (f.g) 
325 "mapList"   forall f.           foldr (mapFB (:) f) []  = mapList f
326  #-}
327 \end{code}
328
329
330 ----------------------------------------------
331 --              append  
332 ----------------------------------------------
333 \begin{code}
334 (++) :: [a] -> [a] -> [a]
335 (++) = append
336
337 {-# RULES
338   "++"  forall xs ys. (++) xs ys = augment (\c n -> foldr c n xs) ys
339  #-}
340
341 append :: [a] -> [a] -> [a]
342 append []     ys = ys
343 append (x:xs) ys = x : append xs ys
344 \end{code}
345
346
347 %*********************************************************
348 %*                                                      *
349 \subsection{Type @Bool@}
350 %*                                                      *
351 %*********************************************************
352
353 \begin{code}
354 data  Bool  =  False | True  deriving (Eq, Ord)
355         -- Read in PrelRead, Show in PrelShow
356
357 -- Boolean functions
358
359 (&&), (||)              :: Bool -> Bool -> Bool
360 True  && x              =  x
361 False && _              =  False
362 True  || _              =  True
363 False || x              =  x
364
365 not                     :: Bool -> Bool
366 not True                =  False
367 not False               =  True
368
369 otherwise               :: Bool
370 otherwise               =  True
371 \end{code}
372
373
374 %*********************************************************
375 %*                                                      *
376 \subsection{The @()@ type}
377 %*                                                      *
378 %*********************************************************
379
380 The Unit type is here because virtually any program needs it (whereas
381 some programs may get away without consulting PrelTup).  Furthermore,
382 the renamer currently *always* asks for () to be in scope, so that
383 ccalls can use () as their default type; so when compiling PrelBase we
384 need ().  (We could arrange suck in () only if -fglasgow-exts, but putting
385 it here seems more direct.)
386
387 \begin{code}
388 data  ()  =  ()
389
390 instance Eq () where
391     () == () = True
392     () /= () = False
393
394 instance Ord () where
395     () <= () = True
396     () <  () = False
397     () >= () = True
398     () >  () = False
399     max () () = ()
400     min () () = ()
401     compare () () = EQ
402 \end{code}
403
404
405 %*********************************************************
406 %*                                                      *
407 \subsection{Type @Ordering@}
408 %*                                                      *
409 %*********************************************************
410
411 \begin{code}
412 data Ordering = LT | EQ | GT deriving (Eq, Ord)
413         -- Read in PrelRead, Show in PrelShow
414 \end{code}
415
416
417 %*********************************************************
418 %*                                                      *
419 \subsection{Type @Char@ and @String@}
420 %*                                                      *
421 %*********************************************************
422
423 \begin{code}
424 type  String = [Char]
425
426 data Char = C# Char#
427
428 -- We don't use deriving for Eq and Ord, because for Ord the derived
429 -- instance defines only compare, which takes two primops.  Then
430 -- '>' uses compare, and therefore takes two primops instead of one.
431
432 instance Eq Char where
433   (C# c1) == (C# c2) = c1 `eqChar#` c2
434   (C# c1) /= (C# c2) = c1 `neChar#` c2
435
436 instance Ord Char where
437   (C# c1) >  (C# c2) = c1 `gtChar#` c2
438   (C# c1) >= (C# c2) = c1 `geChar#` c2
439   (C# c1) <= (C# c2) = c1 `leChar#` c2
440   (C# c1) <  (C# c2) = c1 `ltChar#` c2
441
442 chr :: Int -> Char
443 chr (I# i) | i >=# 0# && i <=# 255# = C# (chr# i)
444            | otherwise = error ("Prelude.chr: bad argument")
445
446 unsafeChr :: Int -> Char
447 unsafeChr (I# i) =  C# (chr# i)
448
449 ord :: Char -> Int
450 ord (C# c) =  I# (ord# c)
451 \end{code}
452
453
454 %*********************************************************
455 %*                                                      *
456 \subsection{Type @Int@}
457 %*                                                      *
458 %*********************************************************
459
460 \begin{code}
461 data Int = I# Int#
462
463 zeroInt, oneInt, twoInt, maxInt, minInt :: Int
464 zeroInt = I# 0#
465 oneInt  = I# 1#
466 twoInt  = I# 2#
467 minInt  = I# (-2147483648#)     -- GHC <= 2.09 had this at -2147483647
468 maxInt  = I# 2147483647#
469
470 instance Eq Int where
471     (==) x y = x `eqInt` y
472     (/=) x y = x `neInt` y
473
474 instance Ord Int where
475     compare x y = compareInt x y 
476
477     (<)  x y = ltInt x y
478     (<=) x y = leInt x y
479     (>=) x y = geInt x y
480     (>)  x y = gtInt x y
481
482 compareInt :: Int -> Int -> Ordering
483 (I# x) `compareInt` (I# y) | x <# y    = LT
484                            | x ==# y   = EQ
485                            | otherwise = GT
486 \end{code}
487
488
489 %*********************************************************
490 %*                                                      *
491 \subsection{The function type}
492 %*                                                      *
493 %*********************************************************
494
495 \begin{code}
496 -- identity function
497 id                      :: a -> a
498 id x                    =  x
499
500 -- constant function
501 const                   :: a -> b -> a
502 const x _               =  x
503
504 -- function composition
505 {-# INLINE (.) #-}
506 (.)       :: (b -> c) -> (a -> b) -> a -> c
507 (.) f g x = f (g x)
508
509 -- flip f  takes its (first) two arguments in the reverse order of f.
510 flip                    :: (a -> b -> c) -> b -> a -> c
511 flip f x y              =  f y x
512
513 -- right-associating infix application operator (useful in continuation-
514 -- passing style)
515 ($)                     :: (a -> b) -> a -> b
516 f $ x                   =  f x
517
518 -- until p f  yields the result of applying f until p holds.
519 until                   :: (a -> Bool) -> (a -> a) -> a -> a
520 until p f x | p x       =  x
521             | otherwise =  until p f (f x)
522
523 -- asTypeOf is a type-restricted version of const.  It is usually used
524 -- as an infix operator, and its typing forces its first argument
525 -- (which is usually overloaded) to have the same type as the second.
526 asTypeOf                :: a -> a -> a
527 asTypeOf                =  const
528 \end{code}
529
530 %*********************************************************
531 %*                                                      *
532 \subsection{CCallable instances}
533 %*                                                      *
534 %*********************************************************
535
536 Defined here to avoid orphans
537
538 \begin{code}
539 instance CCallable Char
540 instance CReturnable Char
541
542 instance CCallable   Int
543 instance CReturnable Int
544
545 instance CReturnable () -- Why, exactly?
546 \end{code}
547
548
549 %*********************************************************
550 %*                                                      *
551 \subsection{Numeric primops}
552 %*                                                      *
553 %*********************************************************
554
555 Definitions of the boxed PrimOps; these will be
556 used in the case of partial applications, etc.
557
558 \begin{code}
559 {-# INLINE eqInt #-}
560 {-# INLINE neInt #-}
561 {-# INLINE gtInt #-}
562 {-# INLINE geInt #-}
563 {-# INLINE ltInt #-}
564 {-# INLINE leInt #-}
565 {-# INLINE plusInt #-}
566 {-# INLINE minusInt #-}
567 {-# INLINE timesInt #-}
568 {-# INLINE quotInt #-}
569 {-# INLINE remInt #-}
570 {-# INLINE negateInt #-}
571
572 plusInt, minusInt, timesInt, quotInt, remInt, gcdInt :: Int -> Int -> Int
573 plusInt (I# x) (I# y) = I# (x +# y)
574 minusInt(I# x) (I# y) = I# (x -# y)
575 timesInt(I# x) (I# y) = I# (x *# y)
576 quotInt (I# x) (I# y) = I# (quotInt# x y)
577 remInt  (I# x) (I# y) = I# (remInt#  x y)
578
579 gcdInt (I# a) (I# b) = g a b
580    where g 0# 0# = error "PrelBase.gcdInt: gcd 0 0 is undefined"
581          g 0# _  = I# absB
582          g _  0# = I# absA
583          g _  _  = I# (gcdInt# absA absB)
584
585          absInt x = if x <# 0# then negateInt# x else x
586
587          absA     = absInt a
588          absB     = absInt b
589
590 negateInt :: Int -> Int
591 negateInt (I# x) = I# (negateInt# x)
592
593 divInt, modInt :: Int -> Int -> Int
594 x `divInt` y 
595   | x > zeroInt && y < zeroInt = quotInt ((x `minusInt` y) `minusInt` oneInt) y
596   | x < zeroInt && y > zeroInt = quotInt ((x `minusInt` y) `plusInt`  oneInt) y
597   | otherwise      = quotInt x y
598
599 x `modInt` y 
600   | x > zeroInt && y < zeroInt || 
601     x < zeroInt && y > zeroInt  = if r/=zeroInt then r `plusInt` y else zeroInt
602   | otherwise                   = r
603   where
604     r = remInt x y
605
606 gtInt, geInt, eqInt, neInt, ltInt, leInt :: Int -> Int -> Bool
607 gtInt   (I# x) (I# y) = x ># y
608 geInt   (I# x) (I# y) = x >=# y
609 eqInt   (I# x) (I# y) = x ==# y
610 neInt   (I# x) (I# y) = x /=# y
611 ltInt   (I# x) (I# y) = x <# y
612 leInt   (I# x) (I# y) = x <=# y
613 \end{code}
614
615
616 %********************************************************
617 %*                                                      *
618 \subsection{Unpacking C strings}
619 %*                                                      *
620 %********************************************************
621
622 This code is needed for virtually all programs, since it's used for
623 unpacking the strings of error messages.
624
625 \begin{code}
626 unpackCString#  :: Addr# -> [Char]
627 unpackCString# a = unpackCStringList# a
628
629 unpackCStringList#  :: Addr# -> [Char]
630 unpackCStringList# addr 
631   = unpack 0#
632   where
633     unpack nh
634       | ch `eqChar#` '\0'# = []
635       | otherwise          = C# ch : unpack (nh +# 1#)
636       where
637         ch = indexCharOffAddr# addr nh
638
639 unpackAppendCString# :: Addr# -> [Char] -> [Char]
640 unpackAppendCString# addr rest
641   = unpack 0#
642   where
643     unpack nh
644       | ch `eqChar#` '\0'# = rest
645       | otherwise          = C# ch : unpack (nh +# 1#)
646       where
647         ch = indexCharOffAddr# addr nh
648
649 unpackFoldrCString#  :: Addr# -> (Char  -> a -> a) -> a -> a 
650 unpackFoldrCString# addr f z 
651   = unpack 0#
652   where
653     unpack nh
654       | ch `eqChar#` '\0'# = z
655       | otherwise          = C# ch `f` unpack (nh +# 1#)
656       where
657         ch = indexCharOffAddr# addr nh
658
659 unpackNBytes#      :: Addr# -> Int#   -> [Char]
660   -- This one is called by the compiler to unpack literal 
661   -- strings with NULs in them; rare. It's strict!
662   -- We don't try to do list deforestation for this one
663
664 unpackNBytes# _addr 0#   = []
665 unpackNBytes#  addr len# = unpack [] (len# -# 1#)
666     where
667      unpack acc i#
668       | i# <# 0#  = acc
669       | otherwise = 
670          case indexCharOffAddr# addr i# of
671             ch -> unpack (C# ch : acc) (i# -# 1#)
672
673 {-# RULES
674 "unpack"         forall a   . unpackCString# a             = build (unpackFoldrCString# a)
675 "unpack-list"    forall a   . unpackFoldrCString# a (:) [] = unpackCStringList# a
676 "unpack-append"  forall a n . unpackFoldrCString# a (:) n  = unpackAppendCString# a n
677
678 -- There's a built-in rule (in PrelRules.lhs) for
679 --      unpackFoldr "foo" c (unpackFoldr "baz" c n)  =  unpackFoldr "foobaz" c n
680
681   #-}
682
683 \end{code}