Skip to content

Instantly share code, notes, and snippets.

@yasar11732
Last active December 6, 2019 14:18
Show Gist options
  • Select an option

  • Save yasar11732/186e511186d928f182433216192a1650 to your computer and use it in GitHub Desktop.

Select an option

Save yasar11732/186e511186d928f182433216192a1650 to your computer and use it in GitHub Desktop.
Haskell Walk Directory Recursively
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