我尝试创建一个函数,如标题所示,它需要两个参数,一个指定该数字必须出现次数的数字以及一个我们正在处理的列表,我创建了一个函数来计算给定数字的出现次数一个列表,我尝试在我的主函数中使用它,但我无法理解 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/