if-statement - Haskell 函数返回列表中出现次数超过给定数量的元素列表

标签 if-statement haskell indentation parse-error

我尝试创建一个函数,如标题所示,它需要两个参数,一个指定该数字必须出现次数的数字以及一个我们正在处理的列表,我创建了一个函数来计算给定数字的出现次数一个列表,我尝试在我的主函数中使用它,但我无法理解 if else 和缩进在 Haskell 中的工作原理,它比其他语言更难修复错误,我认为我缺少 else 语句,但即便如此我也不知道要放在那里

count el list = count el list 0
     where count el list output
             | list==[] = output
             | head(list)==el = count el (tail(list)) output+1
             | otherwise = count el (tail(list)) output


moreThan :: Eq a => Int -> [a] -> [a]
moreThan a [] = []
moreThan a list = moreThan a list output i
    where moreThan a list [] 0
            if i == length (list)
                then output
            else if elem (list!!i) output
                 then moreThan a list output i+1
            else if (count (list!!i) list) >= a 
                then moreThan a list (output ++ [list!!i]) i+1 

我现在得到的是

parse error (possibly incorrect indentation or mismatched brackets) 

最佳答案

您只是忘记了 =符号和一些括号,最后的 else案件。而且您还切换了内部函数声明和调用的顺序:

    moreThan :: Eq a => Int -> [a] -> [a]
    moreThan a [] = []
    moreThan a list = go a list [] 0   -- call
        where go a list output i =      --  declaration  =
                if i == length (list)
                    then output
                else if elem (list!!i) output
                     then go a list output (i+1)    -- (i+1) !
                else if (count (list!!i) list) >= a 
                    then go a list (output ++ [list!!i]) (i+1)   -- (i+1) !
                else
                    undefined

我确实将你的内部函数重命名为 go ,按照惯例。

至于如何修复一般错误,只需缓慢而仔细地阅读错误消息即可 - 它们通常会说明出了什么问题以及出在哪里。

这解决了您询问的语法问题。

至于在缺少的 else 子句中放入什么,您刚刚在上面的行中处理了这个问题 - 您包括 i如果列表中的计数大于或等于给定参数 a,则为输出中的第一个元素。我们在 else 中说要做什么条款。

也就是说,最有可能的是,在输出中包含该元素:

                    then go a list (output ++ [list!!i]) (i+1)
                else               ---------------------
                    undefined

所以,只需保留 output就这样,代替概述的部分,并将该行代替 undefined .

更重要的是,通过索引访问列表元素是一种反模式,最好通过 tail 来“滑动”。在每个递归步骤中,始终处理 head仅元素,就像您在 count 中所做的那样代码(但最好使用模式匹配,而不是直接使用那些函数)。这样我们的代码就变成线性的,而不是像现在这样二次的。

关于if-statement - Haskell 函数返回列表中出现次数超过给定数量的元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67998874/

相关文章:

c - 预处理器指令 #if 和普通 if 之间的区别

ios - 参数类型 'UITextField' 不符合预期类型 'Sequence'

sublimetext3 - 在 Sublime Text 3 中自动将缩进从 2 个空格转换为 4 个空格

jquery - 如何修复 Vim 中 Jquery 脚本的缩进?

haskell - 为什么产品 [] 返回 1?

python - Python GUI 中的缩进

javascript - 为什么我的所有数据都会显示,即使我已经设置了条件以在幻灯片中每 3 个数据显示它?

java - If 和 if else 未获取触发条件

haskell - 如何在 Haskell 项目中组织大量状态

string - 从 Haskell 中的字符串替换子字符串