Where do you use macros in clojure where functions wont work -


i'm new in learning , working clojure i've got basic question on macros in clojure. didn't find case need macros i'm wondering if there real case macro , no normal function or multimethod solves problem.

can show simple example this? think didn't understand concept of macros in clojure.

clojure macros take literal code whereas functions take evaluated code. in turn, macros useful when need manipulate literal code. literal code , evaluated code equivalent except 2 (very important) instances: symbols , expressions (maps, vectors, sets, strings, keywords, numbers, booleans, etcetera, "evalute themselves").

user=> 1 ;evaluates 1 user=> "abc" ;evaluates "abc" user=> :xyz ;evaluates :xyz user=> [1 "abc" :xyz] ;evaluates [1 "abc" :xyz] 

as opposed to:

user=> (+ 1 2) ;an expression evaluates not 3 user=> math/pi ;a symbol evaluates not 3.141592653589793 user=> + ;another example, little weirder #<core$_plus_ clojure.core$_plus_@417ffb28> 

let's wanted create some-fn-or-macro behave this:

user=> (some-fn-or-macro (get {:a 10 :b 20} :a)) "(get {:a 10 :b 20} :a)" user=> (some-fn-or-macro +) "+" 

you not able function. try it:

user=> (defn some-fn-or-macro [expr] (str expr)) #'user/some-fn-or-macro user=> (some-fn-or-macro (get {:a 10 :b 20} :a)) "10" 

what happened here? argument some-fn-or-macro (namely expr) got evaluated prior being string-ized. however, if change definition function macro, great:

user=> (defmacro some-fn-or-macro [expr] (str expr)) #'user/some-fn-or-macro user=> (some-fn-or-macro (get {:a 10 :b 20} :a)) "(get {:a 10 :b 20} :a)" 

that being said, if take original function definition again, , quote argument on invocation, works:

user=> (defn some-fn-or-macro [expr] (str expr)) #'user/some-fn-or-macro user=> (some-fn-or-macro '(get {:a 10 :b 20} :a)) "(get {:a 10 :b 20} :a)" 

so ever need write macro if use-case demands arguments remain literal/unevaluated. if have control on how tool used (which i'm guessing marginally true), can decide develop function, , instruct users quote arguments necessary.

***note: how i've used macros above might leave in dark 1 extremely important fact of macros: output gets evaluated. example:

user=> (defmacro example-macro [] '(+ 1 2)) #'user/example-macro user=> (example-macro) 3 

you might think odd. there couple ways make sense of it. macros expect take source code input, it's natural they'd give source code output--and source code demands evaluation @ point. actually, tend think of difference between macros , functions "shifted evaluation"--evaluation happens either "before" invocation, on arguments (for functions); or "after" invocation, on output (for macros).


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -