Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify that all elements of a list are equal

I have a case, where I need to check if all string elements of a list are equal and I am trying to figure out what the most idiomatic solution would look like. My current approach is, to apply a map to the list, checking if every element equals the first and then reducing the result boolean list with '=':

(def string-list '("3" "3" "3" "3" "3" "3"))
(reduce = (map #(.equals (first string-list) %) string-list))

Obviously, this is not a great solution. Are there more "clojure style" solutions or even a much much simpler approach I am not yet seeing?

like image 759
javahippie Avatar asked Sep 08 '15 06:09

javahippie


People also ask

How do you find if all elements in a list are equal?

Check if all elements in a list are identical or not using count() By counting the number of times the first element occurs in the list, we can check if the count is equal to the size of the list or not.

How do you check if all elements in a list are the same Java?

distinct() Let's look at one particular solution making use of the distinct() method. If the count of this stream is smaller or equal to 1, then all the elements are equal and we return true.

How do you check if two elements in a list are the same python?

Python sort() method and == operator to compare lists We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

How do you check if all elements in an array are equal in C?

How do you check if all values in an array are equal in C? Compare the lengths of arr1 and arr2 . Sort arr1 and arr2 either in ascending or descending order. For each index i of the array, compare arr1[i] and arr2[i] to be equal.


2 Answers

You can use the following:

(apply = string-list)
like image 95
Symfrog Avatar answered Oct 26 '22 07:10

Symfrog


As @Symfrog answered, using apply and = looks best.

(apply = string-list)

Perhaps it looks possible to use distinct function or set, however, these are not a good idea, because these don't work for infinite sequence, though the correct answer will return quickly.

;; works for small sequence, however, will not work for infinite sequence like (range)
(= 1 (count (distinct string-list))) ; bad idea
(= 1 (count (into #{} string-list))) ; bad idea
like image 34
ntalbs Avatar answered Oct 26 '22 07:10

ntalbs