Vector distances in Clojure

less than 1 minute read

Notes

;; vector_distance.clj

(defn square-of-distance [s1 s2]
  (Math/pow (- s1 s2) 2))

(defn absolute-distance [s1 s2]
  (Math/abs (- s1 s2)))

(defn vector-distance [v1 v2]
  (->> (map square-of-distance v1 v2)
       (reduce +)
       Math/sqrt))

(defn manhattan-distance [v1 v2]
  (->> (map absolute-distance v1 v2)
       (reduce +)))

(vector-distance [0 0] [3 4])
(manhattan-distance [0 0] [3 4])
(vector-distance [0 0 7] [3 4 5])
;; lp_distance.clj

(defn absolute-distance [s1 s2]
  (Math/abs (- s1 s2)))

(defn lp-distance [v1 v2 p]
  (as-> (map absolute-distance v1 v2) x
    (map #(Math/pow % p) x)
    (reduce + x)
    (Math/pow x (/ 1 p))))

(defn vector-distance [v1 v2]
  (lp-distance v1 v2 2))

(defn manhattan-distance [v1 v2]
  (lp-distance v1 v2 1))

(lp-distance [0 0] [3 4] 1)
(lp-distance [0 0] [3 4] 2)

(manhattan-distance [0 0] [3 4])
(vector-distance [0 0] [3 4])

Updated: