Is there a ": to" command, as in clojure?

I want to perform the following nested operations until the experiment is satisfied. Is there: up to a keyword that stops performing further operations when the condition is met.?

This command generates Pythagoran Triplet 3 4 5. I do not want him to do anything else when he gets into this sequence of numbers.

(for [a (range 1 100) b (range 1 100) c (list (Math/sqrt (+ (Math/pow (int a) 2) (Math/pow (int b) 2)))) :when (= 12 (+ abc))] (list abc)) 
+4
source share
2 answers

:while is a short circuit criterion in for expressions. The elements of the list will be generated until the first time it performs a test with an error.

In your case

 (for [<code omitted> :while (not (= 12 (+ abc)))] (list abc)) 

will stop generating elements as soon as it finds triplet summation up to 12.

One problem, however, it does not do what you expect. The triplet itself will not be part of the result, since it did not pass the test.

Understanding the list may not be the best solution if you are looking for only one match result. Why not just use a loop?

 (loop [xs (for [a (range 1 100) b (range 1 100)] [a, b])] (when (seq xs) (let [[a, b] (first xs) c (Math/sqrt (+ (Math/pow (int a) 2) (Math/pow (int b) 2)))] (if (not (= 12 (+ abc))) (recur (next xs)) (list abc))))) 
+9
source

Since for gives lazy , you will get the desired result by selecting the first element:

 (first (for [a (range 1 100) b (range 1 100) c (list (Math/sqrt (+ (Math/pow (int a) 2) (Math/pow (int b) 2)))) :when (= 12 (+ abc))] (list abc)) 

Only the first element of the generated list is calculated due to laziness, which can be demonstrated with a side effect:

 user=> (first (for [a (range 1 100) b (range 1 100) c (list (Math/sqrt (+ (Math/pow (int a) 2) (Math/pow (int b) 2)))) :when (= 12 (+ abc))] (do (println "working...") (list abc)))) working... (3 4 5.0) 

(for ...) comes with a: allow modifier, so there is no need to move c to the list:

 (for [a (range 1 100) b (range 1 100) :let [c (Math/sqrt (+ (Math/pow (int a) 2) (Math/pow (int b) 2)))] :when (= 12 (+ abc))] (list abc)) 
+6
source

All Articles