Skip to content

Instantly share code, notes, and snippets.

@gdeer81
Created Nov 17, 2017
Embed
What would you like to do?
Example of using :when qualifier in a for comprehension
(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])))
@gdeer81
Copy link
Author

gdeer81 commented Nov 17, 2017

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 clean
Example: 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 that
You can also use it on its own:
(for [x (range 3) :let [triple-x (* x x x)] triple-pairs] triple-x) => (0 1 8)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment