Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure list vs. vector vs. set

Tags:

clojure

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?

like image 653
Blacksad Avatar asked Feb 02 '13 00:02

Blacksad


People also ask

What is a Clojure vector?

A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.

What is Clojure list?

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.

What is a collection in Clojure?

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.


3 Answers

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.

like image 108
Arthur Ulfeldt Avatar answered Oct 19 '22 07:10

Arthur Ulfeldt


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.

like image 40
Chuck Avatar answered Oct 19 '22 08:10

Chuck


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.

like image 3
HD. Avatar answered Oct 19 '22 08:10

HD.