Reputation: 35
I want to write a function like:
sameBool :: [Bool] -> Bool
for example:
[True, False, True] => False
[True, True] => True
Here's my solution:
sameBool :: [Bool] -> Bool
sameBool xs = if head xs == True
then length (filter (== False) xs) == 0
else length (filter (== True) xs) == 0
Effective though not elegant. I'm looking for some more elegant solution.
Upvotes: 3
Views: 86
Reputation: 5405
With all:
sameBool :: [Bool] -> Bool
sameBool xs = all (== head xs) xs
With nub from Data.List
:
import Data.List
sameBool :: [Bool] -> Bool
sameBool = (== 1) . length . nub
Actually, they works for any instance of Eq
:
sameBool :: Eq a => [a] -> Bool
sameBool xs = all (== head xs) xs
-- Note: return True for []
sameBool :: Eq a => [a] -> Bool
sameBool = (== 1) . length . nub
-- Note: return False for []
Check nubBy for types that aren't instances of Eq
.
Upvotes: 7