Skip to content

Instantly share code, notes, and snippets.

@mbertheau
Created February 20, 2020 16:31
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 mbertheau/3f4081b000be2eb277360e8bfffdb147 to your computer and use it in GitHub Desktop.
Save mbertheau/3f4081b000be2eb277360e8bfffdb147 to your computer and use it in GitHub Desktop.
(def spy #(do (println "DEBUG:" %) %))
(def items [{:steps 5 :date :ereyesterday}
{:steps 4 :date :yesterday}
{:steps 6 :date :today}
{:steps 7 :date :tomorrow}
{:steps 3 :date :overmorrow}])
(def items-noreach [{:steps 1 :date :ereyesterday}
{:steps 1 :date :yesterday}
{:steps 1 :date :today}
{:steps 1 :date :tomorrow}
{:steps 1 :date :overmorrow}])
(defn goal-reached? [n] (>= n 10))
(defn f-normales-reduce [items]
(let [reductor (fn [{:keys [steps-total] :as acc}
{:keys [steps date]}]
(if (goal-reached? steps-total)
acc
{:steps-total (+ steps-total steps)
:date date}))
intermediate (reduce reductor {:steps-total 0 :date nil} items)]
(cond-> intermediate
(not (goal-reached? (:steps-total intermediate))) (assoc :date nil))))
(defn f-anderer-ansatz-aber-komplexer-und-sackgasse [items]
(let [reductor (fn [{:keys [steps-total]}
{:keys [steps date]}]
(let [new-steps-total (+ steps-total steps)]
{:steps-total new-steps-total
:date (when (goal-reached? new-steps-total) date)}))]
(->> items
(reductions reductor {:steps-total 0 :date nil})
spy
(filter #(goal-reached? (:steps-total %)))
spy
first)))
(defn f-funktioniert-aber-viel-noise-im-code [items]
(let [reductor (fn [{:keys [steps-total]}
{:keys [steps date]}]
(if (goal-reached? steps-total)
(reduced {:steps-total steps-total :date date})
{:steps-total (+ steps-total steps) :date nil}))]
(reduce reductor {:steps-total 0 :date nil} items)))
(defn f-funktioniert-fast-aber-weniger-noise [items]
(let [reductor (fn [steps-total
{:keys [steps date]}]
(if (goal-reached? steps-total)
(reduced {:steps-total steps-total :date date})
(+ steps-total steps)))]
(reduce reductor 0 items)))
(f-normales-reduce items)
(f-normales-reduce items-noreach)
(f-anderer-ansatz-aber-komplexer-und-sackgasse items)
(f-anderer-ansatz-aber-komplexer-und-sackgasse items-noreach)
(f-funktioniert-aber-viel-noise-im-code items)
(f-funktioniert-aber-viel-noise-im-code items-noreach)
(f-funktioniert-fast-aber-weniger-noise items)
(f-funktioniert-fast-aber-weniger-noise items-noreach)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment