What's the differences between seqs and lists in Clojure language?
(list [1 2 3]) => ([1 2 3])
(seq [1 2 3]) => ([1 2 3])
These two forms seem to be evaluated as the same results.
In Python, sequence is the generic term for an ordered set. There are several types of sequences in Python, the following three are the most important. Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable - they can be changed.
A sequence is a list of numbers in a certain order. Each number in a sequence is called a term .
Sequence in Scala is a collection that stores elements in a fixed order. It is an indexed collection with 0 index. List is Scala is a collection that stores elements in the form of a linked list. Both are collections that can store data but the sequence has some additional features over the list.
6 Sequences, Arrays, and Vectors In other words, any list is a sequence, and any array is a sequence. The common property that all sequences have is that each is an ordered collection of elements. An array is a fixed-length object with a slot for each of its elements. All the elements are accessible in constant time.
First of all, they may seem to be the same, but they're not:
(class (list [1 2 3])) => clojure.lang.PersistentList
(class (seq [1 2 3])) => clojure.lang.PersistentVector$ChunkedSeq
list
is usually an implementation, whereas seq
is always an abstraction.
The differences between seqs and lists lies in the following three aspects, as pointed out in Clojure Programming
e.g. from Clojure Programming
(let [s (range 1e6)]
(time (count s))) => 1000000
; "Elapsed time: 147.661 msecs"
(let [s (apply list (range 1e6))]
(time (count s))) => 1000000
; "Elapsed time: 0.03 msecs
Because a list always holds a record of its own length, so the operation of counting a list costs constant time. A seq, however, needs to traverse itself to retrieve its count
.
(class (range)) => clojure.lang.LazySeq
(class (apply list (range))) ;cannot be evaluated
; "java.lang.OutOfMemoryError: GC overhead limit exceeded"
Also, lists are their own seqs (implementation details):
(class (seq '(1 2 3))) => clojure.lang.PersistentList
One can always create a seq using cons
. Check out more information in this post for differences between cons
and conj
.
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