Some vector functions

Here are a couple of vector functions.

When you use “map” on a vector, you get a list back.

user.core=> (map inc [1 2 3])
(2 3 4)
user.core=> (class (map inc [1 2 3]))
clojure.lang.LazySeq

It acts like a list (because for lists “conj” adds at the front; for vectors it adds at the end).

user.core=> (conj (map inc [1 2 3]) 5)
(5 2 3 4)

Calling “vector” on it gives you a vector with a list inside it.

user.core=> (vector (map inc [1 2 3]))
[(2 3 4)]

So call “vec” on the result to make it a vector.

user.core=> (vec (map inc [1 2 3]))
[2 3 4]

“vector” can take elements directly.

user.core=> (vector 1 2 3)
[1 2 3]

“vec” must take a collection.

user.core=> (vec 1 2 3)
ArityException Wrong number of args (3) passed to: core/vec clojure.lang.AFn.throwArity (AFn.java:429)

user.core=> (vec '(1 2 3))
[1 2 3]

user.core=> (vec #{1 2 3})
[1 3 2]

Same with “set”.

user.core=> (set 1 2 3)

ArityException Wrong number of args (3) passed to: core/set clojure.lang.AFn.throwArity (AFn.java:429)
user.core=> (vec #{1 2 3} 'a)

ArityException Wrong number of args (2) passed to: core/vec clojure.lang.AFn.throwArity (AFn.java:429)
user.core=> (vec #{1 2 3} '(:a :b "hello"))

ArityException Wrong number of args (2) passed to: core/vec clojure.lang.AFn.throwArity (AFn.java:429)

You’re welcome.

There are 192 words in this article.