Reputation: 97
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
Reputation: 48580
Some tips:
Forget about countDups
for now; you don't need it to write isMemberTwice
.
Start by writing isMember
.
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