Clojure中的惯用序列片 [英] Idiomatic sequence slice in Clojure
问题描述
在Python中,有一种方便的方法来获取名为slicing的列表的一部分:
a = [1,2,3,4,5,6,7,8,9,10]#≡a = range(1,10)
a [:3]#获得前3个元素
a [3:]#获取除第3个元素之外的所有元素
a [: - 3]#获取除最后3个元素之外的所有元素
a [-3:]#获取最后3个元素
a [3:7]#获取从第3个开始的4个元素(≡从第3到第7个)
a [3:-3]#获取除第3个和最后3个元素之外的所有元素
在Clojure中使用 clojure.repl / doc
但是我不确定他们是惯用的。
inc 1)))
/ pre>
(take 3 a)
(drop 3 a)
(take( - (count a)3)a)
)3)a)
(drop 3(take 7a))
(drop 3(take( - (count a)3)a))
我的问题是:如何切割Clojure中的序列?换句话说,返回序列不同部分的正确方法是什么?
解决方案改为使用
take-last
或drop-last
(def a(take 10(iterate inc 1)))
3 a);得到前3个元素
(drop 3 a);获取所有元素,除了第一个3
(drop-last 3 a);获取除最后3个元素之外的所有元素
(take-last 3 a);获取最后3个元素
(drop 3(take 7a));得到从3开始的4个元素
(drop 3(drop-last 3 a));获取除第一个和最后三个之外的所有元素
宏
- >>
宏到线程几个操作在一起。例如,最后两行也可以这样写:( - > ; a(take 7)(drop 3));得到从3开始的4个元素
( - >> a(drop-last 3)(drop 3));获取除第一个和最后三个之外的所有元素
只是对列表应用两个操作,但是当你有一个长字符串
take
,map
,filter
,drop
,- >>
宏可以使代码更容易阅读,并且可能更容易编写。In Python, there is a convenient way of taking parts of a list called "slicing":
a = [1,2,3,4,5,6,7,8,9,10] # ≡ a = range(1,10) a[:3] # get first 3 elements a[3:] # get all elements except the first 3 a[:-3] # get all elements except the last 3 a[-3:] # get last 3 elements a[3:7] # get 4 elements starting from 3rd (≡ from 3rd to 7th exclusive) a[3:-3] # get all elements except the first 3 and the last 3
Playing with
clojure.repl/doc
in Clojure, I found equivalents for all of them but I'm not sure they are idiomatic.(def a (take 10 (iterate inc 1))) (take 3 a) (drop 3 a) (take (- (count a) 3) a) (drop (- (count a) 3) a) (drop 3 (take 7 a)) (drop 3 (take (- (count a) 3) a))
My question is: how to slice sequences in Clojure? In other words, what is the correct way to return different parts of a sequence?
解决方案You can simplify all the ones using
count
by usingtake-last
ordrop-last
instead:(def a (take 10 (iterate inc 1))) (take 3 a) ; get first 3 elements (drop 3 a) ; get all elements except the first 3 (drop-last 3 a) ; get all elements except the last 3 (take-last 3 a) ; get last 3 elements (drop 3 (take 7 a)) ; get 4 elements starting from 3 (drop 3 (drop-last 3 a)) ; get all elements except the first and the last 3
And as suggested in the comments below, you can use the
->>
macro to "thread" several operation together. For example, the last two lines could also be written like this:(->> a (take 7) (drop 3)) ; get 4 elements starting from 3 (->> a (drop-last 3) (drop 3)) ; get all elements except the first and the last 3
I think the two methods are both very readable if you are only applying two operations to a list, but when you have a long string like
take
,map
,filter
,drop
,first
then using the->>
macro can make the code much easier to read and probably even easier for to write.这篇关于Clojure中的惯用序列片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!