Skip to content

Commit

Permalink
Make asDouble return an Either
Browse files Browse the repository at this point in the history
  • Loading branch information
mfussenegger committed Dec 16, 2018
1 parent b4a877d commit 087b3f4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
17 changes: 8 additions & 9 deletions src/Aeson.hs
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,20 @@ asInt o = error $ "Expected an integer but received: " <> show o
-- | Try to extract a Double from Value
--
-- >>> asDouble (Number 10.3)
-- 10.3
-- Right 10.3
--
-- >>> asDouble (String "10.5")
-- 10.5
-- Right 10.5
--
-- >>> asDouble (String "foo")
-- *** Exception: Expected a double, but received: foo
-- ...
asDouble :: Value -> Double
asDouble (Number n) = S.toRealFloat n
-- Left "Expected a double, but received: foo"
asDouble :: Value -> Either String Double
asDouble (Number n) = Right $ S.toRealFloat n
asDouble (String s) =
case T.double s of
(Right (n, _)) -> n
(Left _) -> error $ "Expected a double, but received: " <> T.unpack s
asDouble o = error $ "Expected a double, but received: " <> show o
(Right (n, _)) -> Right n
(Left _) -> Left $ "Expected a double, but received: " <> T.unpack s
asDouble o = Left $ "Expected a double, but received: " <> show o


asArray :: Value -> V.Vector Value
Expand Down
7 changes: 4 additions & 3 deletions src/Fake.hs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ module Fake (

import qualified Aeson as A
import Control.Monad (forM, replicateM)
import Control.Monad.Except (ExceptT)
import Control.Monad.Except (ExceptT, MonadError)
import qualified Control.Monad.Except as Except
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.State.Class (MonadState)
Expand Down Expand Up @@ -48,6 +48,7 @@ newtype Fake a = Fake { runFake :: ExceptT String (StateT Env IO) a }
, Monad
, MonadState Env
, MonadIO
, MonadError String
)

runFakeT :: Maybe Int -> Fake a -> IO a
Expand Down Expand Up @@ -102,8 +103,8 @@ randomInt lower upper = do
-- Number 1.500000257527587
randomDouble :: Expr -> Expr -> Fake Value
randomDouble lower upper = do
lower' <- A.asDouble <$> eval lower
upper' <- A.asDouble <$> eval upper
lower' <- Except.liftEither =<< A.asDouble <$> eval lower
upper' <- Except.liftEither =<< A.asDouble <$> eval upper
Number . S.fromFloatDigits <$> State.state (randomR (lower', upper'))


Expand Down

0 comments on commit 087b3f4

Please sign in to comment.