I built a function that verifies that all elements of a foldable structure are equal.
Compared to a similar function on the lists, it seems to me that the more general function is disproportionately complex, but I have not been able to simplify it.
Do you have any suggestions?
import Data.Monoid
import Data.Sequence as SQ
import Data.Matrix as MT
allElementsEqualL :: Eq a => [a] -> Bool
allElementsEqualL [] = True
allElementsEqualL (x:ns) = all (== x) ns
-- allElementsEqualL [1,1,1] -> True
allElementsEqualF :: (Foldable t, Eq a) => t a -> Bool
allElementsEqualF xs = case (getFirst . foldMap (First . Just) $ xs) of
Nothing -> True
Just x -> all (== x) xs
-- allElementsEqualF [1,1,1] -> True
-- allElementsEqualF $ SQ.fromList [1,1,1] -> True
-- allElementsEqualF $ MT.fromLists [[1,1],[1,1]] -> True
We can check for such scenario using the below python programs. There are different approaches. In this method we grab the first element from the list and use a traditional for loop to keep comparing each element with the first element. If the value does not match for any element then we come out of the loop and the result is false.
Given an array, check whether all elements in an array are same or not. Examples: Input : "Geeks", "for", "Geeks" Output : Not all Elements are Same Input : 1, 1, 1, 1, 1 Output : All Elements are Same. Method 1 (Hashing) We create an empty HashSet, insert all elements into it, then we finally see if size of the HashSet is one or not.
In this, we test for type using isinstance () and check for all elements if they match same type as of 1st element. This is yet another way to perform this task. In this, we instead of iterating perform the task in one line using all and instance ().
You can use a combination of the length () and the unique () functions in R to check if all the elements in a vector are equal or not. The following is the syntax –
I don't know about less complicated, but I think this is the "cleanest" way to do it. By "clean," I mean it's one traversal over the structure using a single, special Monoid
.
data Same a = Vacuous | Fail | Same a
instance Eq a => Semigroup (Same a) where
Vacuous <> x = x
Fail <> _ = Fail
s@(Same l) <> Same r = if l == r then s else Fail
x <> Vacuous = x
_ <> Fail = Fail
instance Eq a => Monoid (Same a) where
mempty = Vacuous
allEq :: (Foldable f, Eq a) => f a -> Bool
allEq xs = case foldMap Same xs of
Fail -> False
_ -> True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With