# 99 questions/Solutions/9

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

(added one more implementation) |
|||

Line 21: | Line 21: | ||

| otherwise = ([], (y:ys)) | | otherwise = ([], (y:ys)) | ||

(first,rest) = getReps xs | (first,rest) = getReps xs | ||

+ | </haskell> | ||

+ | |||

+ | Similarly, using <hask>splitAt</hask> and <hask>findIndex</hask>: | ||

+ | |||

+ | <haskell> | ||

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

</haskell> | </haskell> | ||

## Revision as of 16:55, 15 September 2010

(**) Pack consecutive duplicates of list elements into sublists.

If a list contains repeated elements they should be placed in separate sublists.

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

splitAt

findIndex

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)

group

Data.List

takeWhile

dropWhile

pack :: (Eq a) => [a] -> [[a]] pack [] = [] pack (x:xs) = (x : takeWhile (==x) xs) : pack (dropWhile (==x) xs)