Proposed new syntax

Paul Rubin no.email at nospam.invalid
Mon Aug 14 23:26:12 EDT 2017


Steve D'Aprano <steve+python at pearwood.info> writes:
> It's quite clever, actually, in that it gives *pseudo* random-access
> with lazy evaluation. You can evaluate the Nth element without
> evaluating the earlier ones. But you can't do so without *storing* the
> previous ones, they have to be allocated, with only the actual
> evaluation being delayed.

Look at any of the memoization packages for ways around that.  Or of
course you could just write a function instead of a list...

> In Haskell, you cannot get the last N elements of a list without
> allocating memory for the previous ones.

    lastn n xxs@(x:xs)
      | length (take n xs) == n-1 = xxs
      | otherwise = lastn n xs

    main = print . lastn 5 $ [1..10000000]

    *Main> main
    [9999996,9999997,9999998,9999999,10000000]

works for me.  The 10000000 list nodes all get allocated, but are
immediately freed, so only 5 cells have to be in memory at a time.  In
principle a fancy enough compiler optimization could get rid of all the
allocation completely.



More information about the Python-list mailing list