Data.Set is better. It's safer than head/tail and faster than nub
(O(n^2)). For instance, size
is O(1) and fromList
is O(n*log n).
module AllEqual where import Data.Set (fromList, size) allEqual :: [Int] -> Bool allEqual xs = (size $ fromList xs) <= 1
- module AllEqual where
import Data.List- import Data.Set (fromList, size)
- allEqual :: [Int] -> Bool
allEqual xs = length (nub xs) <= 1- allEqual xs = (size $ fromList xs) <= 1
What is the easiest way to check if all elements are equal in a Haskell list? Perhaps something that is safer than using head or tail?
For instance:
allEqual [1,2,3,4] = False
allEqual [1,1,1,1] = True
module AllEqual where
allEqual :: [Int] -> Bool
allEqual xs = and $ map (== head xs) (tail xs)
import Test.Hspec
import AllEqual
main = hspec $ do
describe "All Equal" $ do
it "Basic tests" $ do
allEqual [1,2,3,4] `shouldBe` False
allEqual [1,1,1,1] `shouldBe` True