
Apologies for the maybe double post (no subject and hadn't confirmed the mailing list first time I sent this). Hi, Here's a simple expression double ( double [1,2,3,4] ) !! 0 The 1st element of a list is double ( 1*2 : double [2,3,4] ) !! 0 1*2*2 : double ( double [2,3,4 ] ) !! 0 1*2*2 4 calculated without having to traverse the rest of the list due to laziness. But how far does the laziness extend? For example, if I take the 2nd element double (double [1,2,3,4]) !! 1 Do we have 1*2*2 : double ( 2*2 : double [3,4] ) !! 1 1*2*2 : 2*2*2 : double ( double [3,4] ) !! 1 2*2*2 8 Resulting in 8. I assume that the 1st list entry 1*2*2 doesn't actually get calculated, but the expression does get formed? The second element (index 1) gets formed, isolated (by !!) and calculated as the return value. And then things can happily stop. What I'm checking is that the laziness doesn't some how magically extend to not having to form the preceding expressions that make up the resulting list? Or can Haskell recognize that this is like doing function composition i.e., (double . double) [ 1 2, 3, 4 ] !! 1 Thanks for any answer. Cheers, Matt. p.s, I kinda hope things are how I've assumed as the example finally shows me some concrete benefit of function composition which has never seemed important given it's so easily re-written as application.

Hello! On Tue, Jun 19, 2012 at 05:20:15PM +0100, Matt Ford wrote:
I assume that the 1st list entry 1*2*2 doesn't actually get calculated, but the expression does get formed? The second element (index 1) gets formed, isolated (by !!) and calculated as the return value. And then things can happily stop.
You're right. The spine of the list is being formed, but it doesn't necessarily evaluate values in the cells of the list. Basically, you can imagine some linked list where each cell have two pointers: one pointing to the next element (or thunk) and another pointing to the value (or thunk) of that cell. When you ask for some element of the list, linked list is being built up to the element you asked for, but only that thunks that are "next elements" are being evaluated - values that aren't used stay being thunks. Now, in your particular example you have constant index and constant list, so I'm pretty sure any Haskell compiler would simply execute the code and put the result into program. But that's only an expectation, not knowledge, so please be critical about it. -- Regards, Alexander Batischev PGP key 356961A20C8BFD03 Fingerprint: CE6C 4307 9348 58E3 FD94 A00F 3569 61A2 0C8B FD03
participants (2)
-
Alexander Batischev
-
Matt Ford