Ryo*_*Ryo 7 haskell scientific-notation
Haskell read
对浮点数有点过于严格:
$ ghci
GHCi, version 8.2.2: http://www.haskell.org/ghc/ :? for help
Prelude> read "-1E34" :: Double
-1.0e34
Prelude> read "-1.E34" :: Double
*** Exception: Prelude.read: no parse
Prelude>
Run Code Online (Sandbox Code Playgroud)
是否有接受第二种形式的读取版本?它在物理科学中很常见.例如,Fortran读取和写入此类表单.
Haskell不支持的另一个例子是"0.1"表示"0.1".这个更为常见.我只是不想转换输入ascii文件....
正如有人所说,您可以创建一个(或三个)辅助函数来帮助将数字转换为适用于read
. 我不是最擅长 Haskell,所以我不确定是否存在其他解决方案,但我编写了一些函数来提供帮助。我已经用 进行了测试read
,到目前为止一切似乎都工作正常。
prefixZero :: String -> String
prefixZero "" = ""
prefixZero ('-' : xs) = '-' : '0' : xs
prefixZero s = '0' : s
suffixZero :: String -> String
suffixZero "" = ""
suffixZero ('.' : exp@('E' : _)) = '.' : '0' : exp
suffixZero (x : xs) = x : suffixZero xs
format :: String -> String
format = suffixZero . prefixZero
Run Code Online (Sandbox Code Playgroud)
您可以拨打以下电话:
read (format "-1.E34") :: Double
Run Code Online (Sandbox Code Playgroud)
其输出如下:
-1.0e34
Run Code Online (Sandbox Code Playgroud)