Creating a Clojure library for map operations

less than 1 minute read

Notes

;; map_product.clj

(defn map-product [m1 m2]
  (let [m1-keys (keys m1)
        m2-keys (keys m2)
        keys (distinct (concat m1-keys m2-keys))]
    (->> (map #(assoc {} %
                      (*
                       (get m1 % 0)
                       (get m2 % 0))) keys)
         (apply merge))))

(defn map-dot-product [m1 m2]
  (reduce + (vals (map-product m1 m2))))
;; 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))))

Updated: