编写一个函数美隔接收一个序列coll和整数n每隔n个元素就删除coll中的一个元素
Write a function which drops every Nth item from a sequence.
(fn [coll idx ]
(->>
(map-indexed vector coll)
(filter #(not= 0 (mod (inc (first %)) idx ) ))
(map second)
)
)
首先使用map-indexed给数据加上索引下标
map-indexed接收一个函数和序列吧序列变换成带索引号的序列
(map-indexed (fn [idx item] [idx item]) "foobar")
=> ([0 \f] [1 \o] [2 \o] [3 \b] [4 \a] [5 \r])
简洁写法
(map-indexed vector "foobar")
=> ([0 \f] [1 \o] [2 \o] [3 \b] [4 \a] [5 \r])
然后是用filter根据下标过滤数据,在使用map过滤下标
在github上看到的一个解法
((fn [vec n]
(->>
(partition-all n vec)
(mapcat #(take (dec n) %))
)
) [1 2 3 4 5 6 7 8] 3)
=> (1 2 4 5 7 8)
partition-all 按照n把序列拆分
((fn [vec n]
(->>
(partition-all n vec)
;; (mapcat #(take (dec n) %))
)
) [1 2 3 4 5 6 7 8] 3)
=> ((1 2 3) (4 5 6) (7 8))