Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow starting a number with a decimal point #296

Merged
merged 1 commit into from
May 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions src/Insect/Parser.purs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ whiteSpace = token.whiteSpace
-- | Parse a number.
number P Decimal
number = do
intPartdigits

mFracPart ← optionMaybe (append <$> string "." <*> digits)
let fracPart = fromMaybe "" mFracPart
decimalPartfractionalPart <|> do
Copy link
Contributor Author

@triallax triallax May 13, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestions on how to better implement this are welcome.

intPart ← digits
mFracPart ← optionMaybe fractionalPart
pure (intPart <> fromMaybe "" mFracPart)

mExpPart ← optionMaybe $ try do
_ ← string "e"
Expand All @@ -103,7 +103,7 @@ number = do

whiteSpace

let floatStr = intPart <> fracPart <> expPart
let floatStr = decimalPart <> expPart

case fromString floatStr of
Just num →
Expand All @@ -118,6 +118,9 @@ number = do
ds ← some $ oneOf ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] <?> "a digit"
pure $ fromCharArray (fromFoldable ds)

fractionalPart P String
fractionalPart = (<>) <$> string "." <*> digits

fromCharArray = fromCodePointArray <<< map codePointFromChar

signAndDigits P String
Expand Down
19 changes: 18 additions & 1 deletion test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,28 @@ main = runTest do
, "+3.50"
]

allParseAs (Expression (scalar 0.2))
[ "0.2"
, " 0.2 "
, "+0.2 "
, ".2"
, "+.2"
]

allParseAs (Expression (Negate (scalar 0.61)))
[ "-0.61"
, "-.61"
, "- .61"
]

shouldParseAs (Expression (scalar 0.05)) ".05"

shouldFail "123.."
shouldFail "0.."
shouldFail ".0."
shouldFail "."
shouldFail ".2"
shouldFail ". 2"
shouldFail "..2"

test "Large numbers" do
allParseAs (Expression (scalar 1234567890000000.0))
Expand Down