Lots of low hanging fruit in Phobos

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Mar 7 22:27:02 PST 2014


On Sat, Mar 08, 2014 at 03:27:15AM +0000, bearophile wrote:
> Adam D. Ruppe:
> 
> >Wordier than
> >yield ShortRange() { yield 50; yield 60; yield 70; }
> >
> >but the same idea.
> 
> In general a typed syntax could be:
> 
> yield(int) ShortRange() { yield 50; yield 60; yield 70; }
> 
> Or even:
> 
> yield(auto) ShortRange() { yield 50; yield 60; yield 70; }
> 
> So yield(auto) could be sugar for yield(auto):
> 
> yield ShortRange() { yield 50; yield 60; yield 70; }
[...]

Yield syntax is generally not a big deal with simple ranges, but once
you start needing recursion and branching logic, things become
significantly hairier without yield. For example:

	yield ComplicatedRange(int arg) {
		if (arg == 0) {
			foreach (i; 0 .. 10)
				yield i;
		} else if (arg >= 1 && arg <= 5) {
			yield 10;
			yield 20;
			yield 30;
		} else if (arg >= 6) {
			foreach (i; 10 .. 20) {
				if (i >= 5 && i < 9) {
					yield 40;
					yield 50;
				} else {
					yield i*2;
				}
			}
		}
	}

With yield, the branching logic is clear and relatively easy to follow.
Without yield, this will turn into a nasty mess of nested state
variables, due to the different numbers of yielded items within nested
conditional blocks.

(Of course, you could argue that if things get this complicated, one
should be splitting it up into multiple composed ranges instead, but not
everything is readily decomposible.)


T

-- 
Bare foot: (n.) A device for locating thumb tacks on the floor.


More information about the Digitalmars-d mailing list