Ad
Algorithms
Logic
Code
Diff
  • module AllEqual where
    
    allEqual :: [Int] -> Bool
    allEqual = and . (zipWith (==) <*> tail)
    • module AllEqual where
    • allEqual :: [Int] -> Bool
    • allEqual = all =<< (==) . head
    • allEqual = and . (zipWith (==) <*> tail)
Algorithms
Logic
Code
Diff
  • module AllEqual where
    
    allEqual :: [Int] -> Bool
    allEqual = all =<< (==) . head
    • module AllEqual where
    • allEqual :: [Int] -> Bool
    • allEqual [] = True
    • allEqual (x:xs) = all (== x) xs
    • allEqual = all =<< (==) . head
Algorithms
Logic

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
    • 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
Algorithms
Logic

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; 
    }
    • function wordCount(str) {
    • var words = 1;
    • for(var i = 1; i < str.length; i++) {
    • if(str[i] == " " && str[i - 1] !== " "&& str[i + 1] !== " ") {
    • words++;
    • }
    • }
    • return words;
    • }
    • function wordCount(str) {
    • return (str.split(" ")).length;
    • }