Skip to content

Commit

Permalink
Use traverse instead of mapM all over the place
Browse files Browse the repository at this point in the history
  • Loading branch information
phadej committed Jul 26, 2016
1 parent bea19f6 commit b90bd03
Show file tree
Hide file tree
Showing 27 changed files with 89 additions and 87 deletions.
21 changes: 11 additions & 10 deletions Cabal/Distribution/Compat/Binary/Class.hs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ import Foreign
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as L

import Data.Char (chr,ord)
import Data.List (unfoldr)
import Data.Char (chr,ord)
import Data.List (unfoldr)
import Data.Foldable (traverse_)

-- And needed for the instances:
import qualified Data.ByteString as B
Expand Down Expand Up @@ -389,7 +390,7 @@ instance (Binary a, Binary b, Binary c, Binary d, Binary e,
-- Container types

instance Binary a => Binary [a] where
put l = put (length l) >> mapM_ put l
put l = put (length l) >> traverse_ put l
get = do n <- get :: Get Int
getMany n

Expand Down Expand Up @@ -444,26 +445,26 @@ instance Binary ByteString where
-- Maps and Sets

instance (Binary a) => Binary (Set.Set a) where
put s = put (Set.size s) >> mapM_ put (Set.toAscList s)
put s = put (Set.size s) >> traverse_ put (Set.toAscList s)
get = liftM Set.fromDistinctAscList get

instance (Binary k, Binary e) => Binary (Map.Map k e) where
put m = put (Map.size m) >> mapM_ put (Map.toAscList m)
put m = put (Map.size m) >> traverse_ put (Map.toAscList m)
get = liftM Map.fromDistinctAscList get

instance Binary IntSet.IntSet where
put s = put (IntSet.size s) >> mapM_ put (IntSet.toAscList s)
put s = put (IntSet.size s) >> traverse_ put (IntSet.toAscList s)
get = liftM IntSet.fromDistinctAscList get

instance (Binary e) => Binary (IntMap.IntMap e) where
put m = put (IntMap.size m) >> mapM_ put (IntMap.toAscList m)
put m = put (IntMap.size m) >> traverse_ put (IntMap.toAscList m)
get = liftM IntMap.fromDistinctAscList get

------------------------------------------------------------------------
-- Queues and Sequences

instance (Binary e) => Binary (Seq.Seq e) where
put s = put (Seq.length s) >> Fold.mapM_ put s
put s = put (Seq.length s) >> Fold.traverse_ put s
get = do n <- get :: Get Int
rep Seq.empty n get
where rep xs 0 _ = return $! xs
Expand Down Expand Up @@ -496,7 +497,7 @@ instance (Binary i, Ix i, Binary e) => Binary (Array i e) where
put a = do
put (bounds a)
put (rangeSize $ bounds a) -- write the length
mapM_ put (elems a) -- now the elems.
traverse_ put (elems a) -- now the elems.
get = do
bs <- get
n <- get -- read the length
Expand All @@ -510,7 +511,7 @@ instance (Binary i, Ix i, Binary e, IArray UArray e) => Binary (UArray i e) wher
put a = do
put (bounds a)
put (rangeSize $ bounds a) -- now write the length
mapM_ put (elems a)
traverse_ put (elems a)
get = do
bs <- get
n <- get
Expand Down
4 changes: 2 additions & 2 deletions Cabal/Distribution/Compat/Graph.hs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ revNeighbors g k = do
-- Requires amortized construction of graph.
closure :: Graph a -> [Key a] -> Maybe [a]
closure g ks = do
vs <- mapM (graphKeyToVertex g) ks
vs <- traverse (graphKeyToVertex g) ks
return (decodeVertexForest g (G.dfs (graphForward g) vs))

-- | Compute the reverse closure of a graph from some set
Expand All @@ -302,7 +302,7 @@ closure g ks = do
-- Requires amortized construction of graph.
revClosure :: Graph a -> [Key a] -> Maybe [a]
revClosure g ks = do
vs <- mapM (graphKeyToVertex g) ks
vs <- traverse (graphKeyToVertex g) ks
return (decodeVertexForest g (G.dfs (graphAdjoint g) vs))

flattenForest :: Tree.Forest a -> [a]
Expand Down
1 change: 1 addition & 0 deletions Cabal/Distribution/PackageDescription/Check.hs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import Distribution.Text
import Distribution.Simple.LocalBuildInfo hiding (compiler)
import Language.Haskell.Extension

import Control.Monad (mapM)
import Data.List (group)
import qualified System.Directory as System
( doesFileExist, doesDirectoryExist )
Expand Down
24 changes: 12 additions & 12 deletions Cabal/Distribution/PackageDescription/Parse.hs
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ readAndParseFile withFileContents' parser verbosity fpath = do
let (line, message) = locatedErrorMsg e
dieWithLocation fpath line message
ParseOk warnings x -> do
mapM_ (warn verbosity . showPWarning fpath) $ reverse warnings
traverse_ (warn verbosity . showPWarning fpath) $ reverse warnings
return x

readHookedBuildInfo :: Verbosity -> FilePath -> IO HookedBuildInfo
Expand All @@ -561,15 +561,15 @@ isStanzaHeader _ = False

mapSimpleFields :: (Field -> ParseResult Field) -> [Field]
-> ParseResult [Field]
mapSimpleFields f = mapM walk
mapSimpleFields f = traverse walk
where
walk fld@F{} = f fld
walk (IfBlock l c fs1 fs2) = do
fs1' <- mapM walk fs1
fs2' <- mapM walk fs2
fs1' <- traverse walk fs1
fs2' <- traverse walk fs2
return (IfBlock l c fs1' fs2')
walk (Section ln n l fs1) = do
fs1' <- mapM walk fs1
fs1' <- traverse walk fs1
return (Section ln n l fs1')

-- prop_isMapM fs = mapSimpleFields return fs == return fs
Expand Down Expand Up @@ -1053,7 +1053,7 @@ parsePackageDescription file = do
condFlds = [ f | f@IfBlock{} <- allflds ]
sections = [ s | s@Section{} <- allflds ]

mapM_
traverse_
(\(Section l n _ _) -> lift . warning $
"Unexpected section '" ++ n ++ "' on line " ++ show l)
sections
Expand All @@ -1073,11 +1073,11 @@ parsePackageDescription file = do
-- to check the CondTree, rather than grovel everywhere
-- inside the conditional bits).
deps <- liftM concat
. mapM (lift . parseConstraint)
. traverse (lift . parseConstraint)
. filter isConstraint
$ simplFlds

ifs <- mapM processIfs condFlds
ifs <- traverse processIfs condFlds

return (CondNode a deps ifs)
where
Expand Down Expand Up @@ -1123,10 +1123,10 @@ parsePackageDescription file = do
PM ()
checkForUndefinedFlags flags mlib sub_libs exes tests = do
let definedFlags = map flagName flags
mapM_ (checkCondTreeFlags definedFlags) (maybeToList mlib)
mapM_ (checkCondTreeFlags definedFlags . snd) sub_libs
mapM_ (checkCondTreeFlags definedFlags . snd) exes
mapM_ (checkCondTreeFlags definedFlags . snd) tests
traverse_ (checkCondTreeFlags definedFlags) (maybeToList mlib)
traverse_ (checkCondTreeFlags definedFlags . snd) sub_libs
traverse_ (checkCondTreeFlags definedFlags . snd) exes
traverse_ (checkCondTreeFlags definedFlags . snd) tests

checkCondTreeFlags :: [FlagName] -> CondTree ConfVar c a -> PM ()
checkCondTreeFlags definedFlags ct = do
Expand Down
6 changes: 3 additions & 3 deletions Cabal/Distribution/ParseUtils.hs
Original file line number Diff line number Diff line change
Expand Up @@ -387,14 +387,14 @@ fName _ = error "fname: not a field or section"

readFields :: String -> ParseResult [Field]
readFields input = ifelse
=<< mapM (mkField 0)
=<< traverse (mkField 0)
=<< mkTree tokens

where ls = (lines . normaliseLineEndings) input
tokens = (concatMap tokeniseLine . trimLines) ls

readFieldsFlat :: String -> ParseResult [Field]
readFieldsFlat input = mapM (mkField 0)
readFieldsFlat input = traverse (mkField 0)
=<< mkTree tokens
where ls = (lines . normaliseLineEndings) input
tokens = (concatMap tokeniseLineFlat . trimLines) ls
Expand Down Expand Up @@ -568,7 +568,7 @@ mkField d (Node (n,_,l) ts) = case span (\c -> isAlphaNum c || c == '-') l of
then tabsError n
else return $ F n (map toLower name)
(fieldValue rest' followingLines)
rest' -> do ts' <- mapM (mkField (d+1)) ts
rest' -> do ts' <- traverse (mkField (d+1)) ts
return (Section n (map toLower name) rest' ts')
where fieldValue firstLine followingLines =
let firstLine' = trimLeading firstLine
Expand Down
2 changes: 1 addition & 1 deletion Cabal/Distribution/Simple.hs
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ clean pkg_descr flags = do
when exists (removeDirectoryRecursive distPref)

-- Any extra files the user wants to remove
mapM_ removeFileOrDirectory (extraTmpFiles pkg_descr)
traverse_ removeFileOrDirectory (extraTmpFiles pkg_descr)

-- If the user wanted to save the config, write it back
traverse_ (writePersistBuildConfig distPref) maybeConfig
Expand Down
2 changes: 1 addition & 1 deletion Cabal/Distribution/Simple/Bench.hs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ bench args pkg_descr lbi flags = do

let totalBenchmarks = length bmsToRun
notice verbosity $ "Running " ++ show totalBenchmarks ++ " benchmarks..."
exitcodes <- mapM doBench bmsToRun
exitcodes <- traverse doBench bmsToRun
let allOk = totalBenchmarks == length (filter (== ExitSuccess) exitcodes)
unless allOk exitFailure
where
Expand Down
2 changes: 1 addition & 1 deletion Cabal/Distribution/Simple/BuildTarget.hs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ readBuildTargets pkg targetStrs = do
let (uproblems, utargets) = readUserBuildTargets targetStrs
reportUserBuildTargetProblems uproblems

utargets' <- mapM checkTargetExistsAsFile utargets
utargets' <- traverse checkTargetExistsAsFile utargets

let (bproblems, btargets) = resolveBuildTargets pkg utargets'
reportBuildTargetProblems bproblems
Expand Down
2 changes: 1 addition & 1 deletion Cabal/Distribution/Simple/Compiler.hs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ registrationPackageDB dbs = last dbs


absolutePackageDBPaths :: PackageDBStack -> IO PackageDBStack
absolutePackageDBPaths = mapM absolutePackageDBPath
absolutePackageDBPaths = traverse absolutePackageDBPath

absolutePackageDBPath :: PackageDB -> IO PackageDB
absolutePackageDBPath GlobalPackageDB = return GlobalPackageDB
Expand Down
18 changes: 9 additions & 9 deletions Cabal/Distribution/Simple/Configure.hs
Original file line number Diff line number Diff line change
Expand Up @@ -1345,12 +1345,12 @@ configurePkgconfigPackages verbosity pkg_descr conf
(_, _, conf') <- requireProgramVersion
(lessVerbose verbosity) pkgConfigProgram
(orLaterVersion $ Version [0,9,0] []) conf
mapM_ requirePkg allpkgs
mlib' <- mapM addPkgConfigBILib (library pkg_descr)
libs' <- mapM addPkgConfigBILib (subLibraries pkg_descr)
exes' <- mapM addPkgConfigBIExe (executables pkg_descr)
tests' <- mapM addPkgConfigBITest (testSuites pkg_descr)
benches' <- mapM addPkgConfigBIBench (benchmarks pkg_descr)
traverse_ requirePkg allpkgs
mlib' <- traverse addPkgConfigBILib (library pkg_descr)
libs' <- traverse addPkgConfigBILib (subLibraries pkg_descr)
exes' <- traverse addPkgConfigBIExe (executables pkg_descr)
tests' <- traverse addPkgConfigBITest (testSuites pkg_descr)
benches' <- traverse addPkgConfigBIBench (benchmarks pkg_descr)
let pkg_descr' = pkg_descr { library = mlib',
subLibraries = libs', executables = exes',
testSuites = tests', benchmarks = benches' }
Expand Down Expand Up @@ -2132,7 +2132,7 @@ checkPackageProblems verbosity gpkg pkg = do
errors = [ e | PackageBuildImpossible e <- pureChecks ++ ioChecks ]
warnings = [ w | PackageBuildWarning w <- pureChecks ++ ioChecks ]
if null errors
then mapM_ (warn verbosity) warnings
then traverse_ (warn verbosity) warnings
else die (intercalate "\n\n" errors)

-- | Preform checks if a relocatable build is allowed
Expand Down Expand Up @@ -2189,11 +2189,11 @@ checkRelocatable verbosity pkg lbi
-- prefix of the package
depsPrefixRelative = do
pkgr <- GHC.pkgRoot verbosity lbi (last (withPackageDB lbi))
mapM_ (doCheck pkgr) ipkgs
traverse_ (doCheck pkgr) ipkgs
where
doCheck pkgr ipkg
| maybe False (== pkgr) (Installed.pkgRoot ipkg)
= mapM_ (\l -> when (isNothing $ stripPrefix p l) (die (msg l)))
= traverse_ (\l -> when (isNothing $ stripPrefix p l) (die (msg l)))
(Installed.libraryDirs ipkg)
| otherwise
= return ()
Expand Down
18 changes: 9 additions & 9 deletions Cabal/Distribution/Simple/GHC.hs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ guessToolFromGhcPath tool ghcProg verbosity searchpath
info verbosity $ "looking for tool " ++ toolname
++ " near compiler in " ++ given_dir
debug verbosity $ "candidate locations: " ++ show guesses
exists <- mapM doesFileExist guesses
exists <- traverse doesFileExist guesses
case [ file | (file, True) <- zip guesses exists ] of
-- If we can't find it near ghc, fall back to the usual
-- method.
Expand Down Expand Up @@ -397,7 +397,7 @@ getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramConfiguration
-> IO [(PackageDB, [InstalledPackageInfo])]
getInstalledPackages' verbosity packagedbs conf
| ghcVersion >= Version [6,9] [] =
sequence
sequenceA
[ do pkgs <- HcPkg.dump (hcPkgInfo conf) verbosity packagedb
return (packagedb, pkgs)
| packagedb <- packagedbs ]
Expand All @@ -415,11 +415,11 @@ getInstalledPackages' verbosity packagedbs conf = do
(UserPackageDB, _global:_) -> return $ Nothing
(SpecificPackageDB specific, _) -> return $ Just specific
_ -> die "cannot read ghc-pkg package listing"
pkgFiles' <- mapM dbFile packagedbs
sequence [ withFileContents file $ \content -> do
pkgFiles' <- traverse dbFile packagedbs
sequenceA [ withFileContents file $ \content -> do
pkgs <- readPackages file content
return (db, pkgs)
| (db , Just file) <- zip packagedbs pkgFiles' ]
| (db , Just file) <- zip packagedbs pkgFiles' ]
where
-- Depending on the version of ghc we use a different type's Read
-- instance to parse the package file and then convert.
Expand All @@ -441,7 +441,7 @@ getInstalledPackagesMonitorFiles :: Verbosity -> Platform
-> [PackageDB]
-> IO [FilePath]
getInstalledPackagesMonitorFiles verbosity platform progdb =
mapM getPackageDBPath
traverse getPackageDBPath
where
getPackageDBPath :: PackageDB -> IO FilePath
getPackageDBPath GlobalPackageDB =
Expand Down Expand Up @@ -659,17 +659,17 @@ buildOrReplLib forRepl verbosity numJobs pkg_descr lbi lib clbi = do
libInstallPath = libdir $ absoluteComponentInstallDirs pkg_descr lbi uid NoCopyDest
sharedLibInstallPath = libInstallPath </> mkSharedLibName compiler_id uid

stubObjs <- catMaybes <$> sequence
stubObjs <- catMaybes <$> sequenceA
[ findFileWithExtension [objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
, x <- libModules lib ]
stubProfObjs <- catMaybes <$> sequence
stubProfObjs <- catMaybes <$> sequenceA
[ findFileWithExtension ["p_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
, x <- libModules lib ]
stubSharedObjs <- catMaybes <$> sequence
stubSharedObjs <- catMaybes <$> sequenceA
[ findFileWithExtension ["dyn_" ++ objExtension] [libTargetDir]
(ModuleName.toFilePath x ++"_stub")
| ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
Expand Down
2 changes: 1 addition & 1 deletion Cabal/Distribution/Simple/GHC/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ getHaskellObjects _implInfo lib lbi pref wanted_obj_ext allow_split_objs
let splitSuffix = "_" ++ wanted_obj_ext ++ "_split"
dirs = [ pref </> (ModuleName.toFilePath x ++ splitSuffix)
| x <- libModules lib ]
objss <- mapM getDirectoryContents dirs
objss <- traverse getDirectoryContents dirs
let objs = [ dir </> obj
| (objs',dir) <- zip objss dirs, obj <- objs',
let obj_ext = takeExtension obj,
Expand Down
4 changes: 2 additions & 2 deletions Cabal/Distribution/Simple/GHCJS.hs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ guessToolFromGhcjsPath tool ghcjsProg verbosity searchpath
guessNormal]
info verbosity $ "looking for tool " ++ toolname
++ " near compiler in " ++ dir
exists <- mapM doesFileExist guesses
exists <- traverse doesFileExist guesses
case [ file | (file, True) <- zip guesses exists ] of
-- If we can't find it near ghc, fall back to the usual
-- method.
Expand Down Expand Up @@ -228,7 +228,7 @@ checkPackageDbStack _ =
getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramConfiguration
-> IO [(PackageDB, [InstalledPackageInfo])]
getInstalledPackages' verbosity packagedbs conf =
sequence
sequenceA
[ do pkgs <- HcPkg.dump (hcPkgInfo conf) verbosity packagedb
return (packagedb, pkgs)
| packagedb <- packagedbs ]
Expand Down
4 changes: 2 additions & 2 deletions Cabal/Distribution/Simple/Haddock.hs
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ haddockPackagePaths :: [InstalledPackageInfo]
-> Maybe (InstalledPackageInfo -> FilePath)
-> IO ([(FilePath, Maybe FilePath)], Maybe String)
haddockPackagePaths ipkgs mkHtmlPath = do
interfaces <- sequence
interfaces <- sequenceA
[ case interfaceAndHtmlPath ipkg of
Nothing -> return (Left (packageId ipkg))
Just (interface, html) -> do
Expand Down Expand Up @@ -750,7 +750,7 @@ getExeSourceFiles lbi exe clbi = do
getSourceFiles :: [FilePath]
-> [ModuleName.ModuleName]
-> IO [(ModuleName.ModuleName, FilePath)]
getSourceFiles dirs modules = flip mapM modules $ \m -> fmap ((,) m) $
getSourceFiles dirs modules = flip traverse modules $ \m -> fmap ((,) m) $
findFileWithExtension ["hs", "lhs"] dirs (ModuleName.toFilePath m)
>>= maybe (notFound m) (return . normalise)
where
Expand Down
2 changes: 1 addition & 1 deletion Cabal/Distribution/Simple/Hpc.hs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ markupPackage :: Verbosity
-> IO ()
markupPackage verbosity lbi distPref libName suites = do
let tixFiles = map (tixFilePath distPref way . testName) suites
tixFilesExist <- mapM doesFileExist tixFiles
tixFilesExist <- traverse doesFileExist tixFiles
when (and tixFilesExist) $ do
-- behaviour of 'markup' depends on version, so we need *a* version
-- but no particular one
Expand Down
Loading

0 comments on commit b90bd03

Please sign in to comment.