Skip to content

Instantly share code, notes, and snippets.

@dyba
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyba/581b7474875750c170da to your computer and use it in GitHub Desktop.
Save dyba/581b7474875750c170da to your computer and use it in GitHub Desktop.
LOL
;; We can go further and use automatic gensyms provided
;; by Clojure when use a hashtag after the symbol we
;; want gensymed
(defmacro nif
[expr pos zero neg]
`(let [e# ~expr]
(cond
(pos? e#) ~pos
(zero? e#) ~zero
:else ~neg)))
;; if we convert nif to a function instead of a macro
;; any expressions we passed to positive, negative, and zero
;; would be immediately evaluated
;; That includes side effects that occur with the evaluation
;; of each expression. With the macro, only one form is
;; evaluated: pos, zero, or neg.
#_(defn nif
[expr pos zero neg]
(let [e expr]
(cond
(pos? e) pos
(zero? e) zero
:else neg)))
(comment
(nif (do (println 100) -10)
(do (println "Positive") "pos")
(do (println "Zero") "zero")
(do (println "Negative") "neg")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Chapter 4
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(let [s 'hello]
`(~s ~'world))
;; => (hello world)
;; We can't do this...
(let [s 'hello]
`(~s world))
;; because Clojure resolves world to the current namespace:
;; => (hello lol.core/world)
(let [s '(b c d)]
`(~'a ~@s ~'e))
;; => (a b c d e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment