As with most problems, there are several ways to solve it. This is just one of them.
If you are using Clojure 1.5, try:
(reduce (fn [acc [ab]] (if (pred b) (reduced (concat (:res acc) [[a (+ b 2)]] (rest (:coll acc)))) (assoc acc :res (conj (:res acc) [ab]) :coll (rest (:coll acc))))) {:coll coll :res []} coll) ;; ([:a 20] [:b 30] [:c 52] [:d 90])
The key to this algorithm is to use the reduced function (note the "d" function) - it essentially tells reduce stop the iteration and return the result. From the doc line:
The code is a bit accurate, but it should give you the basic idea.
Hope this helps.
source share