Explain thread first macro like i am 5?

hi guys, as i’m trying to understand how macro works through thread first -> source. could you pls explain what this line does

(with-meta '(~(first form) ~x ~@(next form)) (meta form))

im also curious about the use of with-meta and meta in this macro definition

1 Like

First, quote and syntax-quote

I think you’ll want syntax-quote and not quote:

' (quote)
` (syntax-quote)

The syntax quote “lets you put things inside it” with ~ (“insert one element”) and ~@ (“insert many elements”)

Second, metadata.

;; When you define Clojure var, metadata is attached.

(def g
  "gravitational accelleration in m/s2"

;; If we just evaluate g and ask for meta, we get nothing, since we evaluated.

(meta g)
;; => nil

;; If we ask for the "reference to g", we'll get the metadata
(meta #'g)
;; => {:line 7,
;;     :column 1,
;;     :file
;;     "/home/teodorlu/sandbox/clojure/scratch/src/th/scratch/rnd_2020_04_30.clj",
;;     :doc "gravitational accelleration in m/s2",
;;     :name g,
;;     :ns #namespace[th.scratch.rnd-2020-04-30]}

You can attach your own metadata using with-meta

(let [eggs (with-meta {:eggs/count 3} {:doc "Please don't break them!"})]
;; => #:eggs{:count 3}

(let [eggs (with-meta {:eggs/count 3} {:doc "Please don't break them!"})]
  (meta eggs))
;; => {:doc "Please don't break them!"}

Does that clear up any confusion?

1 Like

tks u for your explanation, after doing further research from here, i came to understand that this also preserve form metadata. by saying preserve, could you pls tell me more about metadata use cases?

1 Like

Metadata is attached to objects supporting it, but in Clojure, since you don’t mutate arguments, you often return a modified new object from an existing one. The new modified object will have the metadata from the original one only if the macro or function you used to modify it preserves metadata. That means that it copies over the metadata from the original object to the returned one.


tks u all for your help. i could understand it now :+1::heart:

1 Like

You’ve been asking good questions :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.