在下面的示例中,我希望能够直接调用'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".")发布于 2013-05-07 00:48:02
你不能只用
mapM putStrLn (ls ".")因为ls "."具有类型IO [FilePath],而mapM putStrLn只需要[FilePath],所以您需要使用bind,或者在Haskell中使用>>=。所以你的实际代码行应该是
main = ls "." >>= mapM_ putStrLn注意mapM_函数,而不仅仅是mapM函数。mapM将为您提供IO [()]类型,但对于main,您需要IO (),这就是mapM_的用途。
https://stackoverflow.com/questions/16403204
复制相似问题