List 函数中的非穷举模式(Haskell)
我有两个代码段抛出相同的错误:List 函数中的非穷举模式(Haskell),list,haskell,pattern-matching,List,Haskell,Pattern Matching,我有两个代码段抛出相同的错误: Prelude> sum' [] = 0 Prelude> sum' (x:xs) = x + sum' xs Prelude> sum' [1,2,3,4,5] *** Exception: <interactive>:142:1-25: Non-exhaustive patterns in function sum' Prelude>sum'[]=0 前奏曲>和(x:xs)=x+sum'xs 前奏曲>和[1,2,3,4,5] *
Prelude> sum' [] = 0
Prelude> sum' (x:xs) = x + sum' xs
Prelude> sum' [1,2,3,4,5]
*** Exception: <interactive>:142:1-25: Non-exhaustive patterns in function sum'
Prelude>sum'[]=0
前奏曲>和(x:xs)=x+sum'xs
前奏曲>和[1,2,3,4,5]
***异常::142:1-25:函数sum'中的非穷举模式
以及以下各项:
Prelude> prod [] = 1
Prelude> prod (x:xs) = x * (prod xs)
Prelude> prod [1,2,3,4,5]
*** Exception: <interactive>:139:1-27: Non-exhaustive patterns in function prod
Prelude>prod[]=1
前奏曲>产品(x:xs)=x*(产品xs)
前奏曲>产品[1,2,3,4,5]
***异常::139:1-27:函数prod中的非穷举模式
我一定错过了一个模式,但它是什么?还有,我怎样才能避免这些错误呢?在使用模式匹配定义函数时,我应该如何思考?(我要求提供一种方法/技术)要创建一个模式匹配的函数,或者在ghci的命令行中使用多行,您应该使用
{}
并用分隔代码>在您的情况下:
Prelude> let { sum' [] = 0 ; sum' (x:xs) = x + sum' xs }
Prelude> sum' [1,2,3,4,5]
=> 15
否则,您将只将一个等式(在本例中是最后一个)绑定到函数名sum'
,这就是为什么会出现模式匹配失败的原因您定义了两个sum'
s,请参见: