3
import qualified Data.HashMap.Strict as M
import qualified Data.Text as T
import qualified Data.Text.IO as T.IO
import Text.FShow.RealFloat (fshow)

main = do  
  dataA <- T.IO.readFile "pathA"
  dataB <- T.IO.readFile "pathB"
  ...
  let hashmap = -- process dataA and dataB
      hashmapList = map (\(t1,t1Map) -> (t1, map (\(t2,float) -> (t2,fshow float)) (M.toList t1Map))) $ M.toList hashmap
      hashmapString = show hashmapList
  writeFile "path" hashmapString 

I would like to write hashmap (see the code above), which is of type M.HashMap T.Text (M.HashMap T.Text Float), to a file. I turn hashmap into a List and besides use fshow to show Floats efficiently. Using showI then turn the List into a String and write it to a file.

Compiling with -O2 and profiling yields:

COST CENTRE          MODULE                %time %alloc

main.hashmapList.\.\ Main                   46.0   50.0
main.hashmapString   Main                   32.5   41.1
main.writeFile       Main                   11.9    0.2
main.hashmapList.\   Main                    3.4    2.7
...

So especially turning the Map into a List and turning the List into a String takes a lot of time and space. How can hashmap be written to a file more efficiently?

4

1 回答 1

1

还不如正确回答这个问题。如果您有一个打开的文件句柄和一个将单个条目写入此文件的 IO 操作,那么您可以使用mapM_fromData.Foldable并在整个结构上运行该操作以将其运行到该文件中。如果你也需要钥匙,那么类似的东西traverseWithKey就是你的朋友。

于 2015-02-22T19:14:40.630 回答