[Haskell-beginners] Beginners Digest, Vol 45, Issue 35

Lorenzo Bolla lbolla at gmail.com
Thu Mar 29 12:19:57 CEST 2012


Your second solution, a part from non preserving the ordering of the
initial sequence, also requires the type of the list elements to be an
instance of Ord.
I've fixed a bug in your first version, where the return values of isIn
where reversed.

Here they are:


module Main where

import Data.List (sort, group)

-- Need ordering on "a"
uniqueS :: Ord a => [a] -> [a]
uniqueS = concat . filter (null . drop 1) . group . sort

-- Fixed Chaddai's solution
-- Only need equivalent relation on "a"
unique :: Eq a => [a] -> [a]
unique xs = [x | x <- xs, isIn x xs 2]
        where isIn :: Eq a => a -> [a] -> Int -> Bool
              isIn _ _ 0 = False
              isIn _ [] _ = True
              isIn y (x:xs) n
                    | y == x    = isIn y xs (n-1)
                    | otherwise = isIn y xs n

main :: IO ()
main = do
        print $ uniqueS xs
        print $ unique xs
        where xs = [1,2,3,3,5,2,1,4]


L.


On Thu, Mar 29, 2012 at 9:30 AM, Chaddaï Fouché <chaddai.fouche at gmail.com>wrote:

> On Thu, Mar 29, 2012 at 10:28 AM, Chaddaï Fouché
> <chaddai.fouche at gmail.com> wrote:
> >> unique xs = nub (sort xs)
>
> oops, I meant :
>
> > unique = concat . filter (null . drop 1) . group . sort
>
> --
> Jedaï
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120329/b99e57c8/attachment.htm>


More information about the Beginners mailing list