[英]Simple pattern matching in Haskell
I'm a beginner in Haskell, and I tried entering the following in WinGHCi: 我是Haskell的初学者,我尝试在WinGHCi中输入以下内容:
Prelude> factorial 0=1
Prelude> factorial n=n*factorial (n-1)
Prelude> factorial 5
But when I did this, WinGHCi got stuck and didn't do anything. 但是当我这样做时,WinGHCi卡住了,什么也没做。 Why didn't it print out the factorial of 5?
为什么不打印出阶乘5?
When you write in GHCi 当您用GHCi编写时
> let x = 4
> let x = 5
the second definition overrides the first one, removing it from the environment. 第二个定义将覆盖第一个定义,并将其从环境中删除。 This also holds for functions.
这也适用于功能。
> let f 0 = 1
> let f n = 1 + f (n-1)
is equivalent to 相当于
> let f n = 1 + f (n-1)
which will recurse forever on any input. 这将永远在任何输入上递归。
In GHCi, you can have both using 在GHCi中,您可以同时使用
> let f 0 = 1 ; f n = 1 + f (n-1)
but the best approach is to edit a .hs
file, write your definitions there, and then load it in GHCi. 但是最好的方法是编辑
.hs
文件,在其中编写定义,然后将其加载到GHCi中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.