1

What's a good way to create a variadic 'for' in Clojure?

I wrote this out:

(defmacro variadic-for
  [f colls]
  (let [bindings (map (fn [coll] [(gensym) coll]) colls)]
    `(for ~(vec (apply concat bindings))
       (~f ~@(map first bindings)))))

So I can use this like:

(variadic-for + [[1] [2] [3 4]])

and the result will be every possible sum, where each given collection represents the possible values for that binding.

Is there a better way to do this? I don't know of anything in the Clojure core that is used to create all permutations in this way, other than 'for'.

1
  • Could you clarify the desired result? Is it [6 7]? Also, what is the use case? Commented Feb 2, 2022 at 20:56

2 Answers 2

3

Maybe cartesian-product from clojure.math.combinatorics?

(defn variadic-for [f colls]
  (map #(apply f %)
        (apply clojure.math.combinatorics/cartesian-product colls)))

(variadic-for + [[1] [2] [3 4]])
=> (6 7)
3

I think your macro implementation is great, but implementing it as a function has the advantage of increased composability. For instance, you can pass your variadic-for to a function. Here is an implementation of variadic-for as a function:

(defn combine2 [A B]
  (for [a A
        b B]
    (conj a b)))

(defn combinations [colls]
  (reduce combine2 [[]] colls))

(defn variadic-for [f colls]
  (map #(apply f %) (combinations colls)))

I believe there is already a combinations function in some library but implementing it yourself, as done above, is easy.

Here is something you cannot do if variadic-for is a macro:

(def combinatorial+ (partial variadic-for +))

(combinatorial+ [[1] [2] [3 4]])
;; => (6 7)
1
  • Identifying that 'combinations' is just left fold of combine2. Smart! Commented Feb 2, 2022 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.