[Haskell-cafe] comprehension generators from IO [a]'s ?

Bulat Ziganshin bulatz at HotPOP.com
Tue Dec 20 04:36:36 EST 2005

Hello Steve,

Monday, December 19, 2005, 10:42:19 PM, you wrote:

SH> What I'm after is something like:
SH>  -- (psuedo-code)
SH>  [(b,c,d) |
SH>            b <- getDirectoryContents a_dir,
SH>            c <- getDirectoryContents (a_dir ++ "/" ++ b),
SH>            d <- getDirectoryContents (a_dir ++ "/" ++ b ++ "/" ++ c) ],

this can't work because IO itself a monad, so "IO [a]" is two monads,
and you can iterate only over external one, which is IO. instead:

let foreach = flip mapM
list <- foreach (getDirectoryContents a_dir) $ \b ->
  foreach (getDirectoryContents (a_dir ++ "/" ++ b)) $ \c ->
    foreach (getDirectoryContents (a_dir ++ "/" ++ b ++ "/" ++ c)) $ \d ->
      return (b,c,d)
return $ concatMap $ concatMap list

SH> This function isn't so clear at a glance, and yet what it's doing
SH> seems like a pretty common thing to want to do:  are there any library
SH> functions for monads (or IO in particular) that make this sort of thing
SH> easier, or should I to try and write my own function?  Looks not too
SH> difficult to write but I think I might miss something important if I didn't ask
SH> first...  How would you do it?

if you just need to find all files recursively - use library
http://hackage.haskell.org/packages/FilePath-0.1.0.tgz to manipulate
filenames and function `doesDirectoryExist` to check that it is a
directory. don't forget that `getDirectoryContents` returns list what
contains names "." and ".."

Best regards,
 Bulat                            mailto:bulatz at HotPOP.com

More information about the Haskell-Cafe mailing list