[英]How does Haskell evaluate the Fibonacci function?
I am currently looking at this function in Haskell which returns the Fibonacci number at position n
我目前正在Haskell中查看此函数,该函数在位置n
返回斐波那契数
fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
Now, it compiles, returns the correct result and everything... but I don't see how Haskell evaluates this function. 现在,它可以编译并返回正确的结果以及所有内容……但是我看不到Haskell如何评估此函数。
Doesn't Haskell always look for a suitable definition and then apply that definition until it cannot anymore (eg reached base case)? Haskell会不会一直寻找合适的定义,然后应用该定义直到不能再使用(例如达到基本情况)?
In that case, this is what I came up with. 在这种情况下,这就是我想出的。 For instance, evaluating fib 3
例如,评估fib 3
fib n = fib (n-1) + fib (n-2)
fib 3 = fib (3-1) + fib (3-2)
fib 3 = fib ((3-1)-1) + fib ((3-1)-2) + fib ((3-2)-1) + fib ((3-2)-2)
fib 3 = fib (((3-1)-1)-1) + fib (((3-1)-1)-2) +
fib (((3-1)-2)-1) + fib (((3-1)-2)-2) +
fib (((3-2)-1)-1) + fib (((3-2)-1)-2) +
fib (((3-2)-2)-1) + fib (((3-2)-2)-2)
...
This could go on forever without giving an actual result. 这可能永远持续下去,而没有给出实际结果。 However, Haskell returns a result. 但是,Haskell返回结果。 So what am I doing wrong? 那我在做什么错?
The order of the equations in the definition does matter. 定义中方程的顺序确实很重要。
The part 那个部分
fib n = fib (n-1) + fib (n-2)
gets applied only when the previous lines do not apply . 仅在前几行不适用时才应用 。 That is, only when n
is not 0
nor 1
. 也就是说,仅当n
不为0
或1
。 Because of this, the step 因此,该步骤
fib 3 = fib (3-1) + fib (3-2)
fib 3 = fib ((3-1)-1) + fib ((3-1)-2) + fib ((3-2)-1) + fib ((3-2)-2)
is wrong: fib (3-2)
is fib 1 = 1
, and not fib ((3-2)-1) + fib ((3-2)-2)
. 是错误的: fib (3-2)
是fib 1 = 1
,而不是fib ((3-2)-1) + fib ((3-2)-2)
。
Another way to look at is is as follows. 另一种查看方法如下。 The whole 3-lines definition can be equivalently expressed using case
as 整个3行定义可以等效地用case
表示为
fib n = case n of
0 -> 0
1 -> 1
m -> fib (m-1) + fib (m-2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.