Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between a seq and a list

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.

like image 919
albusshin Avatar asked Mar 14 '14 21:03

albusshin


People also ask

What is the difference between list and sequence in Python?

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.

Is sequence a list?

A sequence is a list of numbers in a certain order. Each number in a sequence is called a term .

What is the difference between sequence and list in Scala?

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.

What is the difference between sequence and an array in Python?

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.


1 Answers

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

1. getting the length of a seq can be costy:

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.

2. seqs can be lazy, whereas lists cannot.

 (class (range)) => clojure.lang.LazySeq
 (class (apply list (range))) ;cannot be evaluated
 ; "java.lang.OutOfMemoryError: GC overhead limit exceeded"

3. seqs can be infinite, thus uncountable, whereas lists are always countable.

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.

like image 153
albusshin Avatar answered Oct 19 '22 06:10

albusshin