Nice generator library in CVS
Just committed a new package into the Nice standard library: nice.functional. Currently it contains all sorts of methods for working with iterators and generators. All the same methods are defined for each, but the two styles reflect some of the philosophical leanings of Java and Nice.
I use the word "iterator" to refer to java.util.Iterators, which can be seamlessly used in Nice without any special effort. I use "generator" to refer to a more functional version of iterators. A generator is simply a method that takes no arguments, and returns a new element each time it is called. When it has no more elements to yield, it calls stop(). Here's a simple example:
/**
* A generator which yields natural numbers.
*/
()->int naturals()
{
var int num = 1;
return (()=>num++);
}
This method returns a generator which will yield consecutive integers starting with 1 and continuing forever (well, until int wraps). The new generator library will let you do some interesting things with this generator:
//return only odd numbers let odds = naturals().filter(int n => n % 2 != 0); //Add the first 10 numbers togther: let sum = naturals().take(10).fold(0, (int acc, int n)=> acc + n); //Generate consecutively numbered filenames: let fileNameGenerator = naturals().map( int n => "backup_" + n + ".zip");
One of the really nice things about generators, other than their general convenience, is that they let you deal easily with potentially infinite sequences of elements, and actually build only those elements you actually use. Lazy languages like Haskell make this their default mode of operation. That's not Nice's style, but it's a great tool to have available when you need it.
