[Haskell-cafe] function unique
byorgey at gmail.com
Tue Jul 10 16:52:38 EDT 2007
The problem with your second implementation is that elements which occur
more than once will eventually be included, when the part of the list
remaining only has one copy. For example:
= unique2 [1,2,4,1]
= unique2 [2,4,1]
= 2 : unique2 [4,1]
= 2 : 4 : unique2 
= 2 : 4 : 1 : unique2  -- only a single 1 left, so it gets mistakenly
When you determine that a certain number should not be included in the
output, you need to delete all remaining occurrences of it from the list, so
it won't get included later.
|elemNum2 x xs == 1 = x:unique2 xs
|otherwise = unique2 (deleteElt x xs)
I'll let you figure out how to implement the deleteElt function.
hope this is helpful!
On 7/10/07, Alexteslin <alexteslin at yahoo.co.uk> wrote:
> Hi, i am a beginner to Haskell and i have a beginner's question to ask.
> An exercise asks to define function unique :: [Int] -> [Int], which
> a list with only elements that are unique to the input list (that appears
> more than once). I defined a function with list comprehension which works
> but trying to implement with pattern matching and primitive recursion with
> lists and doesn't work.
> unique :: [Int] -> [Int]
> unique xs = [x | x <- xs, elemNum2 x xs == 1]
> elemNum2 :: Int -> [Int] -> Int
> elemNum2 el xs = length [x| x <- xs, x == el]
> //This doesn't work, I know because the list shrinks and produces wrong
> result but can not get a right //thinking
> unique2 :: [Int] -> [Int]
> unique2  = 
> unique2 (x:xs)
> |elemNum2 x xs == 1 = x:unique2 xs
> |otherwise = unique2 xs
> Any help to a right direction would be very appreciated, thanks.
> View this message in context:
> Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe