2014-05-02 21:37:11 +00:00
|
|
|
(ns koans.17-macros
|
|
|
|
(:require [koan-engine.core :refer :all]))
|
2014-01-26 00:04:22 +00:00
|
|
|
|
2011-02-08 11:51:11 +00:00
|
|
|
(defmacro hello [x]
|
|
|
|
(str "Hello, " x))
|
|
|
|
|
|
|
|
(defmacro infix [form]
|
|
|
|
(list (second form) (first form) (nth form 2)))
|
|
|
|
|
|
|
|
(defmacro infix-better [form]
|
2011-02-08 13:51:41 +00:00
|
|
|
`(~(second form) ; Note the syntax-quote (`) and unquote (~) characters!
|
2011-02-08 11:51:11 +00:00
|
|
|
__
|
|
|
|
__ ))
|
|
|
|
|
|
|
|
(defmacro r-infix [form]
|
2011-02-08 13:46:48 +00:00
|
|
|
(cond (not (seq? form))
|
2011-10-26 02:55:54 +00:00
|
|
|
__
|
2011-02-08 13:46:48 +00:00
|
|
|
(= 1 (count form))
|
2011-10-26 02:55:54 +00:00
|
|
|
`(r-infix ~(first form))
|
2011-02-08 13:46:48 +00:00
|
|
|
:else
|
2011-10-26 02:55:54 +00:00
|
|
|
(let [operator (second form)
|
|
|
|
first-arg (first form)
|
|
|
|
others __]
|
|
|
|
`(~operator
|
|
|
|
(r-infix ~first-arg)
|
|
|
|
(r-infix ~others)))))
|
2011-02-08 11:51:11 +00:00
|
|
|
|
|
|
|
(meditations
|
2011-02-14 01:53:25 +00:00
|
|
|
"Macros are like functions created at compile time"
|
|
|
|
(= __ (hello "Macros!"))
|
2011-02-08 13:20:38 +00:00
|
|
|
|
2013-01-05 21:18:45 +00:00
|
|
|
"I can haz infix?"
|
2011-02-14 01:53:25 +00:00
|
|
|
(= __ (infix (9 + 1)))
|
2011-02-08 13:20:38 +00:00
|
|
|
|
2011-02-14 01:53:25 +00:00
|
|
|
"Remember, these are nothing but code transformations"
|
|
|
|
(= __ (macroexpand '(infix (9 + 1))))
|
2011-02-08 11:51:11 +00:00
|
|
|
|
2013-01-05 21:18:45 +00:00
|
|
|
"You can do better than that - hand crafting FTW!"
|
2011-02-14 01:53:25 +00:00
|
|
|
(= __ (macroexpand '(infix-better (10 * 2))))
|
2011-02-08 13:20:38 +00:00
|
|
|
|
2013-01-05 21:18:45 +00:00
|
|
|
"Things don't always work as you would like them to... "
|
2011-02-14 01:53:25 +00:00
|
|
|
(= __ (macroexpand '(infix-better ( 10 + (2 * 3)))))
|
2011-02-08 11:51:11 +00:00
|
|
|
|
2013-01-05 21:18:45 +00:00
|
|
|
"Really, you don't understand recursion until you understand recursion"
|
2011-02-14 01:53:25 +00:00
|
|
|
(= 36 (r-infix (10 + (2 * 3) + (4 * 5)))))
|