2024 状态 Clojure 问卷! 认分享你的想法。

欢迎!请查看 关于 页面了解更多关于此功能的信息。

+12
Sequences
重新标记

在工作上,我们有一些需要交错延迟序列的情况,如果其中一个序列比另一个短,我们希望在交错完成后将较长的序列中的元素连接到较短的序列之后。

以下代码可用于 - 现有 interleave 函数的一个微小变体

(defn interleave-all
  "Like interleave, but stops when the longest seq is done, instead of
   the shortest."
  {:copyright "Rich Hickey, since this is a modified version of interleave"}
  ([] ())
  ([c1] (lazy-seq c1))
  ([c1 c2]
   (lazy-seq
    (let [s1 (seq c1) s2 (seq c2)]
      (cond
       (and s1 s2) ; there are elements left in both
       (cons (first s1) (cons (first s2)
                              (interleave-all (rest s1) (rest s2))))
       s1 ; s2 is done
       s1
       s2 ; s1 is done
       s2))))
  ([c1 c2 & colls]
   (lazy-seq
    (let [ss (filter identity (map seq (conj colls c2 c1)))]
      (concat (map first ss) (apply interleave-all (map rest ss)))))))

1 答案

+3

选中
...