19586edc9011a72c25d477c3915f673f2a154a42
[ghc-hetmet.git] / ghc / lib / exts / NumExts.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4
5 \section[NumExts]{Misc numeric bits}
6
7 \begin{code}
8 module NumExts
9        (
10          doubleToFloat   -- :: Double -> Float
11        , floatToDouble   -- :: Double -> Float
12        , showHex         -- :: Integral a => a -> ShowS
13        , showOct         -- :: Integral a => a -> ShowS
14        , showIntAtBase   -- :: Integral a => a -> (a -> Char) -> a -> ShowS
15        ) where
16
17 import Char (ord, chr)
18 import PrelBase (ord_0)
19 import GlaExts
20 \end{code}
21
22 \begin{code}
23 doubleToFloat :: Double -> Float
24 doubleToFloat (D# d#) = F# (double2Float# d#)
25
26 floatToDouble :: Float -> Double
27 floatToDouble (F# f#) = D# (float2Double# f#)
28
29 showIntAtBase :: Integral a => a -> (a -> Char) -> a -> ShowS
30 showIntAtBase base toChr n r
31   | n < 0  = error ("NumExts.showIntAtBase: applied to negative number " ++ show n)
32   | otherwise = 
33     case quotRem n base of { (n', d) ->
34     case toChr d        of { C# c# -> -- stricter than necessary
35     let
36         r' = C# c# : r
37     in
38     if n' == 0 then r' else showIntAtBase base toChr n' r'
39     }}
40
41 showHex :: Integral a => a -> ShowS
42 showHex n r = 
43  showString "0x" $
44  showIntAtBase 16 (toChrHex) n r
45  where  
46   toChrHex d
47     | d < 10    = chr (ord_0   + fromIntegral d)
48     | otherwise = chr (ord 'a' + fromIntegral (d - 10))
49
50 showOct :: Integral a => a -> ShowS
51 showOct n r = 
52  showString "0o" $
53  showIntAtBase 8 (toChrOct) n r
54  where toChrOct d = chr (ord_0   + fromIntegral d)
55 \end{code}