Haskell lazy I/O and closing files

前端 未结 7 845
攒了一身酷
攒了一身酷 2020-12-07 23:35

I\'ve written a small Haskell program to print the MD5 checksums of all files in the current directory (searched recursively). Basically a Haskell version of md5deep

7条回答
  •  春和景丽
    2020-12-07 23:43

    The problem is that mapM is not as lazy as you think - it results in a full list with one element per file path. And the file IO you are using is lazy, so you get a list with one open file per file path.

    The simplest solution in this case is to force the evaluation of the hash for each file path. One way to do that is with Control.Exception.evaluate:

    getFileLine path = do
      theHash <- liftM (\c -> (hex $ hash $ BS.unpack c) ++ " " ++ path) (BS.readFile path)
      evaluate theHash
    

    As others have pointed out, we're working on a replacement for the current approach to lazy IO that is more general yet still simple.

提交回复
热议问题