Skip to content

Instantly share code, notes, and snippets.

@sortega
Created November 27, 2012 11:58
Show Gist options
  • Save sortega/4153881 to your computer and use it in GitHub Desktop.
Save sortega/4153881 to your computer and use it in GitHub Desktop.
Decorate a function to know how many times is called
(defn counted [f]
(let [times (atom 0)] ; thread safe counter
(with-meta (fn [& args]
(swap! times inc)
(apply f args))
{:times times}))) ; associated as metadata
(defn times-runned [f]
@(:times (meta f)))
(comment
(def cinc (counted inc))
#'user/cinc
user=> (cinc 1)
2
user=> (cinc 1)
2
user=> (cinc 1)
2
user=> (times-runned cinc)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment