Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: How To: Make An Iterator

by Anonymous Monk
on Apr 17, 2006 at 19:24 UTC ( [id://543899]=note: print w/replies, xml ) Need Help??


in reply to How To: Make An Iterator

Under Things To Consider:
* The return value indicating exhaustion is important

After choosing a value that is known not to be valid in the list, document it. Allow the user to define their own if it is not possible to know in advance.
An even better approach is to use the iterator in list context and just return an empty list when the list is exhausted.
while (my ($elem) = $iter->()) { ... }
That way you don't need any assumptions, you don't need to make any limitations to the value space of the list, and it'll be easier for the maintainer that doesn't have to remember which list doesn't allow which element and which list uses what to signal list exhaustion.

Replies are listed 'Best First'.
Re^2: How To: Make An Iterator
by Limbic~Region (Chancellor) on Apr 17, 2006 at 22:42 UTC
    Anonymous Monk,
    No, that isn't a better approach. If your iterator is designed to return a list each iteration and an empty list is valid then you will prematurely terminate.

    I stand by my statements though I will concede that it would be fair to say that an empty list is usually safe.

    Cheers - L~R

      If your iterator is designed to return a list each iteration and an empty list is valid then you will prematurely terminate.
      Uhm, the whole idea with the above is that if you want "a list" from the iterator the iterator returns an array reference, just as you do if you want to return two or more "lists" from a subroutine or have several "lists" in a list or array.

      Why on earth would the iterator want to return a list instead of an array reference? That would just make it uncomfortable to use. If you return array references you have a perfectly general, maintainable and safe way to signal exhaustion.
        Anonymous Monk,
        Listen, feel free to do whatever you want with the iterators you build. Feel free to always and forever use the same return type and exhaustion indicator regardless of the situation. I have very rarely found a silver bullet that fits every situation so my tutorial was written from the perspective of flexibility and responsibility.

        Objection noted.

        Cheers - L~R

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://543899]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-04-20 12:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found