Python generators in Java?

Robert Oschler no-mail-please at nospam.com
Mon Nov 15 16:42:39 EST 2004


"Alan Kennedy" <alanmk at hotmail.com> wrote in message
news:I%4md.41892$Z14.16845 at news.indigo.ie...
>
> Hi Robert,
>
> Hmm, I don't see a direct question in your post, so I'll just assume
> that you're generally inquiring about generator style functionality in
java.
>
> If you're looking to achieve the execution efficiency of python
> generators, e.g. in terms of processing sequences one value at a time
> rather than generating the entire sequence and then processing, then you
> should look at java iterators, which are designed specifically for this
> purpose.
>
> Note that java 1.5 brings new syntactic features which support
> iterators, e.g. short-hand for loops like this
>
> public int sumArray(int array[]) {
>    int sum = 0;
>    for(int i : array) {
>      sum += i;
>    }
>    return sum;
> }
>
> Quite pythonic, IMHO.
>
> http://java.sun.com/developer/technicalArticles/releases/j2se15langfeat/
>
> However, if you're looking for the resumable-functions aspect of
> generators, you're out of luck: java doesn't not support them. But note
> that a java iterator will still very likely be more efficient than a
> python generator, albeit that the code won't be as clean.
>
> Note that there is a currently a proposal from the codehaus people to
> add continuations to java, which could make both generators and full
> coroutines possible in java.
>
> http://docs.codehaus.org/display/continuation/Home
>
> Lastly, it would probably be easier to discuss this subject if you gave
> an example of the type of thing you want to do, and some reasons why you
> want to do it that way. Post some python: maybe the java would be
> straightforward.
>
> Regards,
>
> -- 
> alan kennedy
> ------------------------------------------------------
> email alan:              http://xhaus.com/contact/alan

Alan,

Yes it's the resumable aspect of generators I'm after.  For me that is their
main appeal. I'm familiar with iterators from C++, but it's the ability to h
ave a function that maintains it's own "state" (generator) that is
attractive.  It simplifies a lot of thorny programming problems.

Thanks for the link on Java continuations, I'll check that out.

-- 
Robert Oschler
http://www.robotsrule.com/phpBB2/
Robot & Android Discussion Forum





More information about the Python-list mailing list