简单易变的问题,你通常希望一劳永逸地建立桌子,然后不作改动。 在此情况下,你可以避免不得不担心 app事,而不是把建造电化表视为一种行动。
一种办法是利用zy评价,并在我们重新构造时参考表格。
import Data.Array
fibs = listArray (0, n-1) $ 0 : 1 : [fibs!(i-1) + fibs!(i-2) | i <- [2..n-1]]
where n = 100
如果表各要素之间的依附关系使得难以在时间之前提出简单的评估顺序,这种方法就特别有用。 然而,它需要使用箱式阵列或病媒,这可能使这种做法由于间接费用的增加而不适合大型表格。
For unboxed vectors, you have operations like constructN
which lets you build a table in a pure way while using mutation underneath to make it efficient. It does this by giving the function you pass an immutable view of the prefix of the vector constructed so far, which you can then use to compute the next element.
import Data.Vector.Unboxed as V
fibs = constructN 100 f
where f xs | i < 2 = i
| otherwise = xs!(i-1) + xs!(i-2)
where i = V.length xs