[Haskell-beginners] Understanding how laziness works

Alexander Batischev eual.jp at gmail.com
Tue Jun 19 22:55:04 CEST 2012


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.

Alexander Batischev

PGP key 356961A20C8BFD03
Fingerprint: CE6C 4307 9348 58E3 FD94  A00F 3569 61A2 0C8B FD03

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: Digital signature
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120620/2fa85209/attachment.pgp>

More information about the Beginners mailing list