Skip to content

Instantly share code, notes, and snippets.

@mtnygard
Created August 9, 2012 18:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtnygard/3306775 to your computer and use it in GitHub Desktop.
Save mtnygard/3306775 to your computer and use it in GitHub Desktop.
Retriable functions, written in CPS
(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