What is the difference between defn and defmacro?

后端 未结 5 1391
青春惊慌失措
青春惊慌失措 2021-02-01 02:25

What is the difference between defn and defmacro? What is the difference between a function and a macro?

5条回答
  •  执念已碎
    2021-02-01 03:24

    Without sounding snarky, one creates a function, while the other creates a macro. In Common Lisp (and I'll assume this applies to clojure as well), Macros are expanded before actual compilation of functions. So, lazy-cat:

    (defmacro lazy-cat
      "Expands to code which yields a lazy sequence of the concatenation
      of the supplied colls. Each coll expr is not evaluated until it is
      needed.
    
      (lazy-cat xs ys zs) === (concat (lazy-seq xs) (lazy-seq ys) (lazy-seq zs))"
      {:added "1.0"}
      [& colls]
      `(concat ~@(map #(list `lazy-seq %) colls)))
    

    Will actually be expanded to

    `(concat ~@(map #(list `lazy-seq %) colls)))
    

    of which lazy-seq will then be further expanded to

    (list 'new 'clojure.lang.LazySeq (list* '^{:once true} fn* [] body)))
    

    all before the actually processing of the data passed to them.

    There's a very cute story that helps explain the difference (followed by some informative examples) at Practical Common Lisp: Chapter 8

提交回复
热议问题