Is there a Way to Return the Last Element of a Set in Clojure?

感情迁移 提交于 2021-01-29 14:34:45

问题


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.

What about also for:

(defn function
 [input]              ;assume input = '(First (Second (Last)))

 (last input)

 )

回答1:


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.

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

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.

In your case, you have a nested data collection: a List where one of the elements is a List, and so on...

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)

From this, you can clearly extract the last element with last:

(last (tree-seq sequential? identity '(First (Second (Last)))))
;; => Last


来源:https://stackoverflow.com/questions/60610883/is-there-a-way-to-return-the-last-element-of-a-set-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!