使用Haskell获取从绝对文件路径到另一个文件路径的相对路径

时间:2020-05-29 00:05:16

标签: haskell directory filepath relative-path absolute-path

我正在寻找Haskell函数以给出两个绝对路径之间的相对路径。 例如,给出:

  1. / home / mydir / images / dir1

  2. / home / mydir / docs / dir2

我想要从1到2的相对路径: ../../ docs / dir2

我看了filepathdirectory,但没有找到我需要的东西。

有功能或库可以执行我想要的吗?

1 个答案:

答案 0 :(得分:0)

我还没有找到这样的功能。您可以使用filepath实用程序来构建它

import System.FilePath
import Control.Applicative

relativeTo :: FilePath -> FilePath -> FilePath
relativeTo path1 path2 = joinPath . getZipList $ ZipList commonPath <|> ZipList splitPath1
 where
  splitPath1 = splitDirectories . dropDrive $ path1
  splitPath2 = splitDirectories . dropDrive $ path2
  dirToDots x y = if x == y && (x /= "/")
                    then ".." 
                    else ""
  commonPath = takeWhile (/= "") $ zipWith dirToDots splitPath1 splitPath2

main = print $ "/home/mydir/docs/dir2" `relativeTo` "/home/mydir/images/dir1"

路径中包含点(例如some/./pathsome/../path)的行为未经测试

相关问题