Simple decorator in Clojure
Code
;; simple_function_decorator.clj
;; 1. Simple Function Decorator (Higher-Order Function)
;; Define a decorator function
(defn timer-decorator [f]
(fn [& args]
(println "Starting execution...")
(let [start (System/currentTimeMillis)
result (apply f args)
end (System/currentTimeMillis)]
(println (str "Execution time: " (- end start) "ms"))
result)))
;; Define a function
(defn slow-add [x y]
(Thread/sleep 1000)
(+ x y))
;; Apply the decorator
(def timed-add (timer-decorator slow-add))
;; Use it
(timed-add 5 3) ; prints timing info and returns 8