Haskell中列表上的模式匹配失败

Jer*_*ert 2 haskell design-patterns list match

我刚刚开始使用Haskell,偶然发现了一个问题.根据Haskell的说法,我有一个模式匹配失败,但我没有看到如何.这是我尝试执行的代码:

statistics ::   [Int] -> (Int, Int, Int)
statistics [gradelist] = ( amountParticipants, average, amountInsufficient)
                        where
                            amountParticipants= length [gradelist]
                            average= sum[gradelist] `div` amountParticipants
                            amountInsufficient= length [number| number<- [gradelist], number<6]
Run Code Online (Sandbox Code Playgroud)

我将'统计'称为:

statistics[4,6,4,6]
Run Code Online (Sandbox Code Playgroud)

这导致模式匹配失败,而我期望看到:(4,5,2)

statistics[6]
Run Code Online (Sandbox Code Playgroud)

给出答案:(1,6,0)(这是正确的).有人能告诉我为什么我的第一个电话会导致这种模式匹配?因为我很确定我会列出一个列表作为参数

Ste*_*ans 7

如果你写的是statistics [gradelist] = ...你对包含一个被称为的唯一元素的单例列表进行模式匹配gradelist.因此,您的函数仅定义为长度恰好为1的列表(例如[6]); 对于空列表([])或具有两个或更多元素(例如[4,6,4,6])的列表,它是未定义的.

您的函数的正确版本将会读取

statistics :: [Int]     -> (Int, Int, Int)
statistics    gradelist =  (amountParticipants, average, amountInsufficient)
  where
    amountParticipants = length gradelist
    average            = sum gradelist `div` amountParticipants
    amountInsufficient = length [number| number <- gradelist, number < 6]
Run Code Online (Sandbox Code Playgroud)

正如@thoferon所说,你还需要对gradelist空的情况做出特殊安排,以避免在计算时除以零average.