在clojure中如何映射重叠对?

Tom*_*Tom 1 clojure

说我有序列:

[1 2 3 4 5]
Run Code Online (Sandbox Code Playgroud)

我想成对映射它们:

[(1, 2), (2, 3), (3, 4), (4, 5)]
Run Code Online (Sandbox Code Playgroud)

我试过了:

(map f (partition 2 [1 2 3 4]))
Run Code Online (Sandbox Code Playgroud)

但这导致了对的顺序:

[(1, 2), (3, 4)]
Run Code Online (Sandbox Code Playgroud)

如何获得所需的功能?

mty*_*aka 9

默认情况下,partiton返回非重叠分区,但您可以提供step参数以提供创建分区的偏移量:

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.
Run Code Online (Sandbox Code Playgroud)

这将做你想要的:

(partition 2 1 [1 2 3 4 5 6 7 8]))
; #=> ((1 2) (2 3) (3 4) (4 5) (5 6) (6 7) (7 8))
Run Code Online (Sandbox Code Playgroud)