Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active December 14, 2017 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisleech/d8f58115045e8ad08ffb6f0b9c0ccb28 to your computer and use it in GitHub Desktop.
Save krisleech/d8f58115045e8ad08ffb6f0b9c0ccb28 to your computer and use it in GitHub Desktop.
Clojure summing numbers in a map, a short story
(def fundings (sql/select-external-fundings sql/db { :year 2017 })) ;; raw data: ({...} {...})
(def sum-keys [:industry_collaborative :research_charity]) ;; keys we want to sum
(def sum-fundings map #(select-keys % sum-keys) fundings)) ;; collection with only keys we want to sum
;; => ({:industry_collaborative 1M :research_charity 2M}
;; {:industry_collaborative 1M :research_charity 1M}
;; {:industry_collaborative 10M :research_charity 1M})
(def start-map (reduce #(assoc %1 %2 0) {} sum-keys)) ;; map with keys all with values of 0
;; wanted end result:
;; {:industry_collaborative 12M :research_charity 4M}
(reduce #(assoc %1 :research_charity (+ (:research_charity %1) (:research_charity %2))) start-map sum-fundings)
;; => {:industry_collaborative 0 :research_charity 234.00M}
;; ^ works for hardcoded key
;; %1 is the return value of the last fn call, or start-map on the 1st call
;; %2 is an item from the collection
;; break it up...
(defn summer [result item] (assoc result :research_charity (+ (:research_charity item) (:research_charity result))))
(reduce summer start-map sum-fundings)
;; summer needs to take two hashes and add together values of the same keys...
;; feels like I need another map or reduce...
;; I want to merge, no not merge. But merge with a function...
;; A little Google later...
(defn summer [result item] (merge-with + result item))
(reduce summer start-map sum-fundings)
;; {:industry_collaborative 12M :research_charity 4M}
;; :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment