Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a ":until" like command in clojure?

Tags:

clojure

I want to perform the following nested operations until the experession is satisfied.. Is there a :until keyword which stops doing further operations when the condition matches.?

This command generates the Pythagoran Triplet 3 4 5. I dont want it to do anything else once it gets to that 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 (+ a b c))]
     (list a b c))
like image 389
unj2 Avatar asked Dec 08 '22 06:12

unj2


1 Answers

:while is a short-circuiting test in for expressions. List elements will be generated until the first time it encounters a failing test.

In your case

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

would stop generating elements as soon as it found the triplet summing to 12.

One problem though, it doesn't do what you're expecting. The triplet itself would not be part of the result since it failed the test.

A list comprehension may not be the best solution if you are only looking for a single matching 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 (+ a b c)))
        (recur (next xs))
        (list a b c)))))
like image 191
alanlcode Avatar answered Dec 11 '22 09:12

alanlcode