opApply/opApplyReverse return value types
Bill Baxter
wbaxter at gmail.com
Fri Oct 20 09:14:23 PDT 2006
BCS wrote:
> Bill Baxter wrote:
>
>> BCS wrote:
>>
>>> Jarrett Billingsley wrote:
>>>
>>>>
>>>> This works fine. I am returning -49 from opApply and it works
>>>> fine. I can return 0 from opApply and it works fine. I honestly
>>>> have no idea what the return from opApply is for.
>>>>
>>>
>>> I would assume that the generated delegate different return value for
>>> each goto and the return;
>>>
>>
>> Damn, is that the only reason? Goto from inside a foreach must
>> constitute less than 1% of all use cases. It just doesn't seem right
>> to expose the user to that kind of implementation detail in a core
>> language construct.
>
>
> also labeled breaks and continues:
> [...]
> OTOH the block is a delegate so it could stuff that value into a
> variable local to the outer scope and then return a "quit" value.
> [...]
>
>
> more or less what you proposed
I think that is indeed mostly what I was proposing. The compiler is
rewriting the block anyway, translating gotos into returns, etc, so why
not have it just translate goto's into:
outerscope_var = /value/;
return true;
Then at least then I can write code without worrying about *what* I
should return.
void opApply(void delegate(inout uint) dg)
{
for (int i = 0; i < array.length; i++)
{
if(dg(array[i])) return;
}
}
Not quite is lovely as the ideal:
void opApply(void delegate(inout uint) dg)
{
for (int i = 0; i < array.length; i++)
{
dg(array[i]);
}
}
but the ideal requires magically jumping from dg's scope back to the
outer scope without bothering opApply to check what's going on. It's
not clear to me how to do that. (But I also don't think it's clear that
it would be impossible to achieve).
>>
>> And there's probably even something cleaner using exceptions or scope
>> statements.
>>
>
> Who cares about clean? The compiler's doing it, all that I want is fast
> code.
I agree that foreach shouldn't induce excessive overhead. But maybe I
differ in that I'd gladly take a small speed hit for improved
readability/usability/maintainablility. I don't think foreach needs to
compile down to the exact same code as the best possible for loop.
My perspective on foreach is similar to virtual functions. Virtual
functions offer me a way to make my code cleaner and easier to maintain,
but there is a small penalty to pay for that convenience. In most cases
that penalty is not significant enough to give up the convenience. I
woudn't mind if foreach came with that same level of penalty.
>> I wonder, can you goto out of an inner function? If not, why should
>> you be able to goto out of a foreach block?'
> because it shouldn't act any different than an if block in that respect.
Yeh, agreed. It looks like a normal controlled block, so it should
behave like one.
--bb
More information about the Digitalmars-d-learn
mailing list