Representation of Fibonacci numbers using list comprehension in Haskell

I wrote the following code to create a list containing Fibonacci numbers.

fibonacci = [a + b | a <- 1:fibonacci, b <- 0:1:fibonacci]

I expect the output of the list to be [1,2,3,5,8,13..], however the output is not a Fibonacci sequence.

I can’t understand why this is not working.

My reasoning is that if the Fibonacci numbers [1,2,3,5,8,13..], then this will be equal to the sum of 2 lists [1,1,2,3,5,8,13..]and [0,1,1,2,3,5,8,13..], which are equivalent to 1:[1,2,3,5,8,13..]and 0:1:[1,2,3,5,8,13..]or 1:fibonacciand0:1:fibonacci

I was looking for other ways to implement this sequence, however I would really like to know why my code does not work.

+4
source share
3 answers

Problem

WITH

fibonacci = [a + b | a <- 1:fibonacci, b <- 0:1:fibonacci]

. :

x = [a + b | a <- [1, 2], b <- [3, 4]]

:

[1 + 3, 1 + 4, 2 + 3, 2 + 4]

Live demo

zipWith

, , zipWith:

fibonacci :: [Int]
fibonacci = zipWith (+) (1:fibonacci) (0:1:fibonacci)

Live demo

+6

  • Non-
  • for -loops

. , , .

fibonacci = 
  for i in 1:fibonacci:
    for j in 0:1:fibonacci:
      i + j

, , - , . zipWith , , " "

fibonacci = zipWith (+) (1:fibonacci) (0:1:fibonacci)
fibonacci = zipWith (+) (0:1:fibonacci) (1:fibonacci)          -- (+) is commutative
fibonacci = zipWith (+) (0:1:fibonacci) (tail (0:1:fibonacci)) -- def of tail

fibonacci' = 0:1:fibonacci
fibonacci' = 0:1:zipWith (+) (0:1:fibonacci) (tail (0:1:fibonacci))
fibonacci' = 0:1:zipWith (+) fibonacci' (tail fibonacci')

fibonacci = drop 2 fibonacci'

ParallelListComprehension, zip-

{-# ParallelListComp #-}
fibonacci = [a + b | a <- 1:fibonacci | b <- 0:1:fibonacci]

> take 10 fibonacci
[1,2,3,5,8,13,21,34,55,89]
+8

. , , , zip.

To see the difference, consider:

Prelude> let fibs = [ a + b | (a,b) <- zip (1 : fibs) (0 : 1 : fibs) ]
Prelude> take 10 fibs
[1,2,3,5,8,13,21,34,55,89]

It works as you expected.

There is a Haskell syntax extension that allows for parallel understanding, so the syntax zip for you. You can enable it with -XParallelListCompand then write:

Prelude> let fibs = [ a + b | a <- 1 : fibs | b <- 0 : 1 : fibs ]
Prelude> take 10 fibs
[1,2,3,5,8,13,21,34,55,89]
+6
source

Source: https://habr.com/ru/post/1546553/


All Articles