Difference between revisions of "99 questions/Solutions/9"

From HaskellWiki
Jump to navigation Jump to search
m (oops mixed up my edge case)
Line 8: Line 8:
 
pack [] = []
 
pack [] = []
 
</haskell>
 
</haskell>
  +
 
This is implemented as <hask>group</hask> in <hask>Data.List</hask>.
   
 
A more verbose solution is
 
A more verbose solution is
Line 32: Line 34:
 
(reps, rest) = maybe (xs,[]) (\i -> splitAt i xs) (findIndex (/=x) xs)
 
(reps, rest) = maybe (xs,[]) (\i -> splitAt i xs) (findIndex (/=x) xs)
 
</haskell>
 
</haskell>
 
This is implemented as <hask>group</hask> in <hask>Data.List</hask>.
 
   
 
Another solution using <hask>takeWhile</hask> and <hask>dropWhile</hask>:
 
Another solution using <hask>takeWhile</hask> and <hask>dropWhile</hask>:
Line 41: Line 41:
 
pack [] = []
 
pack [] = []
 
pack (x:xs) = (x : takeWhile (==x) xs) : pack (dropWhile (==x) xs)
 
pack (x:xs) = (x : takeWhile (==x) xs) : pack (dropWhile (==x) xs)
  +
</haskell>
  +
  +
Or we can use <hask>foldr</hask> to implement this:
  +
  +
<haskell>
  +
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)
 
</haskell>
 
</haskell>

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.

pack (x:xs) = let (first,rest) = span (==x) xs
               in (x:first) : pack rest
pack [] = []

This is implemented as group in Data.List.

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

Similarly, using splitAt and 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)

Another solution using takeWhile and dropWhile:

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

Or we can use foldr 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)