Skip to content

Instantly share code, notes, and snippets.

@xpe
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xpe/46128da5accb0acdf30d to your computer and use it in GitHub Desktop.
Save xpe/46128da5accb0acdf30d to your computer and use it in GitHub Desktop.
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