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

From HaskellWiki
Jump to navigation Jump to search
 
Line 1: Line 1:
 
(**) Pack consecutive duplicates of list elements into sublists.
 
(**) Pack consecutive duplicates of list elements into sublists.
  +
 
If a list contains repeated elements they should be placed in separate sublists.
 
If a list contains repeated elements they should be placed in separate sublists.
   
Line 9: Line 10:
   
 
A more verbose solution is
 
A more verbose solution is
  +
 
<haskell>
 
<haskell>
 
pack :: Eq a => [a] -> [[a]]
 
pack :: Eq a => [a] -> [[a]]
Line 22: Line 24:
   
 
This is implemented as <hask>group</hask> in <hask>Data.List</hask>.
 
This is implemented as <hask>group</hask> in <hask>Data.List</hask>.
  +
  +
Another solution using <hask>takeWhile</hask> and <hask>dropWhile</hask>:
  +
  +
<haskell>
  +
pack :: (Eq a) => [a] -> [[a]]
  +
pack [] = []
  +
pack (x:xs) = (x : takeWhile (==x) xs) : pack (dropWhile (==x) xs)
  +
</haskell>

Revision as of 03:00, 14 July 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

This is implemented as group in Data.List.

Another solution using takeWhile and dropWhile:

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