gpt4 book ai didi

haskell - haskell复制目录的方法是什么

转载 作者:行者123 更新时间:2023-12-02 09:12:08 25 4
gpt4 key购买 nike

我发现自己在 haskell 中编写越来越多的脚本。但在某些情况下,我真的不确定如何“正确”地做到这一点。
例如递归复制目录(类似于 unix cp -r)。

由于我主要使用 Linux 和 Mac OS,所以我通常会作弊:

import System.Cmd
import System.Exit

copyDir :: FilePath -> FilePath -> IO ExitCode
copyDir src dest = system $ "cp -r " ++ src ++ " " ++ dest

但是以独立于平台的方式复制目录的推荐方法是什么?
我在 hackage 上没有找到任何合适的内容。

这是我迄今为止使用的相当幼稚的实现:

import System.Directory
import System.FilePath((</>))
import Control.Applicative((<$>))
import Control.Exception(throw)
import Control.Monad(when,forM_)

copyDir :: FilePath -> FilePath -> IO ()
copyDir src dst = do
whenM (not <$> doesDirectoryExist src) $
throw (userError "source does not exist")
whenM (doesFileOrDirectoryExist dst) $
throw (userError "destination already exists")

createDirectory dst
content <- getDirectoryContents src
let xs = filter (`notElem` [".", ".."]) content
forM_ xs $ \name -> do
let srcPath = src </> name
let dstPath = dst </> name
isDirectory <- doesDirectoryExist srcPath
if isDirectory
then copyDir srcPath dstPath
else copyFile srcPath dstPath

where
doesFileOrDirectoryExist x = orM [doesDirectoryExist x, doesFileExist x]
orM xs = or <$> sequence xs
whenM s r = s >>= flip when r

关于真正的方法有什么建议吗?

<小时/>

我根据 hammar 和 FUZxxl 的建议更新了此内容。
...但对于这样一个常见的任务,我仍然感觉有点笨拙!

最佳答案

可以使用 Shelly要执行此操作,请参阅 cp_r 库:

cp_r "sourcedir" "targetdir"

Shelly 首先尝试使用 native cp -r(如果可用)。如果没有,它将回退到 native Haskell IO 实现。

有关 cp_r 类型语义的更多详细信息,请参阅 this post由我编写,描述如何将 cp_rString 和或 Text 一起使用。

Shelly 不是独立于平台的,因为它依赖于 Unix软件包,Windows 下不支持。

关于haskell - haskell复制目录的方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6807025/

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