Suppose that I have a vector of key-value pairs that I want to put into a map.
(def v [k1 v1 k2 v2])
I do this sort of thing:
(apply assoc (cons my-map v))
And in fact, I've found myself doing this pattern,
(apply some-function (cons some-value some-seq))
several times in the past couple days. Is this idiomatic, or is there a nicer way to move arguments form sequences into functions?
apply
takes extra arguments between the function name and the last seq argument.
user> (doc apply)
-------------------------
clojure.core/apply
([f args* argseq])
Applies fn f to the argument list formed by prepending args to argseq.
That's what args*
means. So you can do this:
user> (apply assoc {} :foo :bar [:baz :quux])
{:baz :quux, :foo :bar}
user> (apply conj [] :foo :bar [:baz :quux])
[:foo :bar :baz :quux]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With