Jef*_*att 5 monads haskell io-monad
我仍在研究 Haskell,尤其是 IO monad。
我有一个目录路径列表,例如,
["/some/path", "/another/path", "/yet/another/path", "/still/more"]
并且我想将此列表映射到每个路径的完全限定内容列表中(没有.
和..
),如下所示:
["/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 字符 实际类型:文件路径 在表达式中: (pd </>) 内容 在‘mapM’的第一个参数中,即 `(\ 内容 -> (pd ) 内容)' 程序.hs:27:84: 无法匹配预期类型“[FilePath]” 实际类型为“IO [FilePath]” 在'mapM'的第二个参数中,即 `(getDirectoryContents pathDir)' 在表达式中: 地图M (\ 内容 -> (pd </>) 内容) (getDirectoryContents pd)
可能的解决方案(导入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]]
Run Code Online (Sandbox Code Playgroud)
可能有某种方法可以进一步简化它。