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
相关产品推荐
相关产品推荐

