5

我仍在研究 Haskell,尤其是 IO monad。

我有一个目录路径列表,例如,

["/some/path", "/another/path", "/yet/another/path", "/still/more"]

我想将此列表映射到每个路径的完全限定内容列表(没有.and ..),如下所示:

["/some/path/file.1", "/some/path/somedir", "/some/path/file.2", "/another/path/file.a", "/another/path/a/directory", "/another/path/file.b", "/still/more/file.alpha", ...]

我想我可以用某种双地图来做到这一点,就像这样:

pathItems <- mapM (\pd -> MapM (\contents -> (pd </>) contents) (getDirectoryContents pd) pathDirs

但这不起作用。我得到的错误是:

程序.hs:27:56:
    无法将类型“[]”与“IO”匹配
    预期类型:IO 字符
      实际类型:FilePath
    在表达式中:(pd </>) 内容
    在“mapM”的第一个参数中,即
      `(\ 内容 -> (pd ) 内容)'

程序.hs:27:84:
    无法匹配预期类型“[FilePath]”
                实际类型为“IO [FilePath]”
    在`mapM'的第二个参数中,即
      `(getDirectoryContents pathDir)'
    在表达式中:
      地图M
        (\ 内容 -> (pd </>) 内容)
        (getDirectoryContents pd)
4

1 回答 1

3

一个可能的解决方案(导入System.IO System.Directory System.FilePath Control.Applicative):

concat <$> mapM (\pd -> map (pd </>) <$> getDirectoryContents pd) pathDirs
                                   -- ^ this is to work under IO (..)
                    --  ^ this is to affect what's under IO [..]
        -- ^ this returns IO [[FilePath]]

可能有一些方法可以进一步简化它。

于 2015-04-24T07:55:01.050 回答