Constant definition in Clojure - macros

I'm trying to define a macro for defining compile-time constants syntax for which was added in Clojure 1.3:
== 2.14 ^:const defs ==
^:const lets you name primitive values with speedier reference.
(def constants {:pi 3.14 :e 2.71})
(def ^:const pi (:pi constants)) (def ^:const e (:e constants))
The overhead of looking up :e and :pi in the map happens at compile
time, as (:pi constants) and (:e constants) are evaluated when their
parent def forms are evaluated.
Basically I want some syntax sugar around (def ^:const ... ...), so I'm trying to do it like this:
(defmacro defconst [const-name const-val]
`(def ^:const ~const-name ~const-val))
But this doesn't work:
user=> (macroexpand '(defconst pi 3.14))
(def pi 3.14)
From what I gather the #^<...> meta shortcut is a reader macro, and to define a macro that adds some metadata to something, one should use (with-meta ...).
I haven't found any documentation regarding ^:const. Does this syntactical construct even create some sort of metadata? Following example doesn't show any:
user=> (def ^:const pi 3.14)
#'user/pi
user=> (meta pi)
nil

The first issue is that you are examining the metadata of 3.14. Use (meta (var pi)) to see the metadata of pi. If you do, you will see that it includes :const true.
(defmacro defconst [const-name const-val]
`(def
~(with-meta const-name
(assoc (meta const-name) :const true))
~const-val))
accurately reproduces the metadata and performance of ^:const (the code is adapted from the source of defn-).

Related

How do defines and syntax macros interact in Racket?

I'm new to Racket and there's something about syntax macros I don't understand. I have these two programs:
This one, which executes correctly:
#lang racket
(define-syntax-rule (create name) (define name 2))
(create x)
(displayln (+ x 3))
And this one, which complains that the identifier x is unbound:
#lang racket
(define-syntax-rule (create) (define x 2))
(create)
(displayln (+ x 3))
With a naive substitution approach (such as C/C++ macros) these two programs would behave identically, but evidently they do not. It seems that identifiers that appear in the invocation of a syntax macro are somehow "special" and defines that use them behave differently to defines that do not. Additionally, there is the struct syntax macro in the Racket standard library which defines several variables that are not explicitly named in its invocation, for example:
(struct employee (first-name last-name))
Will define employee? and employee-first-name, neither of which were directly named in the invocation.
What is going on here, and it can be worked around so that I could create a custom version of struct?
The problem with the naive substitution is unintentional capturing. Racket macros by default are hygienic, which means it avoid this problem. See https://en.wikipedia.org/wiki/Hygienic_macro for more details.
That being said, the macro system supports unhygienic macros too. struct is an example of an unhygienic macro. But you need to put a bit more effort to get unhygienic macros working.
For example, your second version of create could be written as follows:
#lang racket
(require syntax/parse/define)
(define-syntax-parse-rule (create)
#:with x (datum->syntax this-syntax 'x)
(define x 2))
(create)
(displayln (+ x 3))

Where do you use macros in clojure where functions wont work

I'm new in learning and working with clojure so I've got a basic question on macros in clojure. I didn't find a case where you really need macros so I'm wondering if there is a real case where only a macro and no normal function or multimethod solves your problem.
Can someone show a simple example for this?
I think I didn't understand the concept of macros in clojure.
Clojure macros take literal code whereas functions take evaluated code. In turn, macros are useful when you need to manipulate literal code. Literal code and evaluated code are equivalent except for two (very important) instances: symbols and expressions (maps, vectors, sets, strings, keywords, numbers, booleans, etcetera, will all "evalute to themselves").
user=> 1 ;evaluates to itself
1
user=> "abc" ;evaluates to itself
"abc"
user=> :xyz ;evaluates to itself
:xyz
user=> [1 "abc" :xyz] ;evaluates to itself
[1 "abc" :xyz]
As opposed to:
user=> (+ 1 2) ;an expression evaluates to not itself
3
user=> Math/PI ;a symbol evaluates to not itself
3.141592653589793
user=> + ;another example, a little weirder
#<core$_PLUS_ clojure.core$_PLUS_#417ffb28>
Let's say you wanted to create some-fn-or-macro to behave like this:
user=> (some-fn-or-macro (get {:a 10 :b 20} :a))
"(get {:a 10 :b 20} :a)"
user=> (some-fn-or-macro +)
"+"
You will not be able to do this with a 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? The argument to some-fn-or-macro (namely expr) got evaluated prior to being string-ized. However, if all we do is change the definition from a function to a macro, everything will be 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 we take the original function definition again, and simply quote the argument on invocation, that also 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 you only ever need to write a macro if your use-case demands that arguments remain literal/unevaluated. If you have control over how your tool is used (which I'm guessing is always marginally true), you can decide to develop a function, and instruct users to quote arguments as necessary.
***Note: How I've used macros above might leave you in the dark about one extremely important fact of macros: their output gets evaluated. For example:
user=> (defmacro example-macro [] '(+ 1 2))
#'user/example-macro
user=> (example-macro)
3
You might think this is odd. There are a couple ways to make sense of it. Macros expect to take source code as input, so it's only natural that they'd give source code as output--and source code demands evaluation at some point. Actually, I tend to think of the difference between macros and functions as "shifted evaluation"--evaluation happens either "before" invocation, on the arguments (for functions); or "after" invocation, on the output (for macros).
Important thing here is that macro does not evaluate its arguments and can be used for arbitrary transformation of source code.
Most basic examples of macros would be when and when-not macros:
(defmacro when
"Evaluates test. If logical true, evaluates body in an implicit do."
[test & body]
`(if ~test (do ~#body)))
(defmacro when-not
"Evaluates test. If logical false, evaluates body in an implicit do."
[test & body]
`(if test nil (do ~#body)))
Function won't work here, as it has to evaluate all its arguments before execution.
P.S. If you're interested in the topic and want to know more, see also this my answer. It is about Common Lisp, but it could be useful for you too. I also give a link to a cool Paul Graham's article at the end of the answer.
P.S.S If you want an example of a new useful macro, I would like to comment something of Paul Graham here:
It would be convenient here if I could give an example of a powerful macro, and say there! how about that? But if I did, it would just look like gibberish to someone who didn't know Lisp; there isn't room here to explain everything you'd need to know to understand what it meant.

What is the proper way to construct a clojure macro from lists of symbols?

Imagine the following code to dynamically create a macro:
(def a (list '+ 1 2))
(def b (list '- 10 5))
(def c (list '/ 22 2))
(defmacro gg [h]
(let [k# `~h]
k#))
The intent is to pass a vector of symbols to a macro, do some evaluation on each element of the vector such that it returns a nice macro-esque form, then have the macro combine them into a nice macro and evaluate it. The above example works all except the actual evaluation.
When I run it I get:
(gg [a b c])
=> [(+ 1 2) (- 10 5) (/ 22 2)]
What is the secret to passing a symbol that is a list of symbols and getting a macro to evaluate them? I have tried lots of combinations of quoting and have yet to hit the right one.
The real purpose of this question is to build an Archimedes Ogre query based on a definition of a path through the graph. If someone has an example of that, I would be grateful.
EDIT:
(defmacro gg2 [h]
`(do ~#(map identity h)))
(macroexpand '(gg2 [a b c]))
=> (do a b c)
(gg2 [a b c])
=> (/ 22 2)
I was hoping to get 11 rather than the form.
You don't need a macro. Macros don't do what you're looking for here. What you are looking for is eval.
(def a '/)
(def b 22)
(def c 2)
(eval (list* [a b c]))
=> 11
Of course, you can write a macro which expands into (eval (list* ...)) if you want. It could just as well be a function though.
This is a very common mistake when starting out with macros; trying to write a macro which depends on the run-time value of its arguments. Macros run at compile-time, and generally the values of the symbols which you pass to a macro are not yet available when the macro is expanded.
About the use of eval, some cautions are in order. No one said it better than Paul Graham:
Generally it is not a good idea to call eval at runtime, for two reasons:
It’s inefficient: eval is handed a raw list, and either has to compile it on the spot, or evaluate it in an interpreter. Either way is slower than compiling the code beforehand, and just calling it.
It’s less powerful, because the expression is evaluated with no lexical context. Among other things, this means that you can’t refer to ordinary variables visible outside the expression being evaluated.
Usually, calling eval explicitly is like buying something in an airport gift-shop. Having waited till the last moment, you have to pay high prices for a limited selection of second-rate goods.

Splicing unquote for non-literal sequences

This question is a based on a limitation of this answer.
If I have a macro that uses splicing unquote like this:
(defmacro instantiate [klass values]
`(new ~klass ~#values))
It will only work if values is a literal sequence or seq-able.
If it is passed a var holding a sequence like:
(def v [1 2 3])
(macroexpand '(instantiate Person v))
Then the output would be an error indicating that v is not a sequence.
Even a function call would be interpreted as a list:
(defn vf [] [1 2 3])
(macroexpand '(instantiate Person (vf)))
user=>(new Person vf)
My question is: Is there any way to use the splicing unquote in Clojure macros in those two cases where the sequence to be spliced isn't a literal?
Macros receive their arguments unevaluated, so the behavior you are seeing is as intended.
Macros are expanded at compile time, not run time. The values of any variables passed into a macro may not be available at compile time, so dirty hacks like using eval will not work in the general case. Don't create macros that require such tricks.
splicing quotes save a lot of time in almost all cases, except when they dont work, then you need to do things the old fashioned way...
(defmacro instantiate [klass values]
`(new ~klass ~#values))
could become
(defmacro instantiate [klass values]
(concat (list 'new klass) (if (seq? values)
values
(list values))))
user=> (macroexpand '(instantiate asdf (1 2 3)))
(new asdf 1 2 3)
user=> (macroexpand '(instantiate asdf 1))
(new asdf 1)

Use a clojure macro to automatically create getters and setters inside a reify call

I am trying to implement a huge Java interface with numerous (~50) getter and setter methods (some with irregular names). I thought it would be nice to use a macro to reduce the amount of code. So instead of
(def data (atom {:x nil}))
(reify HugeInterface
(getX [this] (:x #data))
(setX [this v] (swap! data assoc :x v)))
I want to be able to write
(def data (atom {:x nil}))
(reify HugeInterface
(set-and-get getX setX :x))
Is this set-and-get macro (or something similar) possible? I haven't been able to make it work.
(Updated with a second approach -- see below the second horizontal rule -- as well as some explanatory remarks re: the first one.)
I wonder if this might be a step in the right direction:
(defmacro reify-from-maps [iface implicits-map emit-map & ms]
`(reify ~iface
~#(apply concat
(for [[mname & args :as m] ms]
(if-let [emit ((keyword mname) emit-map)]
(apply emit implicits-map args)
[m])))))
(def emit-atom-g&ss
{:set-and-get (fn [implicits-map gname sname k]
[`(~gname [~'this] (~k #~(:atom-name implicits-map)))
`(~sname [~'this ~'v]
(swap! ~(:atom-name implicits-map) assoc ~k ~'v))])})
(defmacro atom-bean [iface a & ms]
`(reify-from-maps ~iface {:atom-name ~a} ~emit-atom-g&ss ~#ms))
NB. that the atom-bean macro passes the actual compile-time value of emit-atom-g&ss on to reify-from-maps. Once a particular atom-bean form is compiled, any subsequent changes to emit-atom-g&ss have no effect on the behaviour of the created object.
An example macroexpansion from the REPL (with some line breaks and indentation added for clarity):
user> (-> '(atom-bean HugeInterface data
(set-and-get setX getX :x))
macroexpand-1
macroexpand-1)
(clojure.core/reify HugeInterface
(setX [this] (:x (clojure.core/deref data)))
(getX [this v] (clojure.core/swap! data clojure.core/assoc :x v)))
Two macroexpand-1s are necessary, because atom-bean is a macro which expands to a further macro call. macroexpand would not be particularly useful, as it would expand this all the way to a call to reify*, the implementation detail behind reify.
The idea here is that you can supply an emit-map like emit-atom-g&ss above, keyed by keywords whose names (in symbolic form) will trigger magic method generation in reify-from-maps calls. The magic is performed by the functions stored as functions in the given emit-map; the arguments to the functions are a map of "implicits" (basically any and all information which should be accessible to all method definitions in a reify-from-maps form, like the name of the atom in this particular case) followed by whichever arguments were given to the "magic method specifier" in the reify-from-maps form. As mentioned above, reify-from-maps needs to see an actual keyword -> function map, not its symbolic name; so, it's only really usable with literal maps, inside other macros or with help of eval.
Normal method definitions can still be included and will be treated as in a regular reify form, provided keys matching their names do not occur in the emit-map. The emit functions must return seqables (e.g. vectors) of method definitions in the format expected by reify: in this way, the case with multiple method definitions returned for one "magic method specifier" is relatively simple. If the iface argument were replaced with ifaces and ~iface with ~#ifaces in reify-from-maps' body, multiple interfaces could be specified for implementation.
Here's another approach, possibly easier to reason about:
(defn compile-atom-bean-converter [ifaces get-set-map]
(eval
(let [asym (gensym)]
`(fn [~asym]
(reify ~#ifaces
~#(apply concat
(for [[k [g s]] get-set-map]
[`(~g [~'this] (~k #~asym))
`(~s [~'this ~'v]
(swap! ~asym assoc ~k ~'v))])))))))
This calls on the compiler at runtime, which is somewhat expensive, but only needs to be done once per set of interfaces to be implemented. The result is a function which takes an atom as an argument and reifies a wrapper around the atom implementing the given interfaces with getters and setters as specified in the get-set-map argument. (Written this way, this is less flexible than the previous approach, but most of the code above could be reused here.)
Here's a sample interface and a getter/setter map:
(definterface IFunky
(getFoo [])
(^void setFoo [v])
(getFunkyBar [])
(^void setWeirdBar [v]))
(def gsm
'{:foo [getFoo setFoo]
:bar [getFunkyBar setWeirdBar]})
And some REPL interactions:
user> (def data {:foo 1 :bar 2})
#'user/data
user> (def atom-bean-converter (compile-atom-bean-converter '[IFunky] gsm))
#'user/atom-bean-converter
user> (def atom-bean (atom-bean-converter data))
#'user/atom-bean
user> (.setFoo data-bean 3)
nil
user> (.getFoo atom-bean)
3
user> (.getFunkyBar data-bean)
2
user> (.setWeirdBar data-bean 5)
nil
user> (.getFunkyBar data-bean)
5
The point is reify being a macro itself which is expanded before your own set-and-get macro - so the set-and-get approach doesn't work. So, instead of an inner macro inside reify, you need a macro on the "outside" that generates the reify, too.
Since the trick is to expand the body before reify sees it, a more general solution could be something along these lines:
(defmacro reify+ [& body]
`(reify ~#(map macroexpand-1 body)))
You can also try to force your macro to expand first:
(ns qqq (:use clojure.walk))
(defmacro expand-first [the-set & code] `(do ~#(prewalk #(if (and (list? %) (contains? the-set (first %))) (macroexpand-all %) %) code)))
(defmacro setter [setterf kw] `(~setterf [~'this ~'v] (swap! ~'data assoc ~kw ~'v)))
(defmacro getter [getterf kw] `(~getterf [~'this] (~kw #~'data)))
(expand-first #{setter getter}
(reify HugeInterface
(getter getX :x)
(setter setX :x)))