floating: Punt the FFI newtype wrappers.
[altfloat.git] / Data / Floating / Types.hs
blobd0274a78ac35afaf8bf4af5d4d3848261c9d9fe0
1 {-
2 - Copyright (C) 2009-2010 Nick Bowler.
4 - License BSD2: 2-clause BSD license. See LICENSE for full terms.
5 - This is free software: you are free to change and redistribute it.
6 - There is NO WARRANTY, to the extent permitted by law.
7 -}
9 -- | Definition of the core floating point types and basic manipulation of
10 -- them.
11 {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, OverlappingInstances #-}
12 {-# LANGUAGE MagicHash #-}
13 module Data.Floating.Types (
14 Double(..), Float(..), FloatConvert(..)
15 ) where
17 import Prelude hiding (Double, Float)
18 import qualified GHC.Exts as GHC
19 import GHC.Integer
20 import GHC.Prim
21 import Foreign.C
23 import Data.Ratio
25 import Unsafe.Coerce
27 -- | The Double type. This is expected to be an identical declaration to
28 -- the one found in GHC.Prim. We avoid simply using GHC's type because we need
29 -- to define our own class instances.
30 data Double = D# Double#
32 -- | The Float type.
33 data Float = F# Float#
35 -- | Coercion to floating point types.
36 class FloatConvert a b where
37 -- | Convert to a floating point type. Conversions from integers and real
38 -- types are provided, as well as conversions between floating point types.
39 -- Conversions between floating point types preserve infinities, negative
40 -- zeros and NaNs.
41 toFloating :: a -> b
43 instance FloatConvert Double CDouble where
44 toFloating = unsafeCoerce
46 instance FloatConvert CDouble Double where
47 toFloating = unsafeCoerce
49 instance FloatConvert Float CFloat where
50 toFloating = unsafeCoerce
52 instance FloatConvert CFloat Float where
53 toFloating = unsafeCoerce
55 instance FloatConvert Double Float where
56 toFloating (D# x) = F# (double2Float# x)
58 instance FloatConvert Float Double where
59 toFloating (F# x) = D# (float2Double# x)
61 instance FloatConvert Integer Double where
62 toFloating x = D# (doubleFromInteger x)
64 instance FloatConvert Integer Float where
65 toFloating x = F# (floatFromInteger x)
67 instance Real a => FloatConvert a Double where
68 toFloating x = D# (num /## denom) where
69 !(D# num) = toFloating . numerator . toRational $ x
70 !(D# denom) = toFloating . denominator . toRational $ x
72 instance Real a => FloatConvert a Float where
73 toFloating x = F# (divideFloat# num denom) where
74 !(F# num) = toFloating . numerator . toRational $ x
75 !(F# denom) = toFloating . denominator . toRational $ x
77 instance FloatConvert a a where
78 toFloating = id