在clojure中重新实现分区

Yar*_*Yar 1 clojure

我试图在clojure中找到一种实现分区(带[]填充)的方法.我认为使用循环并重复并将其映射到列表是可行的:

 (defn collect-h [v n]
   (loop [i n
          res []
          lst v
          ]
     (if (= 0 i)
       res
       (recur (dec i) (cons (first lst) res) (next lst))
       )
     )
   )
Run Code Online (Sandbox Code Playgroud)

所以问题是实现只适用于第一系列答案" (collect-h [1 2 3 4 5 6 7 8 9 10] 3)将给予((1 2 3))".所以我需要将它映射到整个集合并删除n每个循环中的第一个数字,但这看起来并不高效.我想知道是否有更好的方法来解决它.

编辑:

所以它应该像这样工作:

(collect-h [1 2 3 4 5 6 7 8 9 10] 3)                   ;; ((1 2 3) (4 5 6) (7 8 9) (10))
Run Code Online (Sandbox Code Playgroud)

与...相同

(partition 3 3 [] [1 2 3 4 5 6 7 8 9 10])
Run Code Online (Sandbox Code Playgroud)

lee*_*ski 5

@Timothy-Pratley的回答很好,但它不是尾递归的,这意味着它会在大量收集的情况下导致堆栈溢出.这是非堆栈消费变体:

(defn my-partition [n items]
  (loop [res [] items items]
    (if (empty? items)
      res
      (recur (conj res (take n items))
             (drop n items)))))

user> (my-partition 3 (range 10))
[(0 1 2) (3 4 5) (6 7 8) (9)]
Run Code Online (Sandbox Code Playgroud)