[Haskell-cafe] Most elegant funciton for removing adjacent duplicates from a list using foldl and foldr

Peter Verswyvelen bugfact at gmail.com
Sun Mar 15 09:43:06 EDT 2009


Why don't you just swap the pattern match order?
   remdups               :: (Eq a) => [a] -> [a]
   remdups (x : xx : xs) =  if x == xx then remdups (x : xs) else x :
remdups (xx : xs)
   remdups xs            = xs

This should cover all cases no?

Also I prefer guards, but I guess that is personal

   remdups (x1:x2:xs)
   | x1 == x2  =      remdups (x2 : xs)
   | otherwise = x1 : remdups (x2 : xs)
   remdups xs  = xs

2009/3/15 R J <rj248842 at hotmail.com>

>  I need to write an implementation using foldl, and a separate
> implementation using foldr, of a function, "remdups xs", that removes
> adjacent duplicate items from the list xs.  For example, remdups
> [1,2,2,3,3,3,1,1]= [1,2,3,1].
>
> My approach is first to write a direct recursion, as follows:
>
>    remdups               :: (Eq a) => [a] -> [a]
>    remdups []            =  []
>    remdups (x : [])      =  [x]
>    remdups (x : xx : xs) =  if x == xx then remdups (x : xs) else x :
> remdups (xx : xs)
>
> This code works, but it has three cases, not usual two, namely [] and (x :
> xs).
>
> What, if any, is the implementation using only two cases?
>
> Also, if three cases are required, then how can it be implemented using
> foldr, and how using foldl?
>
> Thanks.
>
> ------------------------------
> Express your personality in color! Preview and select themes for Hotmail®. See
> how.<http://www.windowslive-hotmail.com/LearnMore/personalize.aspx?ocid=TXT_MSGTX_WL_HM_express_032009#colortheme>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090315/7d8de249/attachment.htm


More information about the Haskell-Cafe mailing list