Created
November 17, 2017 23:14
-
-
Save gdeer81/cd313b12cd9a626d85b83be9d390b956 to your computer and use it in GitHub Desktop.
Example of using :when qualifier in a for comprehension
This file contains 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
(set! *unchecked-math* false) | |
(defn find-the-pairs [^long n] | |
"takes an upper bound and returns all the pairs of numbers where | |
(* x y) equals the sum of the entire collection without x and y | |
(find-the-pairs 26) => [[15 21] [21 15]] | |
" | |
(let [^long coll-sum (/ (* n (inc n)) 2)] | |
(for [^long i (range 1 (inc n)) ^long j (range 1 (inc n)) | |
:when (= (- coll-sum i j) (* i j))] | |
[i j]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm leaving this here in case I ever need a refresher on the power of the
for
comprehension.the
:when
qualifier let me keep the comprehension logic clean which also keeps the results cleanExample: This code
(for [x (range 10)] (when (even? x) x))
returns(0 nil 2 nil 4 nil 6 nil 8 nil)
so whatever code uses those results has to remove the nils.But this code
(for [x (range 10) :when (even? x)] x)
returns(0 2 4 6 8)
the
:let
qualifier lets you keep even more logic out of your body:this code
(for [x (range 10) :let [y (inc x)] :when (odd? y)] x)
returns the same thing as the code above but it shows that if we need to compute some new variables to use in our conditional we can do thatYou can also use it on its own:
(for [x (range 3) :let [triple-x (* x x x)] triple-pairs] triple-x)
=>(0 1 8)