Haskell - 检查列表中是否有重复的元素

a1y*_*1yx 1 haskell

这是一项单一的家庭作业,我大部分都已完成,我不只是来这里寻求答案

给出的任务是查找给定的元素是否在列表中出现多次.我尝试的算法是创建countDups它将充当计数器,并计算在列表中找到所述元素的次数.那么isMemberTwice(应该返回一个Bool)将是Trueif countDups大于1,False否则.

是的,我是Haskell的新手,所以如果这是一个完全可怕的实施方式,我很抱歉.

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 
Run Code Online (Sandbox Code Playgroud)

错误信息

    parse error (possibly incorrect indentation or mismatched brackets)
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

由于下面的评论我更新但仍然没有工作 - 任何建议?

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
Run Code Online (Sandbox Code Playgroud)

dfe*_*uer 5

一些技巧:

  1. 暂时忘了countDups; 你不需要它写isMemberTwice.

  2. 从写作开始isMember.

  3. 使用isMemberisMemberTwice.

     isMember x [] = ???
     isMember x (y : ys)
       | x == y = ???
       | otherwise = ???
    
     isMemberTwice x [] = ???
     isMemberTwice x (y : ys)
       | x == y = ???
       | otherwise = ???
    
    Run Code Online (Sandbox Code Playgroud)