iTranslated by AI
Checking if all elements in a list are equal
How to determine if all elements in a list are identical in Clojure.
(def lst '(10 10 10 10 10))
I used to write it by checking if the count is 1 after removing duplicates with distinct.
(->> lst distinct count (= 1))
;=> true
In a similar way, you can also write it by putting the elements into a Set (which holds unique elements) and checking if the count is 1.
(->> lst (into #{}) count (= 1))
However, Clojure's = operator accepts a variable number of arguments, so you can write it using apply. This approach is more concise.
(apply = lst)
;=> true
However, note that the behavior for empty lists is different, as = returns true when there are zero arguments.
(def lst2 '())
(apply = lst2)
;=> true
(->> lst2 distinct count (= 1))
;=> false
(->> lst2 (into #{}) count (= 1))
;=> false
Furthermore, according to https://stackoverflow.com/questions/32450837/verify-that-all-elements-of-a-list-are-equal, using distinct or set is not ideal because they don't work with infinite sequences. That said, I am not sure if there are many cases where one would actually pass an infinite lazy sequence to distinct or set in this context.
Discussion