Advertisement
Guest User

Haskell lazy I/O and closing files.

a guest
Jun 5th, 2010
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Control.Monad
  2. import Data.Digest.MD5 (hash)
  3. import Data.Word
  4. import List (sort)
  5. import Prelude
  6. import System.Directory
  7. import System.FilePath
  8. import Text.Printf (printf)
  9. import qualified Data.ByteString.Lazy as BS
  10.  
  11. main :: IO ()
  12.  
  13. main = putStr . unlines =<< getList "."
  14.  
  15. getList :: FilePath -> IO [String]
  16.  
  17. getList p =
  18.     let getFileLine path = liftM (\c -> (hex $ hash $ BS.unpack c) ++ " " ++ path) (BS.readFile path)
  19.     in mapM getFileLine =<< getRecursiveContents p
  20.  
  21. hex :: [Word8] -> String
  22.  
  23. hex = concatMap (\x -> printf "%0.2x" (toInteger x))
  24.  
  25. getRecursiveContents :: FilePath -> IO [FilePath]
  26.  
  27. getRecursiveContents topdir = do
  28.     names <- getDirectoryContents topdir
  29.  
  30.     let properNames = filter (`notElem` [".", ".."]) names
  31.  
  32.     paths <- concatForM properNames $ \name -> do
  33.         let path = topdir </> name
  34.  
  35.         isDirectory <- doesDirectoryExist path
  36.         if isDirectory
  37.             then getRecursiveContents path
  38.             else do
  39.                 isFile <- doesFileExist path
  40.                 if isFile
  41.                     then return [path]
  42.                     else return []
  43.  
  44.     return (sort paths)
  45.  
  46. concatForM :: (Monad m) => [a1] -> (a1 -> m [a]) -> m [a]
  47.  
  48. concatForM xs f = liftM concat (forM xs f)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement