Created
August 9, 2012 18:20
-
-
Save mtnygard/3306775 to your computer and use it in GitHub Desktop.
Retriable functions, written in CPS
This file contains 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
(ns planck-server-nio.common | |
(:require (clojure.algo [monads :as m]))) | |
(defn fail [x] (fn [c] nil)) | |
(defn attempt [[a t f]] | |
(fn [c] | |
(if-let [result (f)] | |
result | |
(c [(inc a) t f])))) | |
(defn delay [[a t f]] | |
(fn [c] | |
(Thread/sleep (t a)) | |
(c [a t f]))) | |
(m/with-monad m/cont-m | |
(defn retry [n t f] | |
(let [backoff (if (number? t) (constantly t) t) | |
steps (concat (take (* n 2) (cycle [attempt delay])) [fail]) | |
cont ((m/m-chain steps) [0 backoff f])] | |
(run-cont cont)))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment