【问题标题】:How to filter through the directory list with doesFileExist function in Haskell?如何在Haskell中使用doesFileExist函数过滤目录列表?
【发布时间】: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 &gt;&gt;= mapM_ print
  • 如果您创建并回答,我会像您一样接受它。现在我明白了 >>= 的目的(或多或少)
  • 如果您将do 符号与&lt;-“操作符”一起使用——正如你在这里清楚地看到的那样——那么即使你认为自己不理解,你也确实理解&gt;&gt;= 的目的。下面提供的答案与上面评论中的答案完全相同——一个使用do 表示法,另一个使用明确的&gt;&gt;=,但它们的含义完全相同。 do 表示法(或多或少)只是&gt;&gt;= 连续使用的语法糖。

标签: haskell io


【解决方案1】:

使用另一个&lt;-

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

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多