4clojure 题解 Drop Every Nth Item

作者: admin 日期: 2017-12-29 14:55:41 人气: - 评论: 0

编写一个函数美隔接收一个序列coll和整数n每隔n个元素就删除coll中的一个元素

Write a function which drops every Nth item from a sequence.

test not run
(= (__ [1 2 3 4 5 6 7 8] 3) [1 2 4 5 7 8])
test not run
(= (__ [:a :b :c :d :e :f] 2) [:a :c :e])
test not run
(= (__ [1 2 3 4 5 6] 4) [1 2 3 5 6])











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



相关内容

发表评论
更多 网友评论0 条评论)
暂无评论

Copyright © 2012-2014 我的代码板 Inc. 保留所有权利。

页面耗时0.0348秒, 内存占用1.83 MB, 访问数据库13次

闽ICP备15009223号-1