Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most idiomatic way to pass vectors in for var-args in clojure?

Tags:

clojure

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?

like image 224
Rob Lachlan Avatar asked Jul 01 '10 18:07

Rob Lachlan


1 Answers

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]
like image 86
Brian Carper Avatar answered Sep 24 '22 00:09

Brian Carper