序列和列表之间的区别 [英] Differences between a seq and a list

查看:1682
本文介绍了序列和列表之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clojure语言中的seq和列表之间有什么区别?

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.

推荐答案

首先,它们似乎是相同的,但事实并非如此:

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通常是一种实现,而seq始终是一种抽象.

list is usually an implementation, whereas seq is always an abstraction.

seq和列表之间的区别在于以下三个方面,如 Clojure编程

The differences between seqs and lists lies in the following three aspects, as pointed out in Clojure Programming

例如来自 Clojure编程

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

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"

3. seqs可以是无限的,因此是不可数的,而列表始终是可数的.

此外,列表是它们自己的seq(实现细节):

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

始终可以使用cons创建一个序列.在此帖子中查看更多信息,以了解cons.

One can always create a seq using cons. Check out more information in this post for differences between cons and conj.

这篇关于序列和列表之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆