Blacksad
Blacksad

Reputation: 15422

Clojure list vs. vector vs. set

I'm new to Clojure. Apologies if it's a stupid question!

Should I use a set instead of a vector or list each time I don't care about the order of the items? What is the common criteria to decide between these three when order is not necessary?

Upvotes: 18

Views: 3567

Answers (3)

HD.
HD.

Reputation: 2155

Yes, use a set. Unless you have very, very good reasons to pick something else (performance, memory use, ...) the set is the correct choice.

Remember that programming is primarily about communicating with the human reader of your code and not with the computer. By using a set you make it totally clear that the order of elements is irrelevant (and you are not expecting duplicate values) helping the reader understand your intentions and your own mental mind set.

Upvotes: 3

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

It really depends on how you will be using the items.

  • If you will be searching for items, use a set.
  • If you will be processing it sequentially use a list.
  • If you will be chopping it into even sized chunks (like while sorting) use a vector.
  • If you need to count the length use a vector.
  • If you will be typing these by hand use a vector (to save a little quoting)

In practice most of the processing I see involves turning the data into a seq and processing that so the distinctions between list and vector are often a matter personal taste.

Upvotes: 21

Chuck
Chuck

Reputation: 237060

In general, you want a set when your primary concern is "Is this thing in this group?" Besides not preserving order, sets also only hold a given value once. So if you care about the precise placement of values, a vector is more what you want. If you mainly care about testing for membership, a set is more appropriate.

Upvotes: 9

Related Questions