2

Is there any (reasonable) way to write this macro as a function?

(defmacro assocTop
          [v & args]
          `(push (pop ~v)
                 (assoc (peek ~v) ~@args)))

Given a vector of maps and some associations, the macro code applies the associations to the top/peeked map.

However, when trying to write it as a function, I can't figure out how to expand the ~@args in a legitimate way. In normal functions, is there a way to turn args, which I believe has the form (:a 3 :bb 44 :cd 90,...) into :a 3 :bb 44 :cd 90,... ,i.e. without the parens?

1 Answer 1

5

I guess you should use apply which will apply assoc to (peek v) and expanded args.

(defn assocTop
  [v & args]
  (push (pop v)
        (apply assoc (peek v) args)))
(=
  (assocTop [{:a :b} {:c :d} {:e :f, :g :h}] :e :z)
  [{:a :b} {:c :d} {:g :h, :e :z}]) ; => true
Sign up to request clarification or add additional context in comments.

3 Comments

How come reduce doesn't work here but works with, say, (defn push [v & args] (reduce conj v args))?
@spacingissue, I don't see how do you want to use reduce in this case. Can you elaborate?
I guess I was thinking that applying assoc repeatedly on the answer would be the same as reduce. Is there a distinction to the push case (where you apply conj repeatedly on the answer)?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.