Haskell:阶乘函数中的非穷举模式 [英] Haskell: Non-exhaustive patterns in factorial function
问题描述
我试过在GHCi中实现递归阶乘函数,但我收到以下错误:
Prelude>事实n = n *事实(n-1)
前奏>事实上0 = 1
前奏>事实1
***异常:< interactive>:2:1-10:函数fact中的非穷举模式
这是从哪里来的,我怎样才能避免将来发生这种错误?
正如人们在评论中指出的那样,GHCi 8的单行定义取代了之前的定义。如果你想输入一个多模式定义,你需要使用特殊的:{
和:}
代码开始和结束多行命令。因此,以下工作正常:
Prelude> :{
Prelude |事实上0 = 1
Prelude |事实n = n * fact(n-1)
Prelude | :}
前奏>事实10
3628800
前奏>
(请注意,这仅适用于GHCi 8,不适用于7)。
另外,请注意定义中的顺序。在Haskell中,模式顺序很重要,所以如果你首先尝试匹配 编辑:对于GHCI 7,您需要使用 I've tried implementing a recursive factorial function in GHCi, but I'm receiving the following error: Where is this coming from, and how can I avoid this mistake in the future? As people have pointed out in the comments, a definition on a single line in GHCi 8 replaces any previous definition. If you want to enter a multi-pattern definition, you need to use the special (Note that this is applicable to GHCi 8 only, not 7.) Also, mind the order in your definition. In Haskell, order of patterns matters, so if you try to match Edit: For GHCI 7, you need to use the
这篇关于Haskell:阶乘函数中的非穷举模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! fact n
,它总是匹配的,所以你的事实上0 $ c
let
语法和适当的缩进来输入一个多模式定义:
Prelude> :{
Prelude |让事实0 = 1
Prelude |事实n = n * fact(n-1)
Prelude | :}
前奏>事实10
3628800
前奏>
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
:{
and :}
codes to start and end a multi-line command. So, the following works fine:Prelude> :{
Prelude| fact 0 = 1
Prelude| fact n = n * fact (n-1)
Prelude| :}
Prelude> fact 10
3628800
Prelude>
fact n
first, it will always match, so your fact 0
pattern will never be used..let
syntax with appropriate indentation to enter a multi-pattern definition:Prelude> :{
Prelude| let fact 0 = 1
Prelude| fact n = n * fact (n-1)
Prelude| :}
Prelude> fact 10
3628800
Prelude>