read "10e-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:06:19 26 4
gpt4 key购买 nike

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

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

我们可以尝试让它处理给出整数答案的负指数,但这对于读取函数来说太过分了。

关于haskell - 如何使用 Haskell 读取以指数形式写入的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com