Haskell,简单的模式匹配会产生错误

sno*_*now 2 haskell pattern-matching

let countList (x:xs) = 1+countList xs
let countList [] = 0
countList [1,2,3]
*** Exception: <interactive>:35:5-20: Non-exhaustive patterns in function countList
Run Code Online (Sandbox Code Playgroud)

我认为这样做太简单了,但是错误仍然存​​在,我感到震惊

ham*_*mar 12

使用多个let语句意味着你真正定义了两个函数,第二个定义遮蔽了第一个函数.因此,countList [1, 2, 3]抛出异常,因为范围内的定义仅定义为[].

您需要使用单个同时定义两个方程式let.您可以在一行中键入它们,用分号分隔案例

> let countList (x:xs) = 1 + countList xs; countList [] = 0
Run Code Online (Sandbox Code Playgroud)

或使用GHCi的多行语法:{ ... :},确保将第二个countList与第一个对齐.

> :{
| let countList (x:xs) = 1 + countList xs
|     countList [] = 0
| :}
Run Code Online (Sandbox Code Playgroud)