From 087b3f4f1240d6a651ac7514bde3ca10f99ace75 Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Sun, 16 Dec 2018 16:55:40 +0100 Subject: [PATCH] Make asDouble return an Either --- src/Aeson.hs | 17 ++++++++--------- src/Fake.hs | 7 ++++--- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Aeson.hs b/src/Aeson.hs index 3c601c8..1301bf3 100644 --- a/src/Aeson.hs +++ b/src/Aeson.hs @@ -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 diff --git a/src/Fake.hs b/src/Fake.hs index 9079e78..6beaa4c 100644 --- a/src/Fake.hs +++ b/src/Fake.hs @@ -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) @@ -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 @@ -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'))