gpt4 book ai didi

haskell - 如何映射和连接文件路径?

转载 作者:行者123 更新时间:2023-12-02 12:29:15 24 4
gpt4 key购买 nike

我仍在研究 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", ...]

我想我可以使用某种双 map 来做到这一点,如下所示:

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

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

program.hs:27:56:    Couldn't match type `[]' with `IO'    Expected type: IO Char      Actual type: FilePath    In the expression: (pd </>) contents    In the first argument of `mapM', namely      `(\ contents -> (pd ) contents)'program.hs:27:84:    Couldn't match expected type `[FilePath]'                with actual type `IO [FilePath]'    In the second argument of `mapM', namely      `(getDirectoryContents pathDir)'    In the expression:      mapM        (\ contents -> (pd </>) contents)        (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]]

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

关于haskell - 如何映射和连接文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com