cuddle
cuddle

Reputation: 75

data types in haskell programming

It is a haskell code to find the first duplicate element in the list. if you have 2 lists like this:L1 = {1,2,3,4} L2 = {1,2,3,1}then result for 1st would be No duplicate found and result for second should be integer 1.if one list has L3={1,2,1,3,3} answer should still be 1.

I tried doing it but stuck with the condition checking: We will use union datatype.

data Res a = DuplicateFound a | NoDuplicateFound 
              deriving (Show,Eq)

findDuplicate [] = NoDuplicateFound
findDuplicate (x:xs) = if (condition???)
      where 
      aux x [] = NoDuplicateFound
      aux x (y:ys) = if x == y then DuplicateFound x
                               else aux x ys
                     else NoDuplicateFound

I know its a pathetic code..please help me to improve it.

Upvotes: 3

Views: 570

Answers (3)

lbolla
lbolla

Reputation: 5411

You can easily (but not very efficiently), get a list of all the duplicates using nub and (\\).

I presume this is a homework: this suggestion should give you a good starting point.

Upvotes: 0

Ketil
Ketil

Reputation: 156

The key is, as so often, recursion.

A list contains a duplicate if either:

  1. the first element has a duplicate in the rest of the list, or
  2. the rest of the list contains a duplicate

Add to this that an empty list contains no duplicates, and there's your program.

(I'd make hasElement just return a Bool, and use Maybe a for the return value.)

Upvotes: 4

luqui
luqui

Reputation: 60463

This code is a good start. The aux function you have already written searches to see if an element is in a list. Now you just need to check the first element against the rest of the list, and if that fails, then the second element against all elements after it, etc.

I'll just rename aux to hasElement (never underestimate the clarifying power of a good name):

hasElement x [] = NoDuplicateFound
hasElement x (y:ys) = if x == y then DuplicateFound x
                                else hasElement x ys

Then:

findDuplicate [] = NoDuplicateFound
findDuplicate (x:xs) = 
    case hasElement x xs of
        DuplicateFound dup -> ...
        NoDuplicateFound   -> ...

I will leave you to fill in the ...s. Good luck, and thank you for attempting a solution before coming here for help. It makes me more willing to put effort into my answer.

Upvotes: 2

Related Questions