在clojure中如何映射重叠对?

时间:2015-09-07 09:59:24

标签: clojure

说我有序列:

[1 2 3 4 5]

我想成对地映射它们:

[(1, 2), (2, 3), (3, 4), (4, 5)]

我试过了:

(map f (partition 2 [1 2 3 4]))

但这导致了对的顺序:

[(1, 2), (3, 4)]

如何获得所需的功能?

4 个答案:

答案 0 :(得分: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.

这将做你想要的:

(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))

答案 1 :(得分:2)

另一种方法是使用您拥有的列表和列表的map rest。 E.g:

(user=> (let [l [1 2 3 4 5]] (map list l (rest l)))
((1 2) (2 3) (3 4) (4 5))

答案 2 :(得分:1)

我会这样做

; first generate data 
; (that is if you really are talking about all the ints)
(map (juxt identity inc) [1 2 3 4 5])
=> ([1 2] [2 3] [3 4] [4 5] [5 6])

; inline example
(map (comp 
       (fn [[a b]] (println a b)) ; this would be your f
       (juxt identity inc)) [1 2 3 4 5])

; using your function f
(map (comp 
       f
       (juxt identity inc)) [1 2 3 4 5])

答案 3 :(得分:0)

这也与矢量中的数字顺序无关:

(let [a [5 4 3 2 1] b (rest a)] (map vector a b))

将产生:

([5 4] [4 3] [3 2] [2 1])