[Haskell-beginners] Too much mapM, fmap and concat
martin
martin.drautzburg at web.de
Wed Aug 13 16:21:46 UTC 2014
Hello all,
I never did much IO in haskell, but now I have to process some files. I catch myself adding a mapM here and an fmap
there. While it is clear to me what these functions do, I wonder if there is a way to avoid the noise. Also I could not
find a simple way to pair the lines of a file with its filename. I ended up writing a function "nameAndContent". Finally
I am amazed by the many "concat"s I need.
Maybe these things just lie in the nature of the problem ("process a number of files"). Otherwise any style suggestions
would be much appreciated.
import System.FilePath.Glob
import Data.List
filePattern="*.hs"
fileDirectory = "."
processFile :: (FilePath, [String]) -> [String]
processFile (path, flines) = ["done"]
main = do
matchingFiles <- fmap (concat . fst) $ globDir [compile filePattern] fileDirectory
flines <- mapM nameAndContent matchingFiles
result <- mapM (return . processFile) flines
mapM putStrLn $ concat result
where
nameAndContent :: FilePath -> IO (FilePath, [String])
nameAndContent fn = do
content <- fmap lines $ readFile fn
return (fn, content)
More information about the Beginners
mailing list