Random Perl 6 syntax rant

Andy Wardley abw at wardley.org
Wed Apr 2 08:33:08 BST 2008

Jonathan Rockway wrote:
> How would you distinguish between "give me a lazy iterator over each line"
> and "suck everything into an array, then iterate over that"?

I can't think of a case where I would want to differentiate.  In a for loop,
a lazy iterator works just fine (as per the Perl default).  If I want to read
the lines into an array first (or as a side effect) then I would write that
explicitly, perhaps using a .lines method.

   for $item in <IN>                  # lazy iterator over input lines


   for $item IN <IN.lines>            # pre-fetch input lines


   for $item IN <@list = IN.lines>    # so I can check @list.size, for example

This is assuming that <> is required to indicate "I would like to iterate
over this".  But there's no reason (that I can think of OTOH) why IN couldn't
be a stream object which supports an iterator interface directly.  So you
wouldn't need to add <> at all:

   for $item in IN                # IN isa iterator / does iteration

   for $item in IN.lines          # IN.lines returns a list

> Yes, in most cases you will want an iterator... but wouldn't it be
> confusing for some things to act like iterators and others lists (in the
> ... -> context)?  Yes, it would be :P

I'm not sure I follow what you're getting at.  The iterator over a list is
a different thing from the list that it's iterating over.  So no, there
wouldn't be any confusion because they're different things.

This is the approach used in TT.  Every FOREACH loop has an iterator.  If
you don't pass it an iterator (i.e. you specify a list) then it'll create one
for you.

    FOREACH item IN an_iterator   # yay!  we got an iterator

    FOREACH item IN a_list        # creates an iterator for a_list

Either way, you always have an iterator for the loop, regardless of what the
original data source is.


More information about the london.pm mailing list