Skip to content

Commit

Permalink
Add support for double literals
Browse files Browse the repository at this point in the history
  • Loading branch information
mfussenegger committed Dec 9, 2018
1 parent 007365f commit 702b550
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
21 changes: 19 additions & 2 deletions src/Expr.hs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import Text.Parsec.Text (Parser)
-- >>> :set -XOverloadedStrings

data Expr = IntLiteral Integer
| DoubleLiteral Double
| StringLiteral Text
| FunctionCall { fcName :: Text, fcArgs :: [Expr] }
deriving (Show, Eq)
Expand All @@ -27,14 +28,28 @@ instance IsString Expr where
(Left err) -> error $ show err
(Right e) -> e


expr :: Parser Expr
expr = literal <|> functionCall


literal :: Parser Expr
literal = number <|> stringLiteral


number :: Parser Expr
number = IntLiteral . read <$> many1 digit
number = do
integer <- many1 digit
optionalDot <- optionMaybe (char '.')
case optionalDot of
Nothing -> pure $ IntLiteral (read integer)
(Just _) -> do
fractional <- many digit
let
value :: Double
value = read $ integer <> "." <> fractional
pure $ DoubleLiteral value


stringLiteral :: Parser Expr
stringLiteral = do
Expand Down Expand Up @@ -64,12 +79,14 @@ ident = do
pure $ T.pack (firstChar : next)



-- | Parse an expression
--
-- >>> parseExpr "20"
-- Right (IntLiteral 20)
--
-- >>> parseExpr "20.3"
-- Right (DoubleLiteral 20.3)
--
-- >>> parseExpr "uuid4"
-- Right (FunctionCall {fcName = "uuid4", fcArgs = []})
--
Expand Down
5 changes: 3 additions & 2 deletions src/Fake.hs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ randomInt lower upper = do

-- | Generate a random double
--
-- >>> exec "randomDouble(1, 3)"
-- Number 1.1555807501666868
-- >>> exec "randomDouble(1.5, 3)"
-- Number 1.6166855626250152
randomDouble :: Expr -> Expr -> State Value
randomDouble lower upper = do
lower' <- A.asDouble <$> eval lower
Expand Down Expand Up @@ -162,6 +162,7 @@ fromFile fileName = do
eval :: Expr -> State Value
eval (IntLiteral x) = pure $ Number $ fromInteger x
eval (StringLiteral x) = pure $ String x
eval (DoubleLiteral x) = pure $ Number $ S.fromFloatDigits x
eval (FunctionCall "uuid4" []) = String . UUID.toText <$> withStdGen random
eval (FunctionCall "uuid1" []) = String . UUID.toText <$> uuid1
eval (FunctionCall "randomInt" [lower, upper]) = randomInt lower upper
Expand Down

0 comments on commit 702b550

Please sign in to comment.