如何直接调用Monad函数?

Dav*_*vid 2 monads haskell

在下面的示例中,我希望能够直接调用'ls'函数(请参阅示例的最后一个注释掉的行),但我无法找出正确的语法.提前致谢.

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".")
Run Code Online (Sandbox Code Playgroud)

Ant*_*nov 7

你不能只是使用

mapM putStrLn (ls ".")
Run Code Online (Sandbox Code Playgroud)

因为ls "."有类型IO [FilePath],并且mapM putStrLn只是期望[FilePath],所以你需要使用bind,或者>>=在Haskell中.所以你的实际路线就是

main = ls "." >>= mapM_ putStrLn
Run Code Online (Sandbox Code Playgroud)

注意这个mapM_功能,而不仅仅是mapM.mapM会给你IO [()]打字,但是main你需要IO (),这mapM_就是为了什么.