Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Haskell unable to read "7e7" but able to read "7a7"?

Tags:

string

haskell

Try to do:

Prelude> reads "7a7" :: [(Int, String)]
[(7,"a7")]

Prelude> reads "7e7" :: [(Int, String)]
[]

I tested this for all possible characters in the middle. They all work except for 'e'. It seems as if Haskell tries to interpret the number in scientific notation, but it can't because I'm asking for Int.

It seems like a bug to me.

like image 654
romeovs Avatar asked Mar 27 '14 13:03

romeovs


2 Answers

GHC is indeed buggy. Its implementation of Numeric.readSigned uses the following:

read'' r = do
    (str,s) <- lex r
    (n,"")  <- readPos str
    return (n,s)

The lex call will try to parse any lexeme, and this means that for "7e7" it yields [("7e7", "")], because "7e7" is a whole lexeme for a floating point literal. Then it tries to get a complete parse out of readPos, which in this case is an argument for which Numeric.readDec was passed in, and readDec will yield, correctly, [(7, "e7")] for the string "7e7". That fails pattern matching against (n, ""), and ends up as [].

I think it should be simply as follows:

read'' = readPos
like image 71
R. Martinho Fernandes Avatar answered Sep 24 '22 10:09

R. Martinho Fernandes


7e7 :: Fractional a => a so it can't be read as an Int, but it can be read as a Float or Double.

ghci> :t 7e7
7e7 :: Fractional a => a
like image 22
David Young Avatar answered Sep 23 '22 10:09

David Young