Last active
August 29, 2015 14:13
-
-
Save xpe/46128da5accb0acdf30d to your computer and use it in GitHub Desktop.
Clojure: iterate-until-stable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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