on master help sign in
Make full-precision FromText for Float and Double
2931d2eJulian K. Arni
src/Servant/Common/Text.hs+3−3
@@ -6,12 +6,12 @@ module Servant.Common.Text
6 , ToText(..)
6 , ToText(..)
7 ) where
7 ) where
8
8
9+import Control.Applicative ((<$>))
9import Data.Int (Int16, Int32, Int64, Int8)
10import Data.Int (Int16, Int32, Int64, Int8)
10import Data.String.Conversions (cs)
11import Data.String.Conversions (cs)
11import Data.Text (Text)
12import Data.Text (Text)
12import Data.Text.Read (Reader, decimal, rational, signed)
13import Data.Text.Read (Reader, decimal, rational, signed)
13import Data.Word (Word, Word16, Word32, Word64, Word8)
14import Data.Word (Word, Word16, Word32, Word64, Word8)
14−import GHC.Float (double2Float)
15
15
16-- | For getting values from url captures and query string parameters
16-- | For getting values from url captures and query string parameters
17-- Instances should obey:
17-- Instances should obey:
@@ -125,7 +125,7 @@ instance ToText Integer where
125 toText = cs . show
125 toText = cs . show
126
126
127instance FromText Double where
127instance FromText Double where
128− fromText = runReader rational
128+ fromText x = fromRational <$> runReader rational x
129
129
130instance ToText Double where
130instance ToText Double where
131 toText = cs . show
131 toText = cs . show
@@ -133,7 +133,7 @@ instance ToText Double where
133instance FromText Float where
133instance FromText Float where
134 -- Double is more practically accurate due to weird rounding when using
134 -- Double is more practically accurate due to weird rounding when using
135 -- rational. We convert to double and then convert to Float.
135 -- rational. We convert to double and then convert to Float.
136− fromText = fmap double2Float . runReader rational
136+ fromText x = fromRational <$> runReader rational x
137
137
138instance ToText Float where
138instance ToText Float where
139 toText = cs . show
139 toText = cs . show
test/Servant/Common/TextSpec.hs+2−6
@@ -60,14 +60,10 @@ spec = describe "Servant.Common.Text" $ do
60 --
60 --
61 -- http://en.wikipedia.org/wiki/Floating_point#Internal_representation
61 -- http://en.wikipedia.org/wiki/Floating_point#Internal_representation
62 it "holds for Double" $
62 it "holds for Double" $
63− property $ \x ->
64− x < 1.0e15 && x > 1.0e-15 ==>
65− textLaw (x :: Double)
63+ property $ \x -> textLaw (x :: Double)
66
64
67 it "holds for Float" $
65 it "holds for Float" $
68− property $ \x ->
69− x < 1.0e7 && x > 1.0e-7 ==>
70− textLaw (x :: Float)
66+ property $ \x -> textLaw (x :: Float)
71
67
72textLaw :: (FromText a, ToText a, Eq a) => a -> Bool
68textLaw :: (FromText a, ToText a, Eq a) => a -> Bool
73textLaw a = fromText (toText a) == Just a
69textLaw a = fromText (toText a) == Just a