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

Parsing hexadecimal floats #554

Open
gabrielsimoes opened this issue Feb 24, 2024 · 1 comment
Open

Parsing hexadecimal floats #554

gabrielsimoes opened this issue Feb 24, 2024 · 1 comment

Comments

@gabrielsimoes
Copy link

gabrielsimoes commented Feb 24, 2024

It seems the parsing utilities in Text.Megaparsec.Char.Lexer do not support parsing hexadecimal floats out of the box:

0x0.1E
0xA23p-4
0X1.921FB54442D18P

Given how complex these are to parse efficiently and correctly, it seems like it would be a worthy addition to megaparsec.

Let me know if I am missing something obvious and there is an easy way to use the existing functions to parse these.

@gabrielsimoes
Copy link
Author

gabrielsimoes commented Feb 25, 2024

This is what I ended up going with using FloatingHex:

hexfloat = do
  zerox <- try $ char '0' >> char' 'x' <&> \x -> "0" ++ [x]
  whole <- hexdigits
  frac <- option "" $ liftA2 (:) (char '.') hexdigits
  exp <- option "p0" $ do
    p <- char' 'p'
    sign <- optional $ satisfy (\c -> c == '+' || c == '-')
    val <- digits
    return $ [p] ++ maybe "" (:[]) sign ++ val
  let literal = concat [zerox, whole, frac, exp]
  case readHFloat literal of
    Nothing -> unexpected $ Tokens $ fromList literal
    Just f -> return f
digits = T.unpack <$> takeWhile1P (Just "digit") isDigit
hexdigits = T.unpack <$> takeWhile1P (Just "hex digit") isHexDigit

Definitely not the cleanest/most performant, documenting for others who might need it or might be able to suggest improvements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants