有没有办法在Clojure中返回集合的最后一个元素? [英] Is there a Way to Return the Last Element of a Set in Clojure?
问题描述
user-> (last '(First (Second (Last))))
-> (Second (Last))
我通常会假设此^将仅返回(最后一个).为什么是这样?并有一种方法可以只返回(最后一个)或最后一个.
I would typically assume this ^ would return just (Last). Why is this? And is there a way to return just (Last) or Last.
还有什么呢?
(defn function
[input] ;assume input = '(First (Second (Last)))
(last input)
)
推荐答案
严格来说,(第一个(第二个(最后一个))
)不是一个Set,而是一个List.集合是没有重复的元素的集合,并且不需要元素的顺序.
Strictly speaking, (First (Second (Last)))
is not a Set, but a List. A Set is a collection of elements with no duplicates and ordering of the elements in not required.
如果仔细观察,它是2个元素的列表.第一个元素是符号 First
,第二个元素本身是列表:(第二个(最后一个))
If you look closely, it's a list of 2 elements. The first element is the symbol First
, and the second element is itself a list: (Second (Last))
Clojure的基本思想之一是 sequence 抽象:多种集合数据类型允许您一次使用一个元素.您可以在HashMaps,Sets,Vectors和Lists等集合中调用函数 seq
.
One of the foundational ideas of Clojure is the sequence abstraction: multiple collection data types allow you to take one element at time. You can call the function seq
in collections such as HashMaps, Sets, Vectors and Lists.
在您的情况下,您有一个嵌套的数据集合:一个List,其中元素之一是List,依此类推...
In your case, you have a nested data collection: a List where one of the elements is a List, and so on...
对于嵌套数据结构,您可以使用 tree-seq
,它将一次遍历嵌套列表一个元素,并在需要时进入嵌套集合. tree-seq 带有2或3个参数:可选函数,用于确定元素是否为分支(例如包含其他元素),获取分支子级的函数以及要遍历的集合.
For nested data structures you can use tree-seq
, which will traverse your nested list one element at a time, going into nested collections where needed. tree-seq takes 2 or 3 arguments: an optional function to determine if an element is a branch (eg. contains other elements), the function to get the children of a branch, and the collection to traverse.
(tree-seq sequential? identity '(First (Second (Last))))
;; Note: Commas added for clarity
;; => ((First (Second (Last))), First, (Second (Last)), Second, (Last), Last)
由此,您可以使用 last
清楚地提取last元素:
From this, you can clearly extract the last element with last
:
(last (tree-seq sequential? identity '(First (Second (Last)))))
;; => Last
这篇关于有没有办法在Clojure中返回集合的最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!