与包含所有元素的分区相关的功能?

时间:2014-05-27 00:14:49

标签: clojure

Clojure partition函数的这种行为不是我需要的:

user=> (partition 3 (range 3))
((0 1 2))
user=> (partition 3 (range 4))
((0 1 2))
user=> (partition 3 (range 5))
((0 1 2))
user=> (partition 3 (range 6))
((0 1 2) (3 4 5))

我需要'剩余的'要包括的集合部分,例如:

user=> (partition* 3 (range 4))
((0 1 2) (3))
user=> (partition* 3 (range 5))
((0 1 2) (3 4))

是否有符合我要求的标准库函数?

2 个答案:

答案 0 :(得分:7)

您正在寻找partition-all。只需在您的示例中替换它:

user> (partition-all 3 (range 4))
((0 1 2) (3))
user> (partition-all 3 (range 5)) 
((0 1 2) (3 4))

答案 1 :(得分:5)

pad的4-arity版本中有partition个参数:

user=> (partition 3 3 [] (range 4))
((0 1 2) (3))

user=> (partition 3 3 [] (range 5))
((0 1 2) (3 4))

docstring:

user=> (doc partition)
-------------------------
clojure.core/partition
([n coll] [n step coll] [n step pad coll])
  Returns a lazy sequence of lists of n items each, at offsets step
  apart. If step is not supplied, defaults to n, i.e. the partitions
  do not overlap. If a pad collection is supplied, use its elements as
  necessary to complete last partition upto n items. In case there are
  not enough padding elements, return a partition with less than n items.