Karen Fisher
Karen Fisher

Reputation: 777

How to filter through the directory list with doesFileExist function in Haskell?

I've managed to print the list of directory with this Haskell code:

import Control.Monad
import Control.Applicative
import System.Directory

main :: IO()
main = do
  all <- listDirectory "x:/n"
  mapM_ print all

But now I want to filter all with the doesFileExist function from System.Direcorty module and can't understand how to use it properly:

import Control.Monad
import Control.Applicative
import System.Directory

main :: IO()
main = do
  all <- listDirectory "x:/n"
  mapM_ print (filterM doesFileExist all) 

the code above doesn't compile with ther error:

  * No instance for (Foldable IO) arising from a use of `mapM_'
* In a stmt of a 'do' block:
    mapM_ print (filterM doesFileExist all)
  In the expression:
    do all <- listDirectory "x:/n"
       mapM_ print (filterM doesFileExist all)
  In an equation for `main':
      main
        = do all <- listDirectory "x:/n"
             mapM_ print (filterM doesFileExist all)

   mapM_ print (filterM doesFileExist all)
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I guess that I've missed something fundumental, so, please, give me a hand in finding the way to understand what I am missing. Thanks

Upvotes: 0

Views: 197

Answers (1)

chi
chi

Reputation: 116174

Use another <-:

main = do
  all <- listDirectory "x:/n"
  filtered <- filterM doesFileExist all
  mapM_ print filtered

Upvotes: 4

Related Questions