我正在尝试创建一个countElems带Inta [Int]和a的函数,并返回Int列表中特定数量的函数.到目前为止,我有:
countElems :: Int -> [Int] -> Int
countElems n (x:xs)
| xs == [] = 0
| n == x = 1 + countElems n xs
| n /= x = countElems n xs
Run Code Online (Sandbox Code Playgroud)
运行时,这似乎有效,但在进一步检查时,如果输入的countElems 9 [5, 3, 9, 3, 9]是输出1而不是2.我可以看到这是因为它在检查xs == []之前检查是否n == x导致输出不正确,但如果我交换这两种情况就是说Non-exhaustive pattern.
进一步思考后编辑:
我可以消除使用此代码发布的错误@ user2407038:
countElems :: Int -> [Int] -> Int
countElems _ [] = 0
countElems n (x:xs)
| n == x = 1 + countElems n xs
| n /= x = countElems n xs
Run Code Online (Sandbox Code Playgroud)
它看起来不那么优雅,但工作原理相同?