Created
November 27, 2012 11:58
-
-
Save sortega/4153881 to your computer and use it in GitHub Desktop.
Decorate a function to know how many times is called
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
(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