Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data types in haskell programming

Tags:

haskell

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.

like image 593
cuddle Avatar asked Jan 24 '26 08:01

cuddle


2 Answers

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.)

like image 176
Ketil Avatar answered Jan 26 '26 01:01

Ketil


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.

like image 43
luqui Avatar answered Jan 26 '26 00:01

luqui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!