jpa*_*ich 2 haskell bytestring
我是Haskell的新手,试图摆弄一些我在现实世界中经常遇到的测试用例.假设我有文本文件"foo.txt",其中包含以下内容:
45.4 34.3 377.8
33.2 98.4 456.7
99.1 44.2 395.3
Run Code Online (Sandbox Code Playgroud)
我正在尝试生成输出
[[45.4,34.3,377.8],[33.2,98.4,456.7],[99.1,44.2,395.3]]
Run Code Online (Sandbox Code Playgroud)
我的代码在下面,但我在输出中得到一些虚假的"LPS"......不确定它代表什么.
import qualified Data.ByteString.Lazy.Char8 as BStr
import qualified Data.Map as Map
readDatafile = (map (BStr.words) . BStr.lines)
testFunc path = do
contents <- BStr.readFile path
print (readDatafile contents)
Run Code Online (Sandbox Code Playgroud)
当使用testFunc"foo.txt"调用时,输出为
[[LPS ["45.4"],LPS ["34.3"],LPS ["377.8"]],[LPS ["33.2"],LPS ["98.4"],LPS ["456.7"]],[LPS ["99.1"],LPS ["44.2"],LPS ["395.3"]]]
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏!谢谢.PS:使用ByteString,因为这将在未来用于大量文件.
编辑:
我也很困惑为什么输出列表如上所述(每个数字都绑定在[])中,当在ghci中时,下面的行给出了不同的排列.
*Main> (map words . lines) "45.4 34.3 377.8\n33.2 98.4 456.7\n99.1 44.2 395.3"
[["45.4","34.3","377.8"],["33.2","98.4","456.7"],["99.1","44.2","395.3"]]
Run Code Online (Sandbox Code Playgroud)
你所看到的确实是一个构造函数.当您读取文件时,结果当然是Bytestrings列表的列表,但您想要的是Floats列表的列表.
你能做什么:
readDatafile :: BStr.ByteString -> [[Float]]
readDatafile = (map ((map (read . BStr.unpack)) . BStr.words)) . BStr.lines
Run Code Online (Sandbox Code Playgroud)
这会解压缩Bytestring(即将其转换为字符串).read将字符串转换为float.
不确定在这里使用字节串是否有助于提高性能.