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

Haskell中列表的列表模式匹配失败原因排查

Haskell代码编译错误排查

原代码

-- A region has a list of squares, and a list of possible combinations of values,
-- all of which add up to the same total.
data Region = Region [Square] [[Int]] deriving (Show, Eq)

-- The total which each combination adds up to: if the list of combinations is
-- empty it is 0, otherwise it is the sum of the first combination.
total :: Region -> Int
total (Region _ []) = 0
total (Region _ [c:_]) = sum c

编译报错信息

  • Couldn't match expected type t0 Int' with actual type Int'
    • In the first argument of sum', namely c'
      In the expression: sum c
      In an equation for `total': total (Region _ [c : _]) = sum c

错误原因

问题出在模式匹配的语法上:

  • 你期望c绑定到[[Int]]的第一个元素(类型为[Int]),但[c:_]的写法完全不符合预期。
  • [c:_]是在匹配长度为1的外层列表,这个唯一的元素是一个非空内层列表(c:_),因此c实际绑定的是内层列表的第一个元素,类型为Int。
  • sum函数要求参数是可折叠的Int容器(比如[Int]),传入Int类型的值必然触发类型不匹配错误。

修复方案

将第二个分支的模式匹配从[c:_]改为(c:_),这样c会正确绑定到外层列表的第一个元素([Int]类型):

total :: Region -> Int
total (Region _ []) = 0
total (Region _ (c:_)) = sum c

内容的提问来源于stack exchange,提问作者Jeremy Hicks

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:48:26