2024 年 Clojure 调查问卷 中分享您的看法!

欢迎!有关如何使用本网站的更多信息,请参阅 关于 页面。

+12
序列
再次标记

在工作中,我们有些情况下需要混合同步序列,如果某个序列比另一个短,我们希望在同步结束后将较长的序列的元素附加到较短序列的后面。

以下代码可以用来实现 -- 现有 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

选中
...