推广Fibonacci型序列(性能)

时间:2014-04-19 21:37:08

标签: performance haskell recursion fibonacci

今天我发现了Haskell Fibonacci的定义:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

探索,我写了“tribonacci”数字:

tribs = 0 : 0 : 1 : zipWith (+) (zipWith (+) tribs (tail tribs)) (drop 2 tribs)

这很好用,所以我尝试使用相同的基本思想推广到任何“斐波纳契型”序列:

nbonacci n   = (take n (repeat 0)) ++ [1] ++ (z n) 
   where z 1 = zipWith (+) (nbonacci n) (drop 1 (nbonacci n))
         z x = zipWith (+) (z (x-1)) (drop x (nbonacci n))

这也有效:它正确地给出了我所追求的序列。不幸的是,即使生成相同的斐波那契和三角洲序列,它也会非常缓慢,慢很多倍。我怎样才能以更好的表现来表达同样的想法呢?

1 个答案:

答案 0 :(得分:6)

您可以使用worker-wrapper transform

nbonacci n = go where
    go = take n (repeat 0) ++ [1] ++ z n
    z 1 = zipWith (+) go (drop 1 go)
    z x = zipWith (+) (z (x-1)) (drop x go)