Last active
November 8, 2015 17:54
-
-
Save brianfay/8f752374ed7e2c48b5ad 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
;;Implemented some using reduce, based on a challenge in Daniel Higginbotham's "Clojure for the Brave and True | |
;;This doesn't really work right; it breaks on lists, and it keeps running through the sequence even after it finds | |
;;a value that passes the predicate... | |
(defn my-some | |
"If the predicate is true for some value, returns that value (implemented with reduce)" | |
[pred sequence] | |
(reduce (fn | |
[x y] | |
(if (pred x) x y)) (conj sequence nil))) | |
(my-some #(and (< 30 %) %) [1 2 3 4 5 6 7]) ;;returns nil as expected | |
(my-some #(and (< 3 %) %) [1 2 3 4 5 6 7]) ;;returns 4 as expected | |
(my-some #(and (< 3 %) %) '(1 2 3 4 5 6 7)) ;; Uh oh, NPE... | |
;;EDIT: found a function called "reduced" that will terminate/short-circuit a reduce. Awesome, but how does it work!? | |
(defn my-some | |
"If the predicate is true for some value, returns that value (implemented with reduce)" | |
[pred sequence] | |
(reduce (fn | |
[x y] | |
(if (pred x) (reduced x) y)) sequence)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment