You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell模式匹配非穷尽错误求助:列表求和函数未匹配空列表问题

Fixing Non-Exhaustive Pattern Match in Your Haskell Sum Function

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 into 1 + addfunc [2,3], which further becomes 1 + 2 + addfunc [3], then 1 + 2 + 3 + addfunc [], and finally resolves to 1+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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 08:32:44