Trying to create a function that takes a list and returns a list of all elements identical to its first element, but my function does not work

In particular, for strings. Therefore, it will be required ["so", "what", "and", "so", "for" "so"]and returned ["so", "so", "so"]. My problem is that my function returns a list identical to the one that was entered.

Here are all the relevant codes:

lookAhead :: [String] -> String
lookAhead [] = []
lookAhead (c:cs) = c

groupFirst :: [String] -> [String]
groupFirst [] = []
groupFirst (x:xs) 
    | lookAhead xs == x  = x : (groupFirst ((lookAhead xs):(tail xs)))
    | lookAhead xs /= x  = x : (groupFirst xs)
    | lookAhead xs == [] = x : []
+4
source share
3 answers

trailas head-element -equated-predicated filter:

trail :: Eq a => [a] -> [a]
trail []       = []
trail (x : xs) = x : filter (== x) xs

trailByusing Schwartz transform and memoization :

trailBy :: Eq b => (a -> b) -> [a] -> [a]
trailBy _ []        = []
trailBy f (x1 : xs) = let x1f = f x1
                      in  x1 : filter (\ x -> f x == x1f) xs

trail = trailBy idwhere id x = xis the Haskell authentication function.

+6
source

, groupFirst ( [String]) (String). , .

, ( - f strList, f firstStr strList). , , :

lookAhead :: [String] -> [String]
lookAhead [] = []
lookAhead (x:xs) = x : check x xs

check :: String -> [String] -> [String]
check str = foldr (\x acc -> if x == str then x:acc else acc) []
+2

lookAhead , groupFirst. - :

groupFirst :: [String] -> [String] 
groupFirst [] = []
groupFirst list = [x | x <- list, head list == x]  
+1
source

Source: https://habr.com/ru/post/1659668/


All Articles