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