David
David

Reputation: 6152

How can I invoke a Monad function directly?

In the example below, I'd like to be able to call the 'ls' function directly (see the last commented out line of the example) but I have not been able to figure out the correct syntax. Thanks in advance.

module Main (main) where

import System.Directory

ls :: FilePath -> IO [FilePath]
ls dir = do
    fileList <- getDirectoryContents dir
    return fileList

main = do
    fileList <- ls "."
    mapM putStrLn fileList 
    -- How can I just use the ls call directly like in the following (which doesn't compile)?
    -- mapM putStrLn (ls".")

Upvotes: 2

Views: 110

Answers (1)

Anton Guryanov
Anton Guryanov

Reputation: 12467

You can't just use

mapM putStrLn (ls ".")

because ls "." has type IO [FilePath], and mapM putStrLn expects just [FilePath], so you need to use bind, or >>= in Haskell. So your actual line would be

main = ls "." >>= mapM_ putStrLn

Notice the mapM_ function, not just mapM. mapM will give you IO [()] type, but for main you need IO (), and that's what mapM_ is for.

Upvotes: 7

Related Questions