m (oops mixed up my edge case)
Revision as of 10:55, 17 November 2010
(**) Pack consecutive duplicates of list elements into sublists.
If a list contains repeated elements they should be placed in separate sublists.
This is implemented as
pack (x:xs) = let (first,rest) = span (==x) xs in (x:first) : pack rest pack  = 
A more verbose solution is
pack :: Eq a => [a] -> [[a]] pack  =  pack (x:xs) = (x:first) : pack rest where getReps  = (, ) getReps (y:ys) | y == x = let (f,r) = getReps ys in (y:f, r) | otherwise = (, (y:ys)) (first,rest) = getReps xs
Another solution using
pack :: Eq a => [a] -> [[a]] pack  =  pack (x:xs) = (x:reps) : (pack rest) where (reps, rest) = maybe (xs,) (\i -> splitAt i xs) (findIndex (/=x) xs)
Or we can use
pack :: (Eq a) => [a] -> [[a]] pack  =  pack (x:xs) = (x : takeWhile (==x) xs) : pack (dropWhile (==x) xs)
to implement this:
pack :: (Eq a) => [a] -> [[a]] pack = foldr func  where func x  = [[x]] func x (y:xs) = if x == (head y) then ((x:y):xs) else ([x]:y:xs)