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?
A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.
List is a structure used to store a collection of data items. In Clojure, the List implements the ISeq interface. Lists are created in Clojure by using the list function.
Clojure collections "collect" values into compound values. There are four key Clojure collection types: vectors, lists, sets, and maps. Of those four collection types, vectors and lists are ordered.
It really depends on how you will be using the items.
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.
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.
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.
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