leonyu
leonyu

Reputation: 33

Why the following two expressions have different results

fibs = 1:1:[x+y|x <- fibs, y <- tail fibs]

returns

[1,1,2,3,4,5,6,7,8,9]

fibs = 1:1:[x+y|(x, y) <- zip fibs (tail fibs)]

returns

[1,1,2,3,5,8,13,21,34,55...]

Upvotes: 0

Views: 51

Answers (1)

Paul Johnson
Paul Johnson

Reputation: 17786

The first one is evaluating the Cartesian product (i.e. every combination) of fibs and tail fibs, while the second is evaluating the pairwise pairing.

Prelude> [(x,y) | x <- [1,2,3], y <- [4,5,6]]
[(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]

Prelude> [(x,y) | (x,y) <- [1,2,3] `zip` [4,5,6]]
[(1,4),(2,5),(3,6)]

Upvotes: 4

Related Questions