Differences between seq and list

What are the differences between sections and lists in Clojure?

(list [1 2 3]) => ([1 2 3])
(seq [1 2 3]) => ([1 2 3])

These two forms are apparently evaluated as the same results.

+4
source share
3 answers

First of all, they may seem the same, but this is not the case:

(class (list [1 2 3])) => clojure.lang.PersistentList
(class (seq [1 2 3])) => clojure.lang.PersistentVector$ChunkedSeq

listusually an implementation, while seqalways an abstraction.

The differences between sections and lists are in the following three aspects, as outlined in Clojure Programming

1. getting the seq length can be expensive:

eg. 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

, . seq , count.

2. seqs , .

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

3. seqs , , .

, seqs ( ):

(class (seq '(1 2 3))) => clojure.lang.PersistentList

seq cons. cons conj.

+11

Lists - , . ( - , .)

Sequences - , . , - .

- , , . , , , (, clojure.lang.PersistentVector $ChunkedSeq).

, ( ) ( "" , , ). conj, assoc, count, get .. map, reduce, filter .. , , .

- , Clojure FP . , Clojure.

+6

In response to Albus Shin's answer ...

A list is one type of sequence among several. You do not see any difference between the two, because Clojure prints them the same way. Here are a few (with a vector cast for good measure):

=> (map (juxt identity seq? type)
     [(range 1 4)
      (take 3 (iterate inc 1))
      (list 1 2 3)
      (conj (list 2 3) 1)
      (cons 1 (list 2 3))
      [1 2 3]
      (seq [1 2 3])])

produces ...

([(1 2 3) true clojure.lang.LazySeq]
 [(1 2 3) true clojure.lang.LazySeq]
 [(1 2 3) true clojure.lang.PersistentList]
 [(1 2 3) true clojure.lang.PersistentList]
 [(1 2 3) true clojure.lang.Cons]
 [[1 2 3] false clojure.lang.PersistentVector]
 [(1 2 3) true clojure.lang.PersistentVector$ChunkedSeq])
+1
source

Source: https://habr.com/ru/post/1531863/


All Articles