99 questions/Solutions/9
From HaskellWiki
(Difference between revisions)
(code long line breakup) |
|||
| Line 9: | Line 9: | ||
</haskell> | </haskell> | ||
| - | This is implemented as <hask>group</hask> in <hask>Data.List</hask>. | + | This is implemented as <hask>group</hask> in <hask>Data.List</hask>. |
A more verbose solution is | A more verbose solution is | ||
| Line 25: | Line 25: | ||
</haskell> | </haskell> | ||
| - | Similarly, using <hask>splitAt</hask> and <hask>findIndex</hask>: | + | Similarly, using <hask>splitAt</hask> and <hask>findIndex</hask>: |
<haskell> | <haskell> | ||
| Line 32: | Line 32: | ||
pack (x:xs) = (x:reps) : (pack rest) | pack (x:xs) = (x:reps) : (pack rest) | ||
where | where | ||
| - | (reps, rest) = maybe (xs,[]) (\i -> splitAt i xs) (findIndex (/=x) xs) | + | (reps, rest) = maybe (xs,[]) (\i -> splitAt i xs) |
| + | (findIndex (/=x) xs) | ||
</haskell> | </haskell> | ||
| - | Another solution using <hask>takeWhile</hask> and <hask>dropWhile</hask>: | + | Another solution using <hask>takeWhile</hask> and <hask>dropWhile</hask>: |
<haskell> | <haskell> | ||
| Line 43: | Line 44: | ||
</haskell> | </haskell> | ||
| - | Or we can use <hask>foldr</hask> to implement this: | + | Or we can use <hask>foldr</hask> to implement this: |
<haskell> | <haskell> | ||
Revision as of 09:53, 1 June 2011
(**) 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 [] = []
group
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
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)
takeWhile
dropWhile
pack :: (Eq a) => [a] -> [[a]] pack [] = [] pack (x:xs) = (x : takeWhile (==x) xs) : pack (dropWhile (==x) xs)
foldr
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)
A simple solution:
pack :: (Eq a) => [a] -> [[a]] pack [] = [] pack [x] = [[x]] pack (x:xs) = if x `elem` (head (pack xs)) then (x:(head (pack xs))):(tail (pack xs)) else [x]:(pack xs)
