Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is going on in this function (haskell)?

I have this haskell function that I don't quite understand.

ns :: [Integer]
ns = 0 : [n+k | (n, k) <- zip ns [1,3..]]

I am asked to "take 3 ns".

I thought ns was constant so it would only zip with the first element of the list, giving (0,1). Then when added gives an answer of 1. Then it says "take 3 ns" so I zipped 0 with the first 5 elements of the list, giving... (0,1),(0,3), (0,5) and then when added, I get a final answer of [1,3,5]. However this isn't the correct answer.

What is actually happening to ns? I'm struggling to understand...

like image 836
user3138212 Avatar asked Jan 11 '23 12:01

user3138212


1 Answers

haskell is lazy so you can have recursive definitions. Here it is laid out.

ns = 0 : something

(n,k) <- zip (0 : something ) [1,3,5,7...]
(n,k) <- [(0,1) : something )

ns = 0 : 1 : something

(n,k) <- zip ( 0 : 1 : something ) [3,5,7...]
(n,k) <- (0,1) : (1,3) : something

ns = 0 : 1 : 4 : something

(n,k) <- zip ( 0 : 1 : 4 : something ) [5,7...]
(n,k) <- (0,1) : (1,3) : (4,5) : something

ns = 0 : 1 : 4 : 9 : something

....

See how we determine what the next tuple is then add its two elements. This allows us to determine the next element.

like image 148
DiegoNolan Avatar answered Jan 18 '23 20:01

DiegoNolan