Last active
August 29, 2015 14:07
-
-
Save jaycfields/42663bc7d1c5f119b73c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; top level, used only once | |
(defn only-used-once [r {:keys [foo]}] | |
(if (even? foo) | |
(+ r foo) | |
r)) | |
(defn sum-my-stuff1 [coll] | |
(reduce only-used-once 0 coll)) | |
;; anonymous fn, inline | |
(defn sum-my-stuff2 [coll] | |
(reduce | |
(fn [result {:keys [foo]}] | |
(if (even? foo) (+ result foo) result)) | |
0 | |
coll)) | |
;; multi-arity to encapsulate both | |
(defn sum-my-stuff3 | |
([coll] (sum-my-stuff3 0 coll)) | |
([result [{:keys [foo] :as hd} & tl]] | |
(cond | |
(nil? hd) result | |
(even? foo) (recur (+ result foo) tl) | |
:else (recur result tl)))) | |
;; loop, no other fns needed. | |
(defn sum-my-stuff4 [coll] | |
(loop [result 0 [{:keys [foo] :as hd} & tl] coll] | |
(cond | |
(nil? hd) result | |
(even? foo) (recur (+ result foo) tl) | |
:else (recur result tl)))) |
;; transducer version - the future?
(defn sum-my-stuff-inf [coll]
(transduce (comp (map :foo) (filter even?)) + coll))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As a side-note: the part I found most opaque is the parameter destructuring, but I then again, I rarely use :keys (or mebbe that cause/effect is the other way round).