Algorithms
Code
Diff
  • module AllEqual where
    
    allEqual :: [Int] -> Bool
    allEqual = and . (zipWith (==) <*> tail)
  • 11
    module AllEqual where
    
    22
    33
    allEqual :: [Int] -> Bool
    
    4
    allEqual = all =<< (==) . head
    
    4+
    allEqual = and . (zipWith (==) <*> tail)
    
Algorithms
Code
Diff
  • module AllEqual where
    
    allEqual :: [Int] -> Bool
    allEqual = all =<< (==) . head
  • 11
    module AllEqual where
    
    22
    33
    allEqual :: [Int] -> Bool
    
    4
    allEqual []     = True
    
    5
    allEqual (x:xs) = all (== x) xs
    
    4+
    allEqual = all =<< (==) . head
    
Algorithms

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).

Code
Diff
  • module AllEqual where
    import Data.Set (fromList, size)
    
    allEqual :: [Int] -> Bool 
    allEqual xs = (size $ fromList xs) <= 1
  • 11
    module AllEqual where
    
    2
    import Data.List
    
    2+
    import Data.Set (fromList, size)
    
    33
    44
    allEqual :: [Int] -> Bool 
    
    5
    allEqual xs = length (nub xs) <= 1
    
    5+
    allEqual xs = (size $ fromList xs) <= 1
    
Algorithms

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)
Code
Diff
  • function wordCount(str) { 
    return (str.split(" ")).length; 
    }
  • 1
    function wordCount(str) {
    
    2
      var words = 1;
    
    3
      for(var i = 1; i < str.length; i++) {
    
    4
        if(str[i] == " " && str[i - 1] !== " "&& str[i + 1] !== " ") {
    
    5
          words++;
    
    6
        }
    
    7
      }
    
    8
      return words;
    
    1+
    function wordCount(str) { 
    
    2+
    return (str.split(" ")).length; 
    
    99
    }