After looking at 'Genie's "for" statement is very problematic' ( 
https://bugzilla.gnome.org/show_bug.cgi?id=688437 ) in a recent discussion I 
thought I would try and make some progress on a resolution.

The for loop
----------------
The for loop is used to iterate over a collection, retrieving each item in the 
collection. For example to iterate over an array:
    var test = new array of string [5]
    for var item in test
        print item
[Aside: I believe this also works with List and Dict, but not sure about 
classes in general or multi-dimensional arrays]

A counter can be added to this process:
    var test = new array of string [5]
    var index = 0
    for var item in test
        print "Position: %s   Value: %s",index.to_string(),item
        index++

It can also be used to iterate over a sequence:
var sequence = new array of int [0,1,2,3,4]
for var item in sequence:
    do_stuff( item )

Genie provides a short hand for generating integer sequences:

for var index = 0 to 4
    do_stuff(index)

for an increasing sequence and:

for var index = 4 downto 0
    do_stuff(index)

for a decreasing sequence.


The problem
-----------------
Bug 688437 identifies two problems with the use of the short hand syntax for 
generating integer sequences in the for loop.

The first is for an increasing sequence where the second value is actually less 
than the first, e.g. for var index = 4 to 0. The bug report states that Genie 
will produce the sequence 0,1,2,3,4. After testing this in Vala 0.18.1 no 
sequence is generated. This is the behaviour the bug reporter wants, so I think 
this part needs to be re-tested by the reporter. The test I used was simply:
    for var index = 4 to 0
        print index.to_string()



The second is for an increasing sequence where the second value is equal to the 
first, e.g. for var index = 0 to 0. This produces a sequence of just one value, 
in this case 0. The bug report states this can cause problems when iterating 
over an empty array.

Resolution
--------------
The simplest short term solution appears to be a documentation change 
emphasising that 'for item in array' is the best way of iterating over an array.

Is it desirable to have 'for var index = x to x' to return an empty sequence 
instead of a sequence of one? That's still up for debate.

An alternative is to deprecate the short hand in the for statement and move to 
a more generalised sequence generator. Originally I though of 'sequence( 0 to  
4 )' as a syntax, but 'sequence' is too general a keyword. For example what 
about 'sequence( "Monday" to "Friday" )'. It should be only for integers, but 
something like 'integer_sequence( 0 to 4 )' is too long. Maybe 'var index = new 
array of int [0 to 4]' or 'var index = new array of int 0 to 4'?

Alistair
_______________________________________________
vala-list mailing list
vala-list@gnome.org
https://mail.gnome.org/mailman/listinfo/vala-list

Reply via email to