【问题标题】:What is the difference between seq and sequence in Clojure?Clojure中的seq和sequence有什么区别?
【发布时间】:2016-12-17 00:00:39
【问题描述】:

以下示例产生相同的输出。

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

(sequence [1 2 3 4])
=> (1 2 3 4)

【问题讨论】:

标签: clojure functional-programming lisp clojurescript


【解决方案1】:

不同之处在于 sequence 总是返回一个 seq 即使集合是空的(在这种情况下是一个空列表),而 seq 对于空集合返回 nil。此外,sequence 可以与transducers 一起使用。

查看源代码:

user=> (source sequence)
(defn sequence
  "Coerces coll to a (possibly empty) sequence, if it is not already
  one. Will not force a lazy seq. (sequence nil) yields (), ..."
  ([coll]
     (if (seq? coll) coll
         (or (seq coll) ())))
  ...

因此,如果集合还不是 seq,则仅使用集合调用 sequence 会在集合上调用 seq,如果集合是 nil,则返回空列表。

【讨论】:

    【解决方案2】:

    首先,它们对空序列参数的处理方式不同:

    user> (seq nil)
    nil
    user> (seq ())
    nil
    user> (sequence ())
    ()
    user> (sequence nil)
    ()
    

    sequence 还可以在传感器上进行操作

    截至文档:

    clojure.core/sequence

    [科尔]

    [xform coll]

    [xform coll & colls]

    在 1.0 中添加 强制 coll 到一个(可能是空的)序列,如果它还没有 一。不会强制执行惰性序列。 (sequence nil) 产生 (),当一个 提供了传感器,返回一个惰性的应用程序序列 对 coll(s) 中项目的转换,即转换为 first 的集合 每个 coll 的项目,然后是第二组 每个coll中的项目,直到用完任何一个coll。任何 其他 colls 中的剩余项目将被忽略。转换应该接受 colls 参数数

    clojure.core/seq

    [科尔]

    在 1.0 中添加 返回集合的序列。如果集合是 空,返回零。 (seq nil) 返回 nil。 seq 也适用于 字符串、本地 Java 数组(引用类型)和任何对象 实现Iterable。注意 seqs 缓存值,因此 seq 不应在其迭代器重复的任何 Iterable 上使用 返回相同的可变对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多