What is the vary-meta method in Clojure?

What is metadata?

Metadata is data about data. This means that metadata is a description of another data, but not the content of the data itself.

What is the vary-meta method?

The vary-meta method is used to get both the original object and its associated metadata.

Syntax

(vary-meta obj newmeta)
Syntax for vary-meta method in Clojure

Parameter

From the syntax above, we can deduce that we have two parameters.

  1. obj: This is the object we check for associated metadata.
  2. newmeta: These are the values of the metadata that need to be attached to the object.

Return value

The vary-meta method returns the same object with combined metadata.

Example

Let's look at an example.

(ns clojure.examples.example
(:gen-class))
(defn metta []
(def d-map (with-meta [3 9 8] {:prop "First values"}))
(println (meta d-map))
(def n-map (vary-meta d-map assoc :newprop "Second values"))
(println (meta n-map)))
(metta)

Explanation

Line 3: We define a function metta.

Line 4: We define an object and attach a meta data {:prop "values"} data using the with-meta method.

Line 5: We print the metadata returned using the println. We use the meta method to get the metadata of the object.

Line 6: We add new metadata vary-meta d-map assoc :newprop "Second values" to the initially created object using the vary-meta method. We save it to the n-map variable.

Line 7: We print the object with is combined metadata returned using the println. Using the meta method, we get the metadata of the object.

Line 8: We call the metta function.

Free Resources