Generating Fibonacci numbers in Haskell?

前端 未结 11 1029
有刺的猬
有刺的猬 2020-11-29 18:35

In Haskell, how can I generate Fibonacci numbers based on the property that the nth Fibonacci number is equal to the (n-2)th Fibonacci number plus the (n-1)th Fibonacci numb

11条回答
  •  萌比男神i
    2020-11-29 19:17

    fibs :: [Integer]
    fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
    

    at first, with fibs and tail fibs, we can get the 3rd element:

    fibs                        : [1, 1, ?
    tail fibs                   : [1, ?
    zipWith (+) fibs (tail fibs): [2, ?
    

    now, we know the 3rd is 2, we can get the 4th:

    fibs                        : [1, 1, 2, ?
    tail fibs                   : [1, 2, ?
    zipWith (+) fibs (tail fibs): [2, 3, ?
    

    now the 5th:

    fibs                        : [1, 1, 2, 3, ?
    tail fibs                   : [1, 2, 3, ?
    zipWith (+) fibs (tail fibs): [2, 3, 5, ?
    

    and so on ..

提交回复
热议问题