Skip to content

Instantly share code, notes, and snippets.

@ifesdjeen
Last active December 16, 2015 21:09
Show Gist options
  • Save ifesdjeen/5497846 to your computer and use it in GitHub Desktop.
Save ifesdjeen/5497846 to your computer and use it in GitHub Desktop.
Always think of Clojure functions, when you pass them around, as of values, not references. Whenever you change the root, previous function (one that you have already passed around), won't change. Only future calls will yield new value.
;; Declare a function
(defn fun1 [] (println 1))
;; And a hash that would capture that function
(def h {:key fun1})
;; => {:key #<user$fun1 user$fun1@5e540696>}
;; Now, check out the value of the key
(:key h)
;; => #<user$fun1 user$fun1@5e540696>
;; Run the reference of function
((:key h))
;; That's println:
;; => 1
;; nil
;; Redefine the function:
(defn fun1 [] (println 2))
;; => #'user/fun1
;; Run it!
((:key h))
;; That's println:
;; => 1
;; nil
;; Compare references:
fun1
;; => #<user$fun1 user$fun1@3494e2d2>
(:key h)
;; => #<user$fun1 user$fun1@5e540696>
;; In order to avoid it, use #'
(def h {:key #'fun1})
;; That fixes everything. If you don't want to keep writing #' everywhere,
;; and you can afford abstracting things away, use macro:
(defmacro by-reference [a]
`(#'~a))
;; Of course I mean use #' within your own macro, no sense replacing pretty #' with `by-reference`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment