Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Clojure: iterate-until-stable
;; gfredericks on IRC
(defn repeat-until-stable
[f x]
(->> (iterate f x)
(partition 2 1)
(filter (fn [[x1 x2]] (= x1 x2)))
ffirst))
;; amalloy on IRC
(defn repeat-until-stable
[f x]
(->> (iterate f x)
(partition 2 1)
(filter (partial apply =))
ffirst))
;; gfredericks on IRC
(defn repeat-until-stable
[f x]
(reduce (fn [x1 x2] (if (= x1 x2) (reduced x1) x2))
(iterate f x)))
(defn iterate-until-stable
"Takes a function of one arg and calls (f x), (f (f x)), and so on
until the value does not change."
[f x]
(loop [v x]
(let [v' (f v)]
(if (= v' v)
v
(recur v')))))
(defn f
"Returns (x - 1) ^ 2."
[x]
(let [v (dec x)]
(* v v)))
(def zeros
"Returns the solutions to (x - 1) ^ 2."
(let [xs [1.5 (-> (Math/sqrt 5) (/ 2.0))]]
(map #(apply % xs) '(+ -))))
(iterate-until-stable f (first zeros)) ;; 2.618033988749895
(iterate-until-stable f (second zeros)) ;; hangs
(iterate-until-stable f (+ 0.001 (first zeros))) ;; Double/POSITIVE_INFINITY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.