在clojure中提供相对路径的函数?

在clojure中提供相对路径的函数?,clojure,Clojure,我需要一个函数,当给定一个基本目录和另一个路径时,我已经做了一个简化版本,只匹配绝对路径,但希望也能够智能地处理路径中的“..”和“.”。我不确定最好的方法是什么 一些例子: (relative-path "example" "example/hello") => "hello" (relative-path "example" "../example/hello") => "hello" (relative-path "example" "/usr/local") =>

我需要一个函数,当给定一个基本目录和另一个路径时,我已经做了一个简化版本,只匹配绝对路径,但希望也能够智能地处理路径中的“..”和“.”。我不确定最好的方法是什么

一些例子:

(relative-path "example" "example/hello") => "hello"

(relative-path "example" "../example/hello") => "hello"

(relative-path "example" "/usr/local") => "../../../usr/local"

经过一番尝试和错误之后,我发现了这一点:

(require '[clojure.java.io :as io]
         '[clojure.string :as string])

(defn interpret-dots
  ([v] (interpret-dots v []))
  ([v output]
     (if-let [s (first v)]
       (condp = s
         "."  (recur (next v) output)
         ".." (recur (next v) (pop output))
         (recur (next v) (conj output s)))
       output)))

(defn drop-while-matching [u v]
  (cond (or (empty? u) (empty? v)) [u v]

        (= (first u) (first v))
        (recur (rest u) (rest v))

        :else [u v]))

(defn path-vector [path]
  (string/split (.getAbsolutePath (io/file path))
                (re-pattern (System/getProperty "file.separator"))))

(defn relative-path [root other]
  (let [[base rel] (drop-while-matching (interpret-dots (path-vector root))
                                        (interpret-dots (path-vector other)))]
    (if (and (empty? base) (empty? rel))
      "."
      (->> (-> (count base)
               (repeat "..")
               (concat rel))
           (string/join (System/getProperty "file.separator")))))
用法:

(relative-path "example/repack.advance/resources"
           "example/repack.advance/resources/eueueeueu/oeuoeu")
;;=> "eueueeueu/oeuoeu"

(relative-path "example/repack.advance/resources"
           "/usr/local")
;;=> "../../../../../../../../usr/local"

我发现很难效仿你的榜样。你能更具体地说明你的要求吗?试试看