如何读取使用Haskell以指数形式编写的整数?

时间:2012-11-26 15:02:48

标签: haskell ghci

读取以十进制形式写的整数非常简单:

Prelude> read "1000000000" :: Int
1000000000

但是如何读取以exponetial形式写的整数?

Prelude> read "10e+9" :: Int
*** Exception: Prelude.read: no parse

Prelude中是否有函数可以执行此操作,还是需要解析表达式?

感谢您的回复。

2 个答案:

答案 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