Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure vars with metadata

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?

like image 314
Ralph Avatar asked Nov 18 '10 01:11

Ralph


People also ask

How do you define a variable in Clojure?

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.

How do you define a list in Clojure?

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.

What is binding in Clojure?

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.

What is def Clojure?

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.


2 Answers

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
like image 188
harto Avatar answered Sep 21 '22 17:09

harto


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)
like image 44
kotarak Avatar answered Sep 22 '22 17:09

kotarak