Is it possible to create a new var with metadata without going through an "intermediate" var?
In other words, I know I can do the following:
(def a-var 2)
(def another-var (with-meta a-var {:foo :bar}))
but is there any way to create another-var
without creating a-var
first?
In Clojure, variables are defined by the 'def' keyword. It's a bit different wherein the concept of variables has more to do with binding. In Clojure, a value is bound to a variable.
List is a structure used to store a collection of data items. In Clojure, the List implements the ISeq interface. Lists are created in Clojure by using the list function.
binding => var-symbol init-expr Creates new bindings for the (already-existing) vars, with the supplied initial values, executes the exprs in an implicit do, then re-establishes the bindings that existed before.
def is a special form that associates a symbol (x) in the current namespace with a value (7). This linkage is called a var . In most actual Clojure code, vars should refer to either a constant value or a function, but it's common to define and re-define them for convenience when working at the REPL.
Like this:
user> (def ^{:foo :bar} another-var 2)
#'user/another-var
user> (clojure.pprint/pprint (meta #'another-var))
{:ns #<Namespace user>,
:name another-var,
:file "NO_SOURCE_FILE",
:line 1,
:foo :bar}
nil
Also note, that (def another-var (with-meta a-var {:foo :bar}))
does not attach the metadata to the Var, but to the value. And since in your example a-var
holds an Integer, I wouldn't expect your example to work at all, since Integers can't hold metadata.
user=> (def a-var 2)
#'user/a-var
user=> (def another-var (with-meta a-var {:foo :bar}))
java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.IObj (NO_SOURCE_FILE:2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With