我在 Haskell 中看到了这种斐波那契数的实现,我仍在试图弄清楚为什么它可以正常工作。所以显然,斐波那契数可以使用zipWith函数以非常紧凑的方式编写。实现如下所示
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
To understand better what is happening here I looked at the documentation of the zipWith function. This function adds two lists [a], [b] together using the given function (a -> b -> c). In our case the function is a simple addition. If the two lists [a] and [b] have different length (in our case list [b] is always one element shorted than list [a]) zipWith simply starts at the beginning of both lists and adds them. If the end of one list is reached it just stops no matter if the end of the other list is already reached.
在递归的第一步中,使用 [0,1] 和 tail[0,1] = [1] 调用 zipWith。这导致另一个 1 => [0, 1, 1]。在递归的第二步中,使用 [0,1,1] 和 [1,1] 调用 zipWith,导致 [0+1,1+1] = [1,2]。所以对我来说很明显递归创建了正确的斐波那契数,但我不完全理解为什么只有 zipWith 步骤之后的最后一个数字被添加到结果中,而不是整个列表。也许有人可以向我解释。那将非常有帮助。非常感谢。