哈斯克尔斐波那契解释 [英] Haskell Fibonacci Explanation
问题描述
我知道这个问题之前已经被问过了, ,但没有一个答案解决了我用可视化结果的问题。
代码是使用 从我的理解中,它首先添加了 很多Google Googled的参考文件已经将上面的行可视化为$ b $ (+)[1,1,< thunk>]([1,< thunk>])。 我的问题是这样的: 为什么上面一行中的 不应该包含整个列表加上 这个中间步骤是错误的,因为 回想一下zipWith在一般情况下的作用: 如果直接应用该定义,您可以获得以下扩展: I am quite new to Haskell and I'm trying to wrap my head around how the lazy expression of Fibonacci sequences work. I know this has been asked before, but none of the answers have addressed an issue I'm having with visualising the result. The code is the canonical one using I understand the following: From my understanding, it first adds A lot of references I've Googled have then proceeded to "visualise" the line above as My question is this: Why is the Shouldn't This intermediate step is wrong because Recall what zipWith does in the general case: If you apply the definition directly you get this expansion:
这篇关于哈斯克尔斐波那契解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! zipWith 的规范代码。 code $
$ b $ $ p $ fibs = 0:1:zipWith(+)fibs(tail fibs)
$ b
$ b zipWith
直接将两个列表拉到一起
尾部抓取除第一个元素列表
thunks
。
[0,1,< thunk>]
和 [ 1,< code>使用
zipWith(+)
给出 [1,< thunk>]
。所以,现在你有
pre $ fibs = 0:1:1:zipWith(+)fibs(尾纤)
fibs
组件仅与 [1,1,< ; thunk>]
而不是 [0,1,1,< thunk>]
?
< thunk>
? zipWith
一对物品:
fibs = 0:1:1:zipWith(+)fibs(尾纤)
zipWith f(x:xs)(y:ys)=(fxy):zipWith f xs ys
fibs = 0:1:zipWith +)fibs(tail fibs)#fibs = [0,1,...]
= 0:1:zipWith(+)[0,1,...](tail [0,1,.. 。])#tail fibs = [1,...]
= 0:1:zipWith(+)[0,1,...] [1,...]#应用zipWith
= 0:1:(0 + 1:zipWith(+)[1,0 + 1,...] [0 + 1,...])
= 0:1:1:zipWith(+ [1,1,...] [1,...]#应用zipWith
= 0:1:1:(1 + 1:zipWith(+)[1,1 + 1,...] [1 + 1,...])
= 0:1:1:2:zipW ith(+)[1,2,...] [2,...]#应用zipWith
= 0:1:1:2:(1 + 2:zipWith(+)[2,1+ 2,...] [1 + 2,...])
= 0:1:1:2:3:zipWith(+)[2,3 ...] [3,...] #apply zipWith
:
zipWith
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
zipWith
literally zips two lists togethertail
grabs all but the first element of a listthunks
.[0,1,<thunk>]
and [1,<thunk>]
using zipWith (+)
to give [1,<thunk>]
. So now you havefibs = 0 : 1 : 1 : zipWith (+) fibs (tail fibs)
fibs = 0 : 1 : 1 : zipWith (+) [1,1,<thunk>] ([1,<thunk>]).
fibs
component in the line above only corresponding to [1,1,<thunk>]
instead of [0,1,1,<thunk>]
? fibs
contain the entire list plus <thunk>
? zipWith
has already processed the first pair of items:fibs = 0 : 1 : 1 : zipWith (+) fibs (tail fibs)
zipWith f (x:xs) (y:ys) = (f x y) : zipWith f xs ys
fibs = 0 : 1 : zipWith (+) fibs (tail fibs) # fibs=[0,1,...]
= 0 : 1 : zipWith (+) [0,1,...] (tail [0,1,...]) # tail fibs=[1,...]
= 0 : 1 : zipWith (+) [0,1,...] [1,...] # apply zipWith
= 0 : 1 : (0+1 : zipWith (+) [1,0+1,...] [0+1,...])
= 0 : 1 : 1 : zipWith (+) [1,1,...] [1,...] # apply zipWith
= 0 : 1 : 1 : (1+1 : zipWith (+) [1,1+1,...] [1+1,...])
= 0 : 1 : 1 : 2 : zipWith (+) [1,2,...] [2,...] # apply zipWith
= 0 : 1 : 1 : 2 : (1+2 : zipWith (+) [2,1+2,...] [1+2,...])
= 0 : 1 : 1 : 2 : 3 : zipWith (+) [2,3...] [3,...] # apply zipWith
: