[Haskell-cafe] Most elegant funciton for removing adjacent
duplicates from a list using foldl and foldr
Roel van Dijk
vandijk.roel at gmail.com
Sun Mar 15 09:25:24 EDT 2009
2009/3/15 R J <rj248842 at hotmail.com>:
> What, if any, is the implementation using only two cases?
This version considers 2 cases 2 times :-) But only the 'go' function
is recursive, so it could probably be written using some kind of fold.
The value being build by the fold should probably be some kind of
tuple so you can keep track of some state.
remdups2 :: (Eq a) => [a] -> [a]
remdups2  = 
remdups2 (x:xs) = go x xs
where go x  = [x]
go x (y:ys) = if x == y then go x ys else x : go y ys
I almost managed to write one using foldr, but it always put the first
group last :-( Perhaps someone else manages to get it right.
-- Warning: doesn't work correctly! Last group is last...
remdups3 :: (Eq a) => [a] -> [a]
remdups3  = 
remdups3 (x:xs) = snd $ foldr f (x, ) xs
where f y (x, xs') = if y == x then (x, xs') else (y, x : xs')
More information about the Haskell-Cafe