Last active
December 6, 2019 14:18
-
-
Save yasar11732/186e511186d928f182433216192a1650 to your computer and use it in GitHub Desktop.
Haskell Walk Directory Recursively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import System.Directory | |
| import System.FilePath | |
| import Control.Monad | |
| import Control.Exception | |
| import GHC.IO.Encoding | |
| -- Gets a root directory and a callback, | |
| -- calls callback for root directory and every subdirectory recursively | |
| -- callback signature root -> files -> dirs -> IO () | |
| walkDirectory :: String -> (String -> [String] -> [String] -> IO ()) -> IO () | |
| walkDirectory rootDir callback = do | |
| putStrLn $ "Processing " ++ rootDir | |
| contents <- catch (listDirectory rootDir) (\e -> do | |
| putStrLn $ show (e :: IOException) | |
| return [] | |
| ) | |
| let fullPaths = map (rootDir </>) contents | |
| files <- filterM doesFileExist fullPaths | |
| dirs <- filterM doesDirectoryExist fullPaths | |
| callback rootDir files dirs | |
| mapM_ (flip walkDirectory callback) dirs | |
| main = do | |
| setLocaleEncoding utf8 | |
| walkDirectory "." $ \root files dirs -> do | |
| let txtFiles = filter (\fileName -> takeExtension fileName == ".txt") files | |
| let numtxtFiles = length txtFiles | |
| if numtxtFiles > 3 then | |
| putStrLn $ root ++ ":" ++ show numtxtFiles | |
| else | |
| return () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment