說我有序列:在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)]
如何獲得所需的功能?
說我有序列:在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)]
如何獲得所需的功能?
默認情況下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))
如下
; 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])
一個替代方案是map
與您的列表和rest
的列表。例如: -
(user=> (let [l [1 2 3 4 5]] (map list l (rest l)))
((1 2) (2 3) (3 4) (4 5))
這也適用於獨立的向量編號的順序:
(let [a [5 4 3 2 1] b (rest a)] (map vector a b))
將產生:
([5 4] [4 3] [3 2] [2 1])