Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure 按整数序列划分_Clojure - Fatal编程技术网

Clojure 按整数序列划分

Clojure 按整数序列划分,clojure,Clojure,根据一个整数序列而不是仅仅一个整数来划分一个序列的更惯用的方法是什么 以下是我的实现: (defn partition-by-seq "Return a lazy sequence of lists with a variable number of items each determined by the n in ncoll. Extra values in coll are dropped." [ncoll coll] (let [partition-coll (mapc

根据一个整数序列而不是仅仅一个整数来划分一个序列的更惯用的方法是什么

以下是我的实现:

(defn partition-by-seq
  "Return a lazy sequence of lists with a variable number of items each
  determined by the n in ncoll.  Extra values in coll are dropped."
  [ncoll coll]
  (let [partition-coll (mapcat #(repeat % %) ncoll)]
    (->> coll
         (map vector partition-coll)
         (partition-by first)
         (map (partial map last)))))

然后
(按seq[2 3 6](range))进行分区
生成
((01)(2 3 4)(5 6 7 8 9 10))

您的实现看起来不错,但是可能有一个更简单的解决方案,它使用简单的递归封装在
惰性seq
中(结果证明比使用map和现有的分区更有效)

(defn partition-by-seq [ncoll coll]
  (if (empty? ncoll)
    '()
    (let [n (first ncoll)]
      (cons (take n coll)
            (lazy-seq (partition-by-seq (rest ncoll) (drop n coll)))))))

Ankur答案的一个变体,在let
而不是显式测试
为空时,稍微增加了惰性和

 (defn partition-by-seq [parts coll]
    (lazy-seq
      (when-let [s (seq parts)]
        (cons
          (take (first s) coll)
          (partition-by-seq (rest s) (nthrest coll (first s)))))))

通过在
cons
之外使用
lazy seq
,这可能会变得更加懒惰,因此即使是第一个
(take n coll)
也不会被急切地评估。我喜欢在let
中使用
,因为(cons x nil)只是(x),并且发现它比“if”版本干净得多。为什么使用
nthrest
而不是
drop
?看起来内部可能是
(当让[n(第一部分)](cons(take n coll)(按seq划分)(rest parts)(drop n coll)))
@tobereplace
nthrests
只是
drop
急切地下降,我认为在这种情况下是合适的。再想一想,我不确定这是否重要。实际上,当let
时,
第一个
可以在
内移动。
 (defn partition-by-seq [parts coll]
    (lazy-seq
      (when-let [s (seq parts)]
        (cons
          (take (first s) coll)
          (partition-by-seq (rest s) (nthrest coll (first s)))))))