Last active
August 29, 2015 14:17
-
-
Save dyba/581b7474875750c170da to your computer and use it in GitHub Desktop.
LOL
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
;; 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