Haskell:阶乘函数中的非穷举模式 [英] Haskell: Non-exhaustive patterns in factorial function

查看:263
本文介绍了Haskell:阶乘函数中的非穷举模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过在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中,模式顺序很重要,所以如果你首先尝试匹配 fact n ,它总是匹配的,所以你的事实上0

编辑:对于GHCI 7,您需要使用 let 语法和适当的缩进来输入一个多模式定义:

  Prelude> :{
Prelude |让事实0 = 1
Prelude |事实n = n * fact(n-1)
Prelude | :}
前奏>事实10
3628800
前奏>


I've tried implementing a recursive factorial function in GHCi, but I'm receiving the following error:

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

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 :{ 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> 

(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 fact n first, it will always match, so your fact 0 pattern will never be used..

Edit: For GHCI 7, you need to use the 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> 

这篇关于Haskell:阶乘函数中的非穷举模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆