Generators and Iterators a la Python

Writing and using Classes in Dyalog APL

Re: Generators and Iterators a la Python

Postby petermsiegel on Tue Dec 18, 2012 12:48 am

Nice set of strategies that all work nicely. Truth to tell, these approaches address 95% of all the cases. One nice thing about the YIELD model (of Python, etc.) is that it allows you to be in any arbitrary state without rebuilding it. That said, there is a nice way to simulate the use of YIELD (pass a return-like value from a function and wait for next request, without actually returning) using threads and tokens.

Example: you want to use sequential prime number and set up a prime number generator which does not know how far down the infinite list you (the caller) wants to go. The caller initiates the prime number routine as a thread; it "yields" the next prime number and waits for the next request in a loop; the caller grabs the yielded numbers in turn using a Next call for an object hiding the modest complexity; under the covers token puts and gets take care of the synchronization and a ⎕SIGNAL EndLoop (defined as an appropriate number) allows the prime routine's infinite loop to be terminated appropriately. The prime number routine doesn't need to preserve state, since it never exits-- until the caller is done with it.
petermsiegel
 
Posts: 159
Joined: Thu Nov 11, 2010 11:04 pm

Previous

Return to Object Oriented Programming

Who is online

Users browsing this forum: No registered users and 1 guest