1

在 ghci 中,这段代码:

let max [] = error "maximum of empty list"  

let max [x] = x  

let max (x:xs)   
    | x > maxTail = x  
    | otherwise = maxTail  
    where maxTail = max xs 

导致错误:*** Exception: <interactive>:26:5-106: Non-exhaustive patterns in function max

这里的不竭模式是什么?满足零元素、单元素和多元素列表吗?

更新 : 在此处输入图像描述

更新 2:

在此处输入图像描述

更新 3:

在 Debian (Raspberry Pi) 上按预期工作:

在此处输入图像描述

4

2 回答 2

8

通过使用三个单独let的 s,您定义了三个单独的、非详尽的函数,名为max,每个函数都覆盖前面的函数。为了使用 定义多案例函数let,您使用let关键字 one,然后在每个模式的相同缩进处重复函数签名,如下所示:

let max [] = error "maximum of empty list"
    max [x] = x
    max (x:xs)
      | x > maxTail = x
      | otherwise = maxTail
      where maxTail = max xs

为了让这个(或任何其他占用多行的代码)在 GHCI 中工作,您需要通过输入来启动多行模式,:{然后使用:}或将其全部写在一行中,;而不是换行符(除非在|您只写前面|没有;或换行符的地方)。

于 2015-07-22T22:08:15.913 回答
1

GHCi(通常是let)不允许您以这种方式定义函数。您只需定义 3 个函数,每次都用另一个函数覆盖。

如果您想继续使用 GHCi,请编写如下内容:

let max list = case list of
    [] -> error "maximum of empty list"  
    [x] -> x  
    (x:xs) -> 
      if x > maxTail then x else maxTail  
      where maxTail = max xs 
于 2015-07-22T21:54:54.213 回答