gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:11:12 26 4
gpt4 key购买 nike

这是一项我已经完成大部分的大学作业,我来这里不仅仅是为了寻求答案

给定的任务是查找给定的元素是否在列表中出现多次。我尝试的算法是创建 countDups ,它将充当计数器,并计算在列表中找到所述元素的次数。如果 countDups 大于 1 并且 ,则 isMemberTwice(应返回 Bool)将为 True否则为假

是的,我是 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. 暂时忘记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 = ???

关于Haskell - 检查列表中是否有重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33337555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com