Haskell模式匹配非穷尽错误求助:列表求和函数未匹配空列表问题
Hey there! That error message is pointing straight to the issue—your addfunc only handles one type of list input and completely misses the empty list ([]) scenario. Let's break this down and fix it step by step.
Why the Error Occurs
Your current code only defines behavior for non-empty lists using the pattern (x:xs):
addfunc :: [Int] -> Int addfunc(x:xs) = x + addfunc xs
But in Haskell, lists can be empty! When you pass an empty list to addfunc, there's no matching pattern in your code, so the runtime throws that "non-exhaustive pattern match" error.
The Simple Fix
You just need to add a base case for the empty list. Since the sum of an empty list is logically 0 (the additive identity), we'll use that as our recursion terminator:
addfunc :: [Int] -> Int addfunc [] = 0 -- Handle empty list case addfunc (x:xs) = x + addfunc xs -- Handle non-empty list case
How This Works
- When you call
addfunc [], it immediately returns 0—this stops the recursion chain. - For a non-empty list like
[1,2,3], it breaks down into1 + addfunc [2,3], which further becomes1 + 2 + addfunc [3], then1 + 2 + 3 + addfunc [], and finally resolves to1+2+3+0 = 6.
Bonus: Use Haskell's Built-in Function
Just a quick tip—Haskell has a built-in sum function that does exactly this job! So you could also write sum [1,2,3] instead of rolling your own, but implementing it recursively is great practice for understanding pattern matching and recursion in Haskell.
内容的提问来源于stack exchange,提问作者user13977876

