On Friday, 27 July 2012 at 18:47:34 UTC, Stuart wrote:
[snip]

Ah, but that depends upon the pre-existence of the dirEntries() function. I think perhaps you're missing the point - which is that "Yield" allows you to WRITE a function synchronously which will then be executed lazily, as an iterator. What you have demonstrated there is USING a lazy function. How would I write, in D, a function that would lazily assemble some data and return it as a lazy collection? I mean, without calling existing lazy functions.

Short answer: you'd implement an InputRange, just as dirEntries is
implemented.

When I started learning D, the lack of first-class coroutines ("things that yield") struck me as a real drawback. I had grown very used to
them in Python and in Scheme.

So I learned how to write ranges. I did not totally fall in love with them. I agree with you that there is a conceptual elegance in writing a coroutine as if it were a regular function, just one that happens to include a "yield" keyword that seems to "remember its place" between calls. I'd like to see language-level support for them in D some day.

Having said that, I'm satisfied with ranges. I've seen the fiber and opApply ways of implementing yield, and they are okay. But the fact is, it's usually not that hard to write an input range. Just make a
struct that implements these operations:

http://dlang.org/phobos/std_range.html#isInputRange

Decide what state you need to maintain between calls; determine
meaningful definitions for empty, front, and popFront that read and
manipulate that state.

Write a few of those, and the idiom will become natural to you.

It will feel inside-out with respect to C# enumerators. But it's not inherently bad -- certainly not bad enough to dismiss without deeper study, and certainly not bad enough to immediately jump to fibers or
an opApply-with-mixin trick before you've at least attempted a
range-based solution.

There is a load of reusable library code in D that can be brought to bear on ranges. It's well worth a bit of mental rewiring to benefit
from that.

Best,
Graham

Reply via email to