Haskell中使用:操作符处理列表时出现类型不匹配错误求助
修复Haskell帕斯卡三角代码的类型错误
错误原因分析
你遇到的类型错误核心在于cur_row函数中的(x : 0)表达式:
- Haskell的
:(Cons)运算符语法是元素 : 列表,要求左右两边类型严格匹配:左边必须是单个元素,右边必须是同类型元素组成的列表。 - 这里
x是[Integer]类型的列表,0是Integer类型的单个值,x : 0试图将一个列表作为元素,拼接到非列表的0前面,导致实际类型变成[[Integer]],但编译器期望的是[Integer],因此触发类型不匹配错误。
修正方案
将cur_row函数中的(x : 0)替换为x ++ [0]——++是列表拼接运算符,两边都是[Integer]类型的列表,完全符合语法要求:
-- Gets the next row given the previous row cur_row :: [Integer] -> [Integer] cur_row x = ans where ans = zipWith (\a b -> a + b) (0 : x) (x ++ [0]) -- Gets the xth row rows_helper :: Int -> [Integer] rows_helper x | x == 1 = [1] | otherwise = cur_row (rows_helper (x - 1)) -- Main Function : Finds the first x rows of the Pascal's Triangle rows :: Int -> [[Integer]] rows x | x == 0 = [] | x == 1 = [[1]] | otherwise = rows (x - 1) ++ [rows_helper(x)]
额外优化建议(可选)
当前的rows函数每次递归都会拼接列表,效率较低,可以改用iterate简化实现,同时提升性能:
rows :: Int -> [[Integer]] rows n = take n $ iterate cur_row [1]
这个版本利用iterate不断基于上一行生成下一行,再用take n截取前n行,代码更简洁高效。
内容的提问来源于stack exchange,提问作者MangoPizza
相关产品推荐
相关产品推荐

