parser icon indicating copy to clipboard operation
parser copied to clipboard

Float parser comitting to leading 'e'

Open j-maas opened this issue 5 years ago • 3 comments

Similar to #28, the float parser comitts when it encounters an 'e', making it impossible to have a parser that reads either a float or some text:

floatOrText =
    oneOf
        [ float |> map (\n -> "Number: " ++ String.fromFloat n)
        , chompUntilEndOr "\n" |> getChompedString
    ]

run floatOrText "not starting with e" --> Ok "not starting with e"
run floatOrText "1e10" --> Ok "Number: 10000000000"
run floatOrText "e should be text" --> Err: ExpectingFloat

(Try it on Ellie: https://ellie-app.com/8yp6MxtzSsna1)

j-maas avatar Apr 14 '20 09:04 j-maas

As a workaround, one can define their own float parser:

{-| The built-in float parser has a bug with leading 'e'.
See <https://github.com/elm/parser/issues/44>
-}
parseFloat : Parser Float
parseFloat =
    {- By making it backtrackable, even if the input start with an 'e',
       we will be able to try out other alternatives instead of getting
       stuck on it as an invalid number.
    -}
    Parser.backtrackable <| Parser.float ExpectingFloat InvalidNumber

j-maas avatar May 05 '20 10:05 j-maas

int parser has the same problem of committing the leading 'e'

AlienKevin avatar May 20 '20 20:05 AlienKevin

I ran in to this same problem:

term : Parser Expr
term =
  P.oneOf
    [ P.succeed Number
        |= number
    , P.succeed EParam
        |= param
    ]

Given,

Parser.run term "E"

it returns

Err [{ col = 2, problem = ExpectingInt, row = 1 }]

instead of

Ok (EParam "E")

dwayne avatar May 04 '22 01:05 dwayne