无限斐波那契序列 [英] Infinite fibonacci sequence
问题描述
我试图在F#中使用序列模仿哈斯克尔着名的无限斐波那契列表。为什么不按预期评估以下顺序?如何评估它?
let rec fibs = lazy(Seq.ofpend
(Seq.ofList [0; 1))
((Seq.map2(+)(fibs.Force())
(Seq.skip 1(fibs.Force())))))
问题是您的代码仍然不够懒: Seq.append
在可以访问结果之前计算,但计算第二个参数( Seq.map2 ...
)需要评估它自己的参数,它强制定义相同的惰性值。这可以通过使用 Seq.delay
函数解决
。您也可以放弃懒惰
包装,并且 list
s已经 seq
s,所以你不需要 Seq.ofList
:
let rec fibs =
Seq.append [0; 1]
(Seq.delay(fun() - > Seq.map2(+)fibs(Seq.skip 1 fibs)))$然而,我个人建议使用一个序列表达式,我发现这个序列表达式更令人愉快(阅读并且更易于正确写入):
let rec fibs = seq {
yield 0
yield 1
产量! Seq.map2(+)fibs(fibs |> Seq.skip 1)
}
I'm trying to imitate Haskell's famous infinite fibonacci list in F# using sequences. Why doesn't the following sequence evaluate as expected? How is it being evaluated?
let rec fibs = lazy (Seq.append
(Seq.ofList [0;1])
((Seq.map2 (+) (fibs.Force())
(Seq.skip 1 (fibs.Force())))))
解决方案 The problem is that your code still isn't lazy enough: the arguments to Seq.append
are evaluated before the result can be accessed, but evaluating the second argument (Seq.map2 ...
) requires evaluating its own arguments, which forces the same lazy value that's being defined. This can be
worked around by using the Seq.delay
function. You can also forgo the lazy
wrapper, and list
s are already seq
s, so you don't need Seq.ofList
:
let rec fibs =
Seq.append [0;1]
(Seq.delay (fun () -> Seq.map2 (+) fibs (Seq.skip 1 fibs)))
However, personally I'd recommend using a sequence expression, which I find to be more pleasant to read (and easier to write correctly):
let rec fibs = seq {
yield 0
yield 1
yield! Seq.map2 (+) fibs (fibs |> Seq.skip 1)
}
这篇关于无限斐波那契序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!