Idea: break/continue and scope guards
Derek Parnell
derek at psych.ward
Fri Jul 6 11:35:18 PDT 2007
On Fri, 06 Jul 2007 11:03:04 -0700, BCS wrote:
> mike wrote:
>> Hi!
>>
>> Don't know if that makes any sense or if it would be of any use, but I had an idea lately and wanted to share it here, maybe it's some little thing that could be nice in D.
>>
>> So here we go:
>>
>> ' foreach (customer; customerList)
>> ' {
>> ' foo(customer);
>> ' scope(failure) foo_rollback(customer);
>> '
>> ' bool ok = check_valid_after_foo(customer);
>> ' if (!ok) continue(failure);
>> '
>> ' commit(customer);
>> ' }
>>
>> Basically the idea is to trigger the appropriate scope guards when a break or continue occurs. Another thing where this could be handy is in situations where you loop over an array to search for a specific item and do something when it is found, like:
>>
>> ' foreach (customer; customerList)
>> ' {
>> ' scope(success) result = customer;
>> ' if (customer.ID == wantedID) break(success);
>> ' }
>>
>> What do you think?
>>
>> -mike
>
> [posted in D and D.announce NG, please reply in D ng]
>
> This is much like an idea I had, but backwards from the way I thought of
> it. Add more options to scope, not break/continue.
>
> the second code example would work like this the way I thought of.
>
> ' foreach (customer; customerList)
> ' {
> ' scope(break) result = customer;
> ' if (customer.ID == wantedID) break;
> ' }
>
> other scope "types":
> goto // exit by goto
> goto : label // exit by goto to a given label
> continue // duh
> enter // execute on entrance by any means (goto, switch, etc.)
> out // used in a loop same as exit but for scope including
> // loop. Note: scope(exit) in a loop runs on each cycle,
> // 'out' would only run at the end of the last cycle.
I like this too. I think scope(next) rather than scope(exit) though.
I vaguely remember that this idea was first documented back in the 1960s by
Donald Knuth or Edsger Dijkstra, but I can't locate the reference just now.
--
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell
More information about the Digitalmars-d
mailing list