Inline foldr and (.) when applied to two arguments not three
[ghc-base.git] / GHC / Base.lhs
1 \section[GHC.Base]{Module @GHC.Base@}
2
3 The overall structure of the GHC Prelude is a bit tricky.
4
5   a) We want to avoid "orphan modules", i.e. ones with instance
6         decls that don't belong either to a tycon or a class
7         defined in the same module
8
9   b) We want to avoid giant modules
10
11 So the rough structure is as follows, in (linearised) dependency order
12
13
14 GHC.Prim                Has no implementation.  It defines built-in things, and
15                 by importing it you bring them into scope.
16                 The source file is GHC.Prim.hi-boot, which is just
17                 copied to make GHC.Prim.hi
18
19 GHC.Base        Classes: Eq, Ord, Functor, Monad
20                 Types:   list, (), Int, Bool, Ordering, Char, String
21
22 Data.Tuple      Types: tuples, plus instances for GHC.Base classes
23
24 GHC.Show        Class: Show, plus instances for GHC.Base/GHC.Tup types
25
26 GHC.Enum        Class: Enum,  plus instances for GHC.Base/GHC.Tup types
27
28 Data.Maybe      Type: Maybe, plus instances for GHC.Base classes
29
30 GHC.List        List functions
31
32 GHC.Num         Class: Num, plus instances for Int
33                 Type:  Integer, plus instances for all classes so far (Eq, Ord, Num, Show)
34
35                 Integer is needed here because it is mentioned in the signature
36                 of 'fromInteger' in class Num
37
38 GHC.Real        Classes: Real, Integral, Fractional, RealFrac
39                          plus instances for Int, Integer
40                 Types:  Ratio, Rational
41                         plus intances for classes so far
42
43                 Rational is needed here because it is mentioned in the signature
44                 of 'toRational' in class Real
45
46 GHC.ST  The ST monad, instances and a few helper functions
47
48 Ix              Classes: Ix, plus instances for Int, Bool, Char, Integer, Ordering, tuples
49
50 GHC.Arr         Types: Array, MutableArray, MutableVar
51
52                 Arrays are used by a function in GHC.Float
53
54 GHC.Float       Classes: Floating, RealFloat
55                 Types:   Float, Double, plus instances of all classes so far
56
57                 This module contains everything to do with floating point.
58                 It is a big module (900 lines)
59                 With a bit of luck, many modules can be compiled without ever reading GHC.Float.hi
60
61
62 Other Prelude modules are much easier with fewer complex dependencies.
63
64 \begin{code}
65 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
66 {-# OPTIONS_GHC -fno-warn-orphans #-}
67 {-# OPTIONS_HADDOCK hide #-}
68 -----------------------------------------------------------------------------
69 -- |
70 -- Module      :  GHC.Base
71 -- Copyright   :  (c) The University of Glasgow, 1992-2002
72 -- License     :  see libraries/base/LICENSE
73 -- 
74 -- Maintainer  :  cvs-ghc@haskell.org
75 -- Stability   :  internal
76 -- Portability :  non-portable (GHC extensions)
77 --
78 -- Basic data types and classes.
79 -- 
80 -----------------------------------------------------------------------------
81
82 #include "MachDeps.h"
83
84 -- #hide
85 module GHC.Base
86         (
87         module GHC.Base,
88         module GHC.Bool,
89         module GHC.Classes,
90         module GHC.Generics,
91         module GHC.Ordering,
92         module GHC.Types,
93         module GHC.Prim,        -- Re-export GHC.Prim and GHC.Err, to avoid lots
94         module GHC.Err          -- of people having to import it explicitly
95   ) 
96         where
97
98 import GHC.Types
99 import GHC.Bool
100 import GHC.Classes
101 import GHC.Generics
102 import GHC.Ordering
103 import GHC.Prim
104 import {-# SOURCE #-} GHC.Show
105 import {-# SOURCE #-} GHC.Err
106 import {-# SOURCE #-} GHC.IO (failIO)
107
108 -- These two are not strictly speaking required by this module, but they are
109 -- implicit dependencies whenever () or tuples are mentioned, so adding them
110 -- as imports here helps to get the dependencies right in the new build system.
111 import GHC.Tuple ()
112 import GHC.Unit ()
113
114 infixr 9  .
115 infixr 5  ++
116 infixl 4  <$
117 infixl 1  >>, >>=
118 infixr 0  $
119
120 default ()              -- Double isn't available yet
121 \end{code}
122
123
124 %*********************************************************
125 %*                                                      *
126 \subsection{DEBUGGING STUFF}
127 %*  (for use when compiling GHC.Base itself doesn't work)
128 %*                                                      *
129 %*********************************************************
130
131 \begin{code}
132 {-
133 data  Bool  =  False | True
134 data Ordering = LT | EQ | GT 
135 data Char = C# Char#
136 type  String = [Char]
137 data Int = I# Int#
138 data  ()  =  ()
139 data [] a = MkNil
140
141 not True = False
142 (&&) True True = True
143 otherwise = True
144
145 build = error "urk"
146 foldr = error "urk"
147
148 unpackCString# :: Addr# -> [Char]
149 unpackFoldrCString# :: Addr# -> (Char  -> a -> a) -> a -> a 
150 unpackAppendCString# :: Addr# -> [Char] -> [Char]
151 unpackCStringUtf8# :: Addr# -> [Char]
152 unpackCString# a = error "urk"
153 unpackFoldrCString# a = error "urk"
154 unpackAppendCString# a = error "urk"
155 unpackCStringUtf8# a = error "urk"
156 -}
157 \end{code}
158
159
160 %*********************************************************
161 %*                                                      *
162 \subsection{Monadic classes @Functor@, @Monad@ }
163 %*                                                      *
164 %*********************************************************
165
166 \begin{code}
167 {- | The 'Functor' class is used for types that can be mapped over.
168 Instances of 'Functor' should satisfy the following laws:
169
170 > fmap id  ==  id
171 > fmap (f . g)  ==  fmap f . fmap g
172
173 The instances of 'Functor' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'
174 defined in the "Prelude" satisfy these laws.
175 -}
176
177 class  Functor f  where
178     fmap        :: (a -> b) -> f a -> f b
179
180     -- | Replace all locations in the input with the same value.
181     -- The default definition is @'fmap' . 'const'@, but this may be
182     -- overridden with a more efficient version.
183     (<$)        :: a -> f b -> f a
184     (<$)        =  fmap . const
185
186 {- | The 'Monad' class defines the basic operations over a /monad/,
187 a concept from a branch of mathematics known as /category theory/.
188 From the perspective of a Haskell programmer, however, it is best to
189 think of a monad as an /abstract datatype/ of actions.
190 Haskell's @do@ expressions provide a convenient syntax for writing
191 monadic expressions.
192
193 Minimal complete definition: '>>=' and 'return'.
194
195 Instances of 'Monad' should satisfy the following laws:
196
197 > return a >>= k  ==  k a
198 > m >>= return  ==  m
199 > m >>= (\x -> k x >>= h)  ==  (m >>= k) >>= h
200
201 Instances of both 'Monad' and 'Functor' should additionally satisfy the law:
202
203 > fmap f xs  ==  xs >>= return . f
204
205 The instances of 'Monad' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'
206 defined in the "Prelude" satisfy these laws.
207 -}
208
209 class  Monad m  where
210     -- | Sequentially compose two actions, passing any value produced
211     -- by the first as an argument to the second.
212     (>>=)       :: forall a b. m a -> (a -> m b) -> m b
213     -- | Sequentially compose two actions, discarding any value produced
214     -- by the first, like sequencing operators (such as the semicolon)
215     -- in imperative languages.
216     (>>)        :: forall a b. m a -> m b -> m b
217         -- Explicit for-alls so that we know what order to
218         -- give type arguments when desugaring
219
220     -- | Inject a value into the monadic type.
221     return      :: a -> m a
222     -- | Fail with a message.  This operation is not part of the
223     -- mathematical definition of a monad, but is invoked on pattern-match
224     -- failure in a @do@ expression.
225     fail        :: String -> m a
226
227     m >> k      = m >>= \_ -> k
228     fail s      = error s
229 \end{code}
230
231
232 %*********************************************************
233 %*                                                      *
234 \subsection{The list type}
235 %*                                                      *
236 %*********************************************************
237
238 \begin{code}
239 -- do explicitly: deriving (Eq, Ord)
240 -- to avoid weird names like con2tag_[]#
241
242 instance (Eq a) => Eq [a] where
243     {-# SPECIALISE instance Eq [Char] #-}
244     []     == []     = True
245     (x:xs) == (y:ys) = x == y && xs == ys
246     _xs    == _ys    = False
247
248 instance (Ord a) => Ord [a] where
249     {-# SPECIALISE instance Ord [Char] #-}
250     compare []     []     = EQ
251     compare []     (_:_)  = LT
252     compare (_:_)  []     = GT
253     compare (x:xs) (y:ys) = case compare x y of
254                                 EQ    -> compare xs ys
255                                 other -> other
256
257 instance Functor [] where
258     fmap = map
259
260 instance  Monad []  where
261     m >>= k             = foldr ((++) . k) [] m
262     m >> k              = foldr ((++) . (\ _ -> k)) [] m
263     return x            = [x]
264     fail _              = []
265 \end{code}
266
267 A few list functions that appear here because they are used here.
268 The rest of the prelude list functions are in GHC.List.
269
270 ----------------------------------------------
271 --      foldr/build/augment
272 ----------------------------------------------
273   
274 \begin{code}
275 -- | 'foldr', applied to a binary operator, a starting value (typically
276 -- the right-identity of the operator), and a list, reduces the list
277 -- using the binary operator, from right to left:
278 --
279 -- > foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
280
281 foldr            :: (a -> b -> b) -> b -> [a] -> b
282 -- foldr _ z []     =  z
283 -- foldr f z (x:xs) =  f x (foldr f z xs)
284 {-# INLINE [0] foldr #-}
285 -- Inline only in the final stage, after the foldr/cons rule has had a chance
286 -- Also note that we inline it when it has *two* parameters, which are the 
287 -- ones we are keen about specialising!
288 foldr k z = go
289           where
290             go []     = z
291             go (y:ys) = y `k` go ys
292
293 -- | A list producer that can be fused with 'foldr'.
294 -- This function is merely
295 --
296 -- >    build g = g (:) []
297 --
298 -- but GHC's simplifier will transform an expression of the form
299 -- @'foldr' k z ('build' g)@, which may arise after inlining, to @g k z@,
300 -- which avoids producing an intermediate list.
301
302 build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
303 {-# INLINE [1] build #-}
304         -- The INLINE is important, even though build is tiny,
305         -- because it prevents [] getting inlined in the version that
306         -- appears in the interface file.  If [] *is* inlined, it
307         -- won't match with [] appearing in rules in an importing module.
308         --
309         -- The "1" says to inline in phase 1
310
311 build g = g (:) []
312
313 -- | A list producer that can be fused with 'foldr'.
314 -- This function is merely
315 --
316 -- >    augment g xs = g (:) xs
317 --
318 -- but GHC's simplifier will transform an expression of the form
319 -- @'foldr' k z ('augment' g xs)@, which may arise after inlining, to
320 -- @g k ('foldr' k z xs)@, which avoids producing an intermediate list.
321
322 augment :: forall a. (forall b. (a->b->b) -> b -> b) -> [a] -> [a]
323 {-# INLINE [1] augment #-}
324 augment g xs = g (:) xs
325
326 {-# RULES
327 "fold/build"    forall k z (g::forall b. (a->b->b) -> b -> b) . 
328                 foldr k z (build g) = g k z
329
330 "foldr/augment" forall k z xs (g::forall b. (a->b->b) -> b -> b) . 
331                 foldr k z (augment g xs) = g k (foldr k z xs)
332
333 "foldr/id"                        foldr (:) [] = \x  -> x
334 "foldr/app"     [1] forall ys. foldr (:) ys = \xs -> xs ++ ys
335         -- Only activate this from phase 1, because that's
336         -- when we disable the rule that expands (++) into foldr
337
338 -- The foldr/cons rule looks nice, but it can give disastrously
339 -- bloated code when commpiling
340 --      array (a,b) [(1,2), (2,2), (3,2), ...very long list... ]
341 -- i.e. when there are very very long literal lists
342 -- So I've disabled it for now. We could have special cases
343 -- for short lists, I suppose.
344 -- "foldr/cons" forall k z x xs. foldr k z (x:xs) = k x (foldr k z xs)
345
346 "foldr/single"  forall k z x. foldr k z [x] = k x z
347 "foldr/nil"     forall k z.   foldr k z []  = z 
348
349 "augment/build" forall (g::forall b. (a->b->b) -> b -> b)
350                        (h::forall b. (a->b->b) -> b -> b) .
351                        augment g (build h) = build (\c n -> g c (h c n))
352 "augment/nil"   forall (g::forall b. (a->b->b) -> b -> b) .
353                         augment g [] = build g
354  #-}
355
356 -- This rule is true, but not (I think) useful:
357 --      augment g (augment h t) = augment (\cn -> g c (h c n)) t
358 \end{code}
359
360
361 ----------------------------------------------
362 --              map     
363 ----------------------------------------------
364
365 \begin{code}
366 -- | 'map' @f xs@ is the list obtained by applying @f@ to each element
367 -- of @xs@, i.e.,
368 --
369 -- > map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
370 -- > map f [x1, x2, ...] == [f x1, f x2, ...]
371
372 map :: (a -> b) -> [a] -> [b]
373 map _ []     = []
374 map f (x:xs) = f x : map f xs
375
376 -- Note eta expanded
377 mapFB ::  (elt -> lst -> lst) -> (a -> elt) -> a -> lst -> lst
378 {-# INLINE [0] mapFB #-}
379 mapFB c f x ys = c (f x) ys
380
381 -- The rules for map work like this.
382 -- 
383 -- Up to (but not including) phase 1, we use the "map" rule to
384 -- rewrite all saturated applications of map with its build/fold 
385 -- form, hoping for fusion to happen.
386 -- In phase 1 and 0, we switch off that rule, inline build, and
387 -- switch on the "mapList" rule, which rewrites the foldr/mapFB
388 -- thing back into plain map.  
389 --
390 -- It's important that these two rules aren't both active at once 
391 -- (along with build's unfolding) else we'd get an infinite loop 
392 -- in the rules.  Hence the activation control below.
393 --
394 -- The "mapFB" rule optimises compositions of map.
395 --
396 -- This same pattern is followed by many other functions: 
397 -- e.g. append, filter, iterate, repeat, etc.
398
399 {-# RULES
400 "map"       [~1] forall f xs.   map f xs                = build (\c n -> foldr (mapFB c f) n xs)
401 "mapList"   [1]  forall f.      foldr (mapFB (:) f) []  = map f
402 "mapFB"     forall c f g.       mapFB (mapFB c f) g     = mapFB c (f.g) 
403   #-}
404 \end{code}
405
406
407 ----------------------------------------------
408 --              append  
409 ----------------------------------------------
410 \begin{code}
411 -- | Append two lists, i.e.,
412 --
413 -- > [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
414 -- > [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
415 --
416 -- If the first list is not finite, the result is the first list.
417
418 (++) :: [a] -> [a] -> [a]
419 (++) []     ys = ys
420 (++) (x:xs) ys = x : xs ++ ys
421
422 {-# RULES
423 "++"    [~1] forall xs ys. xs ++ ys = augment (\c n -> foldr c n xs) ys
424   #-}
425
426 \end{code}
427
428
429 %*********************************************************
430 %*                                                      *
431 \subsection{Type @Bool@}
432 %*                                                      *
433 %*********************************************************
434
435 \begin{code}
436 -- |The 'Bool' type is an enumeration.  It is defined with 'False'
437 -- first so that the corresponding 'Prelude.Enum' instance will give
438 -- 'Prelude.fromEnum' 'False' the value zero, and
439 -- 'Prelude.fromEnum' 'True' the value 1.
440 -- The actual definition is in the ghc-prim package.
441
442 -- XXX These don't work:
443 -- deriving instance Eq Bool
444 -- deriving instance Ord Bool
445 -- <wired into compiler>:
446 --     Illegal binding of built-in syntax: con2tag_Bool#
447
448 instance Eq Bool where
449     True  == True  = True
450     False == False = True
451     _     == _     = False
452
453 instance Ord Bool where
454     compare False True  = LT
455     compare True  False = GT
456     compare _     _     = EQ
457
458 -- Read is in GHC.Read, Show in GHC.Show
459
460 -- |'otherwise' is defined as the value 'True'.  It helps to make
461 -- guards more readable.  eg.
462 --
463 -- >  f x | x < 0     = ...
464 -- >      | otherwise = ...
465 otherwise               :: Bool
466 otherwise               =  True
467 \end{code}
468
469 %*********************************************************
470 %*                                                      *
471 \subsection{Type @Ordering@}
472 %*                                                      *
473 %*********************************************************
474
475 \begin{code}
476 -- | Represents an ordering relationship between two values: less
477 -- than, equal to, or greater than.  An 'Ordering' is returned by
478 -- 'compare'.
479 -- XXX These don't work:
480 -- deriving instance Eq Ordering
481 -- deriving instance Ord Ordering
482 -- Illegal binding of built-in syntax: con2tag_Ordering#
483 instance Eq Ordering where
484     EQ == EQ = True
485     LT == LT = True
486     GT == GT = True
487     _  == _  = False
488         -- Read in GHC.Read, Show in GHC.Show
489
490 instance Ord Ordering where
491     LT <= _  = True
492     _  <= LT = False
493     EQ <= _  = True
494     _  <= EQ = False
495     GT <= GT = True
496 \end{code}
497
498
499 %*********************************************************
500 %*                                                      *
501 \subsection{Type @Char@ and @String@}
502 %*                                                      *
503 %*********************************************************
504
505 \begin{code}
506 -- | A 'String' is a list of characters.  String constants in Haskell are values
507 -- of type 'String'.
508 --
509 type String = [Char]
510
511 {-| The character type 'Char' is an enumeration whose values represent
512 Unicode (or equivalently ISO\/IEC 10646) characters
513 (see <http://www.unicode.org/> for details).
514 This set extends the ISO 8859-1 (Latin-1) character set
515 (the first 256 charachers), which is itself an extension of the ASCII
516 character set (the first 128 characters).
517 A character literal in Haskell has type 'Char'.
518
519 To convert a 'Char' to or from the corresponding 'Int' value defined
520 by Unicode, use 'Prelude.toEnum' and 'Prelude.fromEnum' from the
521 'Prelude.Enum' class respectively (or equivalently 'ord' and 'chr').
522 -}
523
524 -- We don't use deriving for Eq and Ord, because for Ord the derived
525 -- instance defines only compare, which takes two primops.  Then
526 -- '>' uses compare, and therefore takes two primops instead of one.
527
528 instance Eq Char where
529     (C# c1) == (C# c2) = c1 `eqChar#` c2
530     (C# c1) /= (C# c2) = c1 `neChar#` c2
531
532 instance Ord Char where
533     (C# c1) >  (C# c2) = c1 `gtChar#` c2
534     (C# c1) >= (C# c2) = c1 `geChar#` c2
535     (C# c1) <= (C# c2) = c1 `leChar#` c2
536     (C# c1) <  (C# c2) = c1 `ltChar#` c2
537
538 {-# RULES
539 "x# `eqChar#` x#" forall x#. x# `eqChar#` x# = True
540 "x# `neChar#` x#" forall x#. x# `neChar#` x# = False
541 "x# `gtChar#` x#" forall x#. x# `gtChar#` x# = False
542 "x# `geChar#` x#" forall x#. x# `geChar#` x# = True
543 "x# `leChar#` x#" forall x#. x# `leChar#` x# = True
544 "x# `ltChar#` x#" forall x#. x# `ltChar#` x# = False
545   #-}
546
547 -- | The 'Prelude.toEnum' method restricted to the type 'Data.Char.Char'.
548 chr :: Int -> Char
549 chr i@(I# i#)
550  | int2Word# i# `leWord#` int2Word# 0x10FFFF# = C# (chr# i#)
551  | otherwise
552     = error ("Prelude.chr: bad argument: " ++ showSignedInt (I# 9#) i "")
553
554 unsafeChr :: Int -> Char
555 unsafeChr (I# i#) = C# (chr# i#)
556
557 -- | The 'Prelude.fromEnum' method restricted to the type 'Data.Char.Char'.
558 ord :: Char -> Int
559 ord (C# c#) = I# (ord# c#)
560 \end{code}
561
562 String equality is used when desugaring pattern-matches against strings.
563
564 \begin{code}
565 eqString :: String -> String -> Bool
566 eqString []       []       = True
567 eqString (c1:cs1) (c2:cs2) = c1 == c2 && cs1 `eqString` cs2
568 eqString _        _        = False
569
570 {-# RULES "eqString" (==) = eqString #-}
571 -- eqString also has a BuiltInRule in PrelRules.lhs:
572 --      eqString (unpackCString# (Lit s1)) (unpackCString# (Lit s2) = s1==s2
573 \end{code}
574
575
576 %*********************************************************
577 %*                                                      *
578 \subsection{Type @Int@}
579 %*                                                      *
580 %*********************************************************
581
582 \begin{code}
583 zeroInt, oneInt, twoInt, maxInt, minInt :: Int
584 zeroInt = I# 0#
585 oneInt  = I# 1#
586 twoInt  = I# 2#
587
588 {- Seems clumsy. Should perhaps put minInt and MaxInt directly into MachDeps.h -}
589 #if WORD_SIZE_IN_BITS == 31
590 minInt  = I# (-0x40000000#)
591 maxInt  = I# 0x3FFFFFFF#
592 #elif WORD_SIZE_IN_BITS == 32
593 minInt  = I# (-0x80000000#)
594 maxInt  = I# 0x7FFFFFFF#
595 #else 
596 minInt  = I# (-0x8000000000000000#)
597 maxInt  = I# 0x7FFFFFFFFFFFFFFF#
598 #endif
599
600 instance Eq Int where
601     (==) = eqInt
602     (/=) = neInt
603
604 instance Ord Int where
605     compare = compareInt
606     (<)     = ltInt
607     (<=)    = leInt
608     (>=)    = geInt
609     (>)     = gtInt
610
611 compareInt :: Int -> Int -> Ordering
612 (I# x#) `compareInt` (I# y#) = compareInt# x# y#
613
614 compareInt# :: Int# -> Int# -> Ordering
615 compareInt# x# y#
616     | x# <#  y# = LT
617     | x# ==# y# = EQ
618     | otherwise = GT
619 \end{code}
620
621
622 %*********************************************************
623 %*                                                      *
624 \subsection{The function type}
625 %*                                                      *
626 %*********************************************************
627
628 \begin{code}
629 -- | Identity function.
630 id                      :: a -> a
631 id x                    =  x
632
633 -- | The call '(lazy e)' means the same as 'e', but 'lazy' has a 
634 -- magical strictness property: it is lazy in its first argument, 
635 -- even though its semantics is strict.
636 lazy :: a -> a
637 lazy x = x
638 -- Implementation note: its strictness and unfolding are over-ridden
639 -- by the definition in MkId.lhs; in both cases to nothing at all.
640 -- That way, 'lazy' does not get inlined, and the strictness analyser
641 -- sees it as lazy.  Then the worker/wrapper phase inlines it.
642 -- Result: happiness
643
644
645 -- | The call '(inline f)' reduces to 'f', but 'inline' has a BuiltInRule
646 -- that tries to inline 'f' (if it has an unfolding) unconditionally
647 -- The 'NOINLINE' pragma arranges that inline only gets inlined (and
648 -- hence eliminated) late in compilation, after the rule has had
649 -- a god chance to fire.
650 inline :: a -> a
651 {-# NOINLINE[0] inline #-}
652 inline x = x
653
654 -- Assertion function.  This simply ignores its boolean argument.
655 -- The compiler may rewrite it to @('assertError' line)@.
656
657 -- | If the first argument evaluates to 'True', then the result is the
658 -- second argument.  Otherwise an 'AssertionFailed' exception is raised,
659 -- containing a 'String' with the source file and line number of the
660 -- call to 'assert'.
661 --
662 -- Assertions can normally be turned on or off with a compiler flag
663 -- (for GHC, assertions are normally on unless optimisation is turned on 
664 -- with @-O@ or the @-fignore-asserts@
665 -- option is given).  When assertions are turned off, the first
666 -- argument to 'assert' is ignored, and the second argument is
667 -- returned as the result.
668
669 --      SLPJ: in 5.04 etc 'assert' is in GHC.Prim,
670 --      but from Template Haskell onwards it's simply
671 --      defined here in Base.lhs
672 assert :: Bool -> a -> a
673 assert _pred r = r
674
675 breakpoint :: a -> a
676 breakpoint r = r
677
678 breakpointCond :: Bool -> a -> a
679 breakpointCond _ r = r
680
681 data Opaque = forall a. O a
682
683 -- | Constant function.
684 const                   :: a -> b -> a
685 const x _               =  x
686
687 -- | Function composition.
688 {-# INLINE (.) #-}
689 -- Make sure it has TWO args only on the left, so that it inlines
690 -- when applied to two functions, even if there is no final argument
691 (.)    :: (b -> c) -> (a -> b) -> a -> c
692 (.) f g = \x -> f (g x)
693
694 -- | @'flip' f@ takes its (first) two arguments in the reverse order of @f@.
695 flip                    :: (a -> b -> c) -> b -> a -> c
696 flip f x y              =  f y x
697
698 -- | Application operator.  This operator is redundant, since ordinary
699 -- application @(f x)@ means the same as @(f '$' x)@. However, '$' has
700 -- low, right-associative binding precedence, so it sometimes allows
701 -- parentheses to be omitted; for example:
702 --
703 -- >     f $ g $ h x  =  f (g (h x))
704 --
705 -- It is also useful in higher-order situations, such as @'map' ('$' 0) xs@,
706 -- or @'Data.List.zipWith' ('$') fs xs@.
707 {-# INLINE ($) #-}
708 ($)                     :: (a -> b) -> a -> b
709 f $ x                   =  f x
710
711 -- | @'until' p f@ yields the result of applying @f@ until @p@ holds.
712 until                   :: (a -> Bool) -> (a -> a) -> a -> a
713 until p f x | p x       =  x
714             | otherwise =  until p f (f x)
715
716 -- | 'asTypeOf' is a type-restricted version of 'const'.  It is usually
717 -- used as an infix operator, and its typing forces its first argument
718 -- (which is usually overloaded) to have the same type as the second.
719 asTypeOf                :: a -> a -> a
720 asTypeOf                =  const
721 \end{code}
722
723 %*********************************************************
724 %*                                                      *
725 \subsection{@Functor@ and @Monad@ instances for @IO@}
726 %*                                                      *
727 %*********************************************************
728
729 \begin{code}
730 instance  Functor IO where
731    fmap f x = x >>= (return . f)
732
733 instance  Monad IO  where
734     {-# INLINE return #-}
735     {-# INLINE (>>)   #-}
736     {-# INLINE (>>=)  #-}
737     m >> k    = m >>= \ _ -> k
738     return    = returnIO
739     (>>=)     = bindIO
740     fail s    = GHC.IO.failIO s
741
742 returnIO :: a -> IO a
743 returnIO x = IO $ \ s -> (# s, x #)
744
745 bindIO :: IO a -> (a -> IO b) -> IO b
746 bindIO (IO m) k = IO $ \ s -> case m s of (# new_s, a #) -> unIO (k a) new_s
747
748 thenIO :: IO a -> IO b -> IO b
749 thenIO (IO m) k = IO $ \ s -> case m s of (# new_s, _ #) -> unIO k new_s
750
751 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
752 unIO (IO a) = a
753 \end{code}
754
755 %*********************************************************
756 %*                                                      *
757 \subsection{@getTag@}
758 %*                                                      *
759 %*********************************************************
760
761 Returns the 'tag' of a constructor application; this function is used
762 by the deriving code for Eq, Ord and Enum.
763
764 The primitive dataToTag# requires an evaluated constructor application
765 as its argument, so we provide getTag as a wrapper that performs the
766 evaluation before calling dataToTag#.  We could have dataToTag#
767 evaluate its argument, but we prefer to do it this way because (a)
768 dataToTag# can be an inline primop if it doesn't need to do any
769 evaluation, and (b) we want to expose the evaluation to the
770 simplifier, because it might be possible to eliminate the evaluation
771 in the case when the argument is already known to be evaluated.
772
773 \begin{code}
774 {-# INLINE getTag #-}
775 getTag :: a -> Int#
776 getTag x = x `seq` dataToTag# x
777 \end{code}
778
779 %*********************************************************
780 %*                                                      *
781 \subsection{Numeric primops}
782 %*                                                      *
783 %*********************************************************
784
785 \begin{code}
786 divInt# :: Int# -> Int# -> Int#
787 x# `divInt#` y#
788         -- Be careful NOT to overflow if we do any additional arithmetic
789         -- on the arguments...  the following  previous version of this
790         -- code has problems with overflow:
791 --    | (x# ># 0#) && (y# <# 0#) = ((x# -# y#) -# 1#) `quotInt#` y#
792 --    | (x# <# 0#) && (y# ># 0#) = ((x# -# y#) +# 1#) `quotInt#` y#
793     | (x# ># 0#) && (y# <# 0#) = ((x# -# 1#) `quotInt#` y#) -# 1#
794     | (x# <# 0#) && (y# ># 0#) = ((x# +# 1#) `quotInt#` y#) -# 1#
795     | otherwise                = x# `quotInt#` y#
796
797 modInt# :: Int# -> Int# -> Int#
798 x# `modInt#` y#
799     | (x# ># 0#) && (y# <# 0#) ||
800       (x# <# 0#) && (y# ># 0#)    = if r# /=# 0# then r# +# y# else 0#
801     | otherwise                   = r#
802     where
803     !r# = x# `remInt#` y#
804 \end{code}
805
806 Definitions of the boxed PrimOps; these will be
807 used in the case of partial applications, etc.
808
809 \begin{code}
810 {-# INLINE eqInt #-}
811 {-# INLINE neInt #-}
812 {-# INLINE gtInt #-}
813 {-# INLINE geInt #-}
814 {-# INLINE ltInt #-}
815 {-# INLINE leInt #-}
816 {-# INLINE plusInt #-}
817 {-# INLINE minusInt #-}
818 {-# INLINE timesInt #-}
819 {-# INLINE quotInt #-}
820 {-# INLINE remInt #-}
821 {-# INLINE negateInt #-}
822
823 plusInt, minusInt, timesInt, quotInt, remInt, divInt, modInt :: Int -> Int -> Int
824 (I# x) `plusInt`  (I# y) = I# (x +# y)
825 (I# x) `minusInt` (I# y) = I# (x -# y)
826 (I# x) `timesInt` (I# y) = I# (x *# y)
827 (I# x) `quotInt`  (I# y) = I# (x `quotInt#` y)
828 (I# x) `remInt`   (I# y) = I# (x `remInt#`  y)
829 (I# x) `divInt`   (I# y) = I# (x `divInt#`  y)
830 (I# x) `modInt`   (I# y) = I# (x `modInt#`  y)
831
832 {-# RULES
833 "x# +# 0#" forall x#. x# +# 0# = x#
834 "0# +# x#" forall x#. 0# +# x# = x#
835 "x# -# 0#" forall x#. x# -# 0# = x#
836 "x# -# x#" forall x#. x# -# x# = 0#
837 "x# *# 0#" forall x#. x# *# 0# = 0#
838 "0# *# x#" forall x#. 0# *# x# = 0#
839 "x# *# 1#" forall x#. x# *# 1# = x#
840 "1# *# x#" forall x#. 1# *# x# = x#
841   #-}
842
843 negateInt :: Int -> Int
844 negateInt (I# x) = I# (negateInt# x)
845
846 gtInt, geInt, eqInt, neInt, ltInt, leInt :: Int -> Int -> Bool
847 (I# x) `gtInt` (I# y) = x >#  y
848 (I# x) `geInt` (I# y) = x >=# y
849 (I# x) `eqInt` (I# y) = x ==# y
850 (I# x) `neInt` (I# y) = x /=# y
851 (I# x) `ltInt` (I# y) = x <#  y
852 (I# x) `leInt` (I# y) = x <=# y
853
854 {-# RULES
855 "x# ># x#"  forall x#. x# >#  x# = False
856 "x# >=# x#" forall x#. x# >=# x# = True
857 "x# ==# x#" forall x#. x# ==# x# = True
858 "x# /=# x#" forall x#. x# /=# x# = False
859 "x# <# x#"  forall x#. x# <#  x# = False
860 "x# <=# x#" forall x#. x# <=# x# = True
861   #-}
862
863 {-# RULES
864 "plusFloat x 0.0"   forall x#. plusFloat#  x#   0.0# = x#
865 "plusFloat 0.0 x"   forall x#. plusFloat#  0.0# x#   = x#
866 "minusFloat x 0.0"  forall x#. minusFloat# x#   0.0# = x#
867 "minusFloat x x"    forall x#. minusFloat# x#   x#   = 0.0#
868 "timesFloat x 0.0"  forall x#. timesFloat# x#   0.0# = 0.0#
869 "timesFloat0.0 x"   forall x#. timesFloat# 0.0# x#   = 0.0#
870 "timesFloat x 1.0"  forall x#. timesFloat# x#   1.0# = x#
871 "timesFloat 1.0 x"  forall x#. timesFloat# 1.0# x#   = x#
872 "divideFloat x 1.0" forall x#. divideFloat# x#  1.0# = x#
873   #-}
874
875 {-# RULES
876 "plusDouble x 0.0"   forall x#. (+##) x#    0.0## = x#
877 "plusDouble 0.0 x"   forall x#. (+##) 0.0## x#    = x#
878 "minusDouble x 0.0"  forall x#. (-##) x#    0.0## = x#
879 "timesDouble x 1.0"  forall x#. (*##) x#    1.0## = x#
880 "timesDouble 1.0 x"  forall x#. (*##) 1.0## x#    = x#
881 "divideDouble x 1.0" forall x#. (/##) x#    1.0## = x#
882   #-}
883
884 {-
885 We'd like to have more rules, but for example:
886
887 This gives wrong answer (0) for NaN - NaN (should be NaN):
888     "minusDouble x x"    forall x#. (-##) x#    x#    = 0.0##
889
890 This gives wrong answer (0) for 0 * NaN (should be NaN):
891     "timesDouble 0.0 x"  forall x#. (*##) 0.0## x#    = 0.0##
892
893 This gives wrong answer (0) for NaN * 0 (should be NaN):
894     "timesDouble x 0.0"  forall x#. (*##) x#    0.0## = 0.0##
895
896 These are tested by num014.
897 -}
898
899 -- Wrappers for the shift operations.  The uncheckedShift# family are
900 -- undefined when the amount being shifted by is greater than the size
901 -- in bits of Int#, so these wrappers perform a check and return
902 -- either zero or -1 appropriately.
903 --
904 -- Note that these wrappers still produce undefined results when the
905 -- second argument (the shift amount) is negative.
906
907 -- | Shift the argument left by the specified number of bits
908 -- (which must be non-negative).
909 shiftL# :: Word# -> Int# -> Word#
910 a `shiftL#` b   | b >=# WORD_SIZE_IN_BITS# = int2Word# 0#
911                 | otherwise                = a `uncheckedShiftL#` b
912
913 -- | Shift the argument right by the specified number of bits
914 -- (which must be non-negative).
915 shiftRL# :: Word# -> Int# -> Word#
916 a `shiftRL#` b  | b >=# WORD_SIZE_IN_BITS# = int2Word# 0#
917                 | otherwise                = a `uncheckedShiftRL#` b
918
919 -- | Shift the argument left by the specified number of bits
920 -- (which must be non-negative).
921 iShiftL# :: Int# -> Int# -> Int#
922 a `iShiftL#` b  | b >=# WORD_SIZE_IN_BITS# = 0#
923                 | otherwise                = a `uncheckedIShiftL#` b
924
925 -- | Shift the argument right (signed) by the specified number of bits
926 -- (which must be non-negative).
927 iShiftRA# :: Int# -> Int# -> Int#
928 a `iShiftRA#` b | b >=# WORD_SIZE_IN_BITS# = if a <# 0# then (-1#) else 0#
929                 | otherwise                = a `uncheckedIShiftRA#` b
930
931 -- | Shift the argument right (unsigned) by the specified number of bits
932 -- (which must be non-negative).
933 iShiftRL# :: Int# -> Int# -> Int#
934 a `iShiftRL#` b | b >=# WORD_SIZE_IN_BITS# = 0#
935                 | otherwise                = a `uncheckedIShiftRL#` b
936
937 #if WORD_SIZE_IN_BITS == 32
938 {-# RULES
939 "narrow32Int#"  forall x#. narrow32Int#   x# = x#
940 "narrow32Word#" forall x#. narrow32Word#   x# = x#
941    #-}
942 #endif
943
944 {-# RULES
945 "int2Word2Int"  forall x#. int2Word# (word2Int# x#) = x#
946 "word2Int2Word" forall x#. word2Int# (int2Word# x#) = x#
947   #-}
948 \end{code}
949
950
951 %********************************************************
952 %*                                                      *
953 \subsection{Unpacking C strings}
954 %*                                                      *
955 %********************************************************
956
957 This code is needed for virtually all programs, since it's used for
958 unpacking the strings of error messages.
959
960 \begin{code}
961 unpackCString# :: Addr# -> [Char]
962 {-# NOINLINE unpackCString# #-}
963     -- There's really no point in inlining this, ever, cos
964     -- the loop doesn't specialise in an interesting
965     -- But it's pretty small, so there's a danger that
966     -- it'll be inlined at every literal, which is a waste
967 unpackCString# addr 
968   = unpack 0#
969   where
970     unpack nh
971       | ch `eqChar#` '\0'# = []
972       | otherwise          = C# ch : unpack (nh +# 1#)
973       where
974         !ch = indexCharOffAddr# addr nh
975
976 unpackAppendCString# :: Addr# -> [Char] -> [Char]
977 {-# NOINLINE unpackAppendCString# #-}
978      -- See the NOINLINE note on unpackCString# 
979 unpackAppendCString# addr rest
980   = unpack 0#
981   where
982     unpack nh
983       | ch `eqChar#` '\0'# = rest
984       | otherwise          = C# ch : unpack (nh +# 1#)
985       where
986         !ch = indexCharOffAddr# addr nh
987
988 unpackFoldrCString# :: Addr# -> (Char  -> a -> a) -> a -> a 
989 {-# NOINLINE [0] unpackFoldrCString# #-}
990 -- Unlike unpackCString#, there *is* some point in inlining unpackFoldrCString#, 
991 -- because we get better code for the function call.
992 -- However, don't inline till right at the end;
993 -- usually the unpack-list rule turns it into unpackCStringList
994 -- It also has a BuiltInRule in PrelRules.lhs:
995 --      unpackFoldrCString# "foo" c (unpackFoldrCString# "baz" c n)
996 --        =  unpackFoldrCString# "foobaz" c n
997 unpackFoldrCString# addr f z 
998   = unpack 0#
999   where
1000     unpack nh
1001       | ch `eqChar#` '\0'# = z
1002       | otherwise          = C# ch `f` unpack (nh +# 1#)
1003       where
1004         !ch = indexCharOffAddr# addr nh
1005
1006 unpackCStringUtf8# :: Addr# -> [Char]
1007 unpackCStringUtf8# addr 
1008   = unpack 0#
1009   where
1010     unpack nh
1011       | ch `eqChar#` '\0'#   = []
1012       | ch `leChar#` '\x7F'# = C# ch : unpack (nh +# 1#)
1013       | ch `leChar#` '\xDF'# =
1014           C# (chr# (((ord# ch                                  -# 0xC0#) `uncheckedIShiftL#`  6#) +#
1015                      (ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#))) :
1016           unpack (nh +# 2#)
1017       | ch `leChar#` '\xEF'# =
1018           C# (chr# (((ord# ch                                  -# 0xE0#) `uncheckedIShiftL#` 12#) +#
1019                     ((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#`  6#) +#
1020                      (ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#))) :
1021           unpack (nh +# 3#)
1022       | otherwise            =
1023           C# (chr# (((ord# ch                                  -# 0xF0#) `uncheckedIShiftL#` 18#) +#
1024                     ((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#` 12#) +#
1025                     ((ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#) `uncheckedIShiftL#`  6#) +#
1026                      (ord# (indexCharOffAddr# addr (nh +# 3#)) -# 0x80#))) :
1027           unpack (nh +# 4#)
1028       where
1029         !ch = indexCharOffAddr# addr nh
1030
1031 unpackNBytes# :: Addr# -> Int# -> [Char]
1032 unpackNBytes# _addr 0#   = []
1033 unpackNBytes#  addr len# = unpack [] (len# -# 1#)
1034     where
1035      unpack acc i#
1036       | i# <# 0#  = acc
1037       | otherwise = 
1038          case indexCharOffAddr# addr i# of
1039             ch -> unpack (C# ch : acc) (i# -# 1#)
1040
1041 {-# RULES
1042 "unpack"       [~1] forall a   . unpackCString# a             = build (unpackFoldrCString# a)
1043 "unpack-list"  [1]  forall a   . unpackFoldrCString# a (:) [] = unpackCString# a
1044 "unpack-append"     forall a n . unpackFoldrCString# a (:) n  = unpackAppendCString# a n
1045
1046 -- There's a built-in rule (in PrelRules.lhs) for
1047 --      unpackFoldr "foo" c (unpackFoldr "baz" c n)  =  unpackFoldr "foobaz" c n
1048
1049   #-}
1050 \end{code}
1051
1052 #ifdef __HADDOCK__
1053 \begin{code}
1054 -- | A special argument for the 'Control.Monad.ST.ST' type constructor,
1055 -- indexing a state embedded in the 'Prelude.IO' monad by
1056 -- 'Control.Monad.ST.stToIO'.
1057 data RealWorld
1058 \end{code}
1059 #endif