Finding out magnitude and unit map in Clojure

less than 1 minute read

Notes

;; map_operations.clj

(defn scalar-to-map [s map-keys]
  (reduce #(assoc %1 %2 s) {} map-keys))

(defn map-op [func m1 m2]
  (if (map? m2)
    (let [m1-keys (keys m1)
          m2-keys (keys m2)
          keys (distinct (concat m1-keys m2-keys))]
      (->> (map #(assoc {} %
                        (func
                         (get m1 % 0)
                         (get m2 % 0))) keys)
           (apply merge)))
    (map-op func m1 (scalar-to-map m2 (keys m1)))))

(defn map-mul [m1 m2]
  (map-op * m1 m2))

(defn map-div [m1 m2]
  (map-op / m1 m2))

(defn map-add [m1 m2]
  (map-op + m1 m2))

(defn map-sub [m1 m2]
  (map-op - m1 m2))

(defn map-dot-product [m1 m2]
  (reduce + (vals (map-mul m1 m2))))

(defn map-magnitude [m]
  (Math/sqrt (map-dot-product m m)))

(defn unit-map [m]
  (let [magnitude (map-magnitude m)]
    (map-div m magnitude)))

Updated: