【发布时间】:2019-02-10 22:38:35
【问题描述】:
我已经用这个 Haskell 代码打印了目录列表:
import Control.Monad
import Control.Applicative
import System.Directory
main :: IO()
main = do
all <- listDirectory "x:/n"
mapM_ print all
但现在我想用 System.Direcorty 模块中的 dosFileExist 函数过滤所有内容,无法理解如何正确使用它:
import Control.Monad
import Control.Applicative
import System.Directory
main :: IO()
main = do
all <- listDirectory "x:/n"
mapM_ print (filterM doesFileExist all)
上面的代码编译时出现错误:
* 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)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我想我错过了一些基本的东西,所以,请帮我找出方法来了解我所缺少的东西。 谢谢
【问题讨论】:
-
你可以使用
filterM doesFileExists all >>= mapM_ print。 -
如果您创建并回答,我会像您一样接受它。现在我明白了 >>= 的目的(或多或少)
-
如果您将
do符号与<-“操作符”一起使用——正如你在这里清楚地看到的那样——那么即使你认为自己不理解,你也确实理解>>=的目的。下面提供的答案与上面评论中的答案完全相同——一个使用do表示法,另一个使用明确的>>=,但它们的含义完全相同。do表示法(或多或少)只是>>=连续使用的语法糖。