Haskell:阶乘函数中的非详尽模式
Haskell: Non-exhaustive patterns in factorial function
我尝试在 GHCi 中实现递归阶乘函数,但收到以下错误:
Prelude> fact n = n * fact (n-1)
Prelude> fact 0 = 1
Prelude> fact 1
*** Exception: <interactive>:2:1-10: Non-exhaustive patterns in function fact
这是从哪里来的,以后我该如何避免这个错误?
正如人们在评论中指出的那样,GHCi 8 中的单行定义取代了之前的任何定义。如果要输入多模式定义,则需要使用特殊的 :{
和 :}
代码来开始和结束多行命令。因此,以下工作正常:
Prelude> :{
Prelude| fact 0 = 1
Prelude| fact n = n * fact (n-1)
Prelude| :}
Prelude> fact 10
3628800
Prelude>
(请注意,这仅适用于 GHCi 8,不适用于 7。)
另外,请注意定义中的顺序。在 Haskell 中,模式的顺序很重要,因此如果您首先尝试匹配 fact n
,它将始终匹配,因此永远不会使用您的 fact 0
模式..
编辑:对于 GHCI 7,您需要使用带有适当缩进的 let
语法来输入多模式定义:
Prelude> :{
Prelude| let fact 0 = 1
Prelude| fact n = n * fact (n-1)
Prelude| :}
Prelude> fact 10
3628800
Prelude>
我尝试在 GHCi 中实现递归阶乘函数,但收到以下错误:
Prelude> fact n = n * fact (n-1)
Prelude> fact 0 = 1
Prelude> fact 1
*** Exception: <interactive>:2:1-10: Non-exhaustive patterns in function fact
这是从哪里来的,以后我该如何避免这个错误?
正如人们在评论中指出的那样,GHCi 8 中的单行定义取代了之前的任何定义。如果要输入多模式定义,则需要使用特殊的 :{
和 :}
代码来开始和结束多行命令。因此,以下工作正常:
Prelude> :{
Prelude| fact 0 = 1
Prelude| fact n = n * fact (n-1)
Prelude| :}
Prelude> fact 10
3628800
Prelude>
(请注意,这仅适用于 GHCi 8,不适用于 7。)
另外,请注意定义中的顺序。在 Haskell 中,模式的顺序很重要,因此如果您首先尝试匹配 fact n
,它将始终匹配,因此永远不会使用您的 fact 0
模式..
编辑:对于 GHCI 7,您需要使用带有适当缩进的 let
语法来输入多模式定义:
Prelude> :{
Prelude| let fact 0 = 1
Prelude| fact n = n * fact (n-1)
Prelude| :}
Prelude> fact 10
3628800
Prelude>