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