Clojure macro to return two or more s-expressions

Is there a way in Clojure to write a macro (or use an existing one) that returns two or more s-expressions?

Example. Let's say I'm trying to create the first 10 squares:

(map * (range 10) (range 10))

Now I want to try and use repeat so that later I can provide power (2 at the moment) as a parameter:

(map * (repeat 2 (range 10)))

However, the above does not work as repeat returns a single s-expression with two ranges, not two ranges.

Please do not provide alternative implementations of the "return the first 10 squares" function. I am interested in idiomatic ways to solve such situations or generally applicable workarounds.

I assume that I am looking for a way to implement explode below:

(explode '( a b c )) ;; evals to a b c
(map * (explode (repeat 2 (range 10)))
+5
source share
2 answers

One macro cannot do this.

A macro is a function that takes an s-expression and converts it to another s-expression. Inputs can be any sequence of expressions (characters, primitives, other expressions, etc.) and the output is one expression that is inserted instead of the original macro call.

generally a macro would have to surround the call to display and transform the whole form

(your-macro-here (map * (repeat 2 (range 10))))

: , , , , , , , . , .

+4

, , , . , , .

, , . , do:

(defmacro defn-foos [& foos]
  `(do ~@(map (fn [foo] `(defn ~foo [])) foos)))

(defn-foos my-fn-1 my-fn-2)
;; expands as:
;; (do (defn my-fn-1 [])
;;     (defn my-fn-2 []))

, , - , , list, apply, .

, , , apply:

(apply map * (repeat 2 (range 10)))
+2

All Articles