2015-09-07 67 views
1

說我有序列:在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)] 

如何獲得所需的功能?

回答

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

如下

; 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]) 
2

一個替代方案是map與您的列表和rest的列表。例如: -

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

這也適用於獨立的向量編號的順序:

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

將產生:

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