Skip to content

Commit

Permalink
Make asInt pure
Browse files Browse the repository at this point in the history
  • Loading branch information
mfussenegger committed Dec 16, 2018
1 parent 940165b commit 6b67df4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 15 deletions.
24 changes: 12 additions & 12 deletions src/Aeson.hs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ module Aeson (


import Data.Aeson (Value (..))
import Data.Maybe (fromJust)
import qualified Data.Scientific as S
import qualified Data.Text as T
import qualified Data.Text.Read as T
Expand All @@ -17,21 +16,22 @@ import qualified Data.Vector as V
-- | Try to extract an Int from Value
--
-- >>> asInt (Number 10)
-- 10
-- Right 10
--
-- >>> asInt (String "10")
-- 10
-- Right 10
--
-- >>> asInt (Number 10.38)
-- Left "Could not convert 10.38 to an Int"
--
-- >>> asInt (String "foo")
-- *** Exception: Expected an integer, but received: foo
-- ...
asInt :: Value -> Int
asInt (Number n) = fromJust $ S.toBoundedInteger n
asInt (String s) =
case T.decimal s of
(Right (n, _)) -> n
(Left _) -> error $ "Expected an integer, but received: " <> T.unpack s
asInt o = error $ "Expected an integer but received: " <> show o
-- Left "input does not start with a digit"
asInt :: Value -> Either String Int
asInt (Number n) = case S.toBoundedInteger n of
Nothing -> Left $ "Could not convert " <> show n <> " to an Int"
Just n' -> Right n'
asInt (String s) = fmap fst (T.decimal s)
asInt o = Left $ "Expected an integer but received: " <> show o


-- | Try to extract a Double from Value
Expand Down
6 changes: 3 additions & 3 deletions src/Fake.hs
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ uuid1 = do
-- Number 1.0
randomInt :: Expr -> Expr -> Fake Value
randomInt lower upper = do
lower' <- A.asInt <$> eval lower
upper' <- A.asInt <$> eval upper
lower' <- Except.liftEither =<< A.asInt <$> eval lower
upper' <- Except.liftEither =<< A.asInt <$> eval upper
Number . fromIntegral <$> State.state (randomR (lower', upper'))


Expand Down Expand Up @@ -151,7 +151,7 @@ oneOfArgs args = do
--
replicate :: Expr -> Expr -> Fake Value
replicate num expr = do
num' <- A.asInt <$> eval num
num' <- Except.liftEither =<< A.asInt <$> eval num
Array <$> V.replicateM num' (eval expr)


Expand Down

0 comments on commit 6b67df4

Please sign in to comment.