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

Haskell类型匹配错误排查:计算数字幂和时遇类型不匹配问题

Haskell类型匹配错误修复

问题背景

在解决Codewars的kata时,反复遇到类型匹配错误,调整语法后仍无法定位问题。

编写的代码

eqSumPowDig :: Int -> Int -> [Int]
eqSumPowDig hmax po = [x | x<-[2..hmax], expo (show x) po]
                                              where expo :: String -> Int -> Bool
                                                    expo b e = sum [(read n)^e | n<-b] == b

错误信息(翻译后)

• 无法匹配类型‘Char’与‘[Char]’
  期望类型: String
  实际类型: Char
• 在‘read’的第一个参数中,即‘n’
  在表达式中: (read n)
  在‘sum’的第一个参数中,即‘[(read n) | n <- b]’
  |
6 |                                                     expo b e = (sum [(read n) | n<-b]) == b
  |                                                                            ^

修复后的代码

eqSumPowDig :: Int -> Int -> [Int]
eqSumPowDig hmax po = [x | x<-[2..hmax], expo (show x) po]
                                              where expo :: String -> Int -> Bool
                                                    expo b e = sum [(read [n])^e | n<-b] == read b

错误原因与修复说明

  • 第一个错误:遍历字符串b时,n是单个Char类型,但read函数要求输入String(即[Char]),所以需要将n包装成单元素列表[n],让类型匹配。
  • 第二个隐藏错误:等式左边sum计算结果是Int,右边的b是String,类型不匹配,需要用read b将字符串转为整数后再比较。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:45:42