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

时间:2015-10-26 02:24:58

标签: haskell

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

给出的任务是查找给定的元素是否在列表中出现多次。我尝试的算法是创建countDups作为计数器,并计算在列表中找到所述元素的次数。如果isMemberTwice大于1,则Bool(应返回TruecountDups,否则为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 

错误消息

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

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

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

1 个答案:

答案 0 :(得分:5)

一些提示:

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

  2. 首先撰写isMember

  3. 使用isMember撰写isMemberTwice

     isMember x [] = ???
     isMember x (y : ys)
       | x == y = ???
       | otherwise = ???
    
     isMemberTwice x [] = ???
     isMemberTwice x (y : ys)
       | x == y = ???
       | otherwise = ???
    
相关问题