读取以十进制形式写入的整数非常简单:
Prelude> read "1000000000" :: Int
1000000000
但是如何读取以指数形式写的整数呢?
Prelude> read "10e+9" :: Int
*** Exception: Prelude.read: no parse
中是否有一个函数Prelude
可以做到这一点,还是我们需要解析表达式?
感谢您的回复。
这是一个解析器
readI xs = let (m,e) = break (=='e') xs in
read m * 10 ^ case e of
"" -> 1
('e':'+':p) -> read p
('e':p) -> read p
给予
Main> readI "3e5"
300000
Main> readI "3e+500"
300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Main> readI "3e+500" :: Int
0
Main> readI "3e+500" :: Integer
300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
并且
Main> readI "32e-5"
Program error: Prelude.^: negative exponent
我们可以尝试让它处理给出整数答案的负指数,但这对于读取函数来说太过分了。
根据字符串的确切格式,您可以将read
其转换为浮点类型:
> read "10e+9" :: Double
1.0e10
然后转换为整数类型——我建议Integer
不要Int
:
> floor (read "10e+9" :: Double) :: Integer
10000000000