Re: [Vala] Two small new features



On Mo, 2010-09-27 at 02:55 +0200, Frederik Sdun wrote:
* Jürg Billeter <j bitron ch> [25.09.2010 18:22]:
Hi Frederik,

On Sat, 2010-09-25 at 17:20 +0200, Frederik Sdun wrote:
i just pushed two little patches to [0] which allows to add an else
statement to foreach and catch statements.
For foreach, the else block is called if there is no iteration in the
loop.
For the catch clause, the else block is called if no exception was
caught and before the finally statement.

Here are 2 little examples:
foreach:
void print_array (string[] args) {
        foreach (var arg in args) {
                debug(@"arg: $arg");
        } else {
                debug("no args"); //called if the array is empty
        }
}
void main (string[] args)
{
        string[] test_1 = new string[0];
        string[] test_2 = new string[2]{"hello", "world"};
        print_array (test_1);
        print_array (test_2);
}

The `else` seems to indicate that the code in the else block is reached
if the foreach is not successful. However, zero iterations are by no
means an unusual condition. In general, I'd like to keep (control flow)
statements relatively simple as, in my opinion, it's ok that the code
gets more complex when the control flow is more complex. You don't want
to hide complex control flow.

This is just for convinience, for the not unusual case of:
if (args.length > 0)
    foreach(...)
else
    ...
That would be confusing for people with Python background, as 'else' is
executed when the loop is exhausted; that is if there was no
return/break in the loop body.

Python documentation of 'for'
=============================
When the items are
exhausted (which is immediately when the sequence is empty), the suite
in the ``else`` clause, if present, is executed, and the loop
terminates.

A ``break`` statement executed in the first suite terminates the loop
without executing the ``else`` clause's suite.  A ``continue``
statement executed in the first suite skips the rest of the suite and
continues with the next item, or with the ``else`` clause if there was
no next item.

-- 
Julian Andres Klode  - Debian Developer, Ubuntu Member

See http://wiki.debian.org/JulianAndresKlode and http://jak-linux.org/.





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]