macro based decorator in Clojure
clojure-diary.gitlab.io·20h
🧠Lisp Dialects
Preview
Report Post

1 minute read

Code

;; macro_based_decorator.clj

;; 3. Macro-based Decorator (More Python-like Syntax)

(defmacro decorate [decorator & body]
(let [form (first body)]
(if (and (list? form) (= 'fn (first form)))
;; Anonymous function: (decorate decorator (fn [x y] (+ x y)))
`(~decorator ~form)
;; Named function: (decorate decorator (add [x y] (+ x y)))
(let [[fname args & fbody] form]
`(def ~fname (~decorator (fn ~args ~@fbody)))))))

;; Define decorators
(defn log-calls [f]
(fn [& args]
(println (str "Calling function with args: " args))
(let [result (apply f args)]
(println (str "Result: " result))
result)))

(defn timer-decorator [f]
(fn [& args]
(let [start (System/nanoTime)
result (apply f args)
end (System/nanoTime)]
(println (str "Execution time: " (/ (- end start) 1000000...

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help