读取以十进制形式写的整数非常简单:
Prelude> read "1000000000" :: Int
1000000000
但是如何读取以exponetial形式写的整数?
Prelude> read "10e+9" :: Int
*** Exception: Prelude.read: no parse
Prelude
中是否有函数可以执行此操作,还是需要解析表达式?
感谢您的回复。
答案 0 :(得分:3)
这是一个解析器
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
我们可以尝试使它能够处理给出整数答案的负指数,但这对于读函数来说是过度的。
答案 1 :(得分:2)
根据字符串的确切格式,您可以read
将其转换为浮点类型:
> read "10e+9" :: Double
1.0e10
then convert to an integral type - 我建议使用Integer
代替Int
:
> floor (read "10e+9" :: Double) :: Integer
10000000000