Created
September 4, 2017 19:01
-
-
Save Olical/3de12db1d8d9b4af926ce2f6e7b24cd0 to your computer and use it in GitHub Desktop.
A function macro that yields the EXACT same function reference if the arguments and body LOOK the same.
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
;; Wasn't sure on a name, but this'll do. | |
(def fn-cache (atom {})) | |
(defmacro lzfn [& forms] | |
`(let [fn-hash# (hash '~forms) | |
fn# (get @fn-cache fn-hash#)] | |
(if fn# | |
fn# | |
(let [new-fn# (fn ~@forms)] | |
(swap! fn-cache assoc fn-hash# new-fn#) | |
new-fn#)))) | |
(def a (lzfn [y] (+ y x))) | |
(def b (lzfn [y] (+ y x))) | |
(def c (lzfn [y] (* y x))) | |
(= a b) ;; true | |
(= b c) ;; false | |
;; The reason I didn't take this further was this: I intended for this to be used with Reagent et al in event handler bindings. | |
;; Creating anon functions every render is not a good idea, I hoped this would help. | |
;; The problem is that the cached fn will carry it's scope with it, which will be super confusing. | |
;; Still a fun experiment into macros. Maybe it'll help someone some day! :D |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment