Fibonacci numbers with initial two values as parameters
fibonacci, haskell, lazy-evaluation
Solution
How about
fib a b = fibs where fibs = a : b : zipWith (+) fibs (tail fibs)
? Use the same method, but with your parameters in scope.
I should add that, in case you are tempted by
fib a b = a : b : zipWith (+) (fib a b) (tail (fib a b)) -- worth trying?
the `where fibs` version ensures that only one infinite stream is generated. The latter risks generating a fresh stream for each recursive invocation of `fib`. The compiler might be clever enough to spot the common subexpression, but it is not wise to rely on such luck. Try both versions in `ghci` and see how long it takes to compute the 1000th element.
Problem
I have been trying to make a infinite fibonacci list producing function that can take first 2 values as parameters. Without specifying the first two values it is possible like this ``` fib = 1 : 1 : zipWith (+) fib (tail fib) ``` Suppose I wanted to start the fibonacci sequence with 5 and 6 instead of 1,1 or 0,1 then I will have to change the above code. But when trying to make a lazy list generator in which I can specify the first 2 values of fibonacci sequence I am stumped. I came up with this but that didn't work. ``` fib a b = a : b : zipWith (+) fib (tail fib) ``` The problem is obvious. I am trying to convert the use of list in the hard-coded one. How can I solve that?