a1yx
a1yx

Reputation: 97

Haskell - check if there is a repeated element in the list

This is a uni homework assignment that I have mostly finished and I'm not just coming here for answers

The task given was to find if a given an element shows up more than once in a list. The algorithm I tried was to create countDups that will act as a counter, and count the amount of times said element is found in list. Then isMemberTwice (which should return a Bool) will be True if countDups is greater than 1 and False otherwise.

Yes I am new to Haskell so I'm sorry if this is a completely horrendous way to implement.

countDups x [] = 0 
countDups x (y:ys) 
    | x == y = 1 + countDups x ys 
    | otherwise = countDups x ys

isMemberTwice x [] = False      --base case; empty list
isMemberTwice x (y: ys) 
    | countDups > 1 = True 
    | otherwise False 

Error Message

    parse error (possibly incorrect indentation or mismatched brackets)
Failed, modules loaded: none.

Due to a comment below I updated but still not working - any suggestions?

isMember _ [] = 0
isMember a (x:xs)
    | (a == x) = 1
    | otherwise isMember a xs

isMemberTwice _ [] = False
isMemberTwice a (x:xs)
    | (a == x) = if ((1 + isMember a (x:xs)) > 1) then True
    | otherwise isMemberTwice a xs

Upvotes: 2

Views: 2345

Answers (1)

dfeuer
dfeuer

Reputation: 48580

Some tips:

  1. Forget about countDups for now; you don't need it to write isMemberTwice.

  2. Start by writing isMember.

  3. Use isMember to write isMemberTwice.

     isMember x [] = ???
     isMember x (y : ys)
       | x == y = ???
       | otherwise = ???
    
     isMemberTwice x [] = ???
     isMemberTwice x (y : ys)
       | x == y = ???
       | otherwise = ???
    

Upvotes: 5

Related Questions