#Traversing list backwards

1 messages · Page 1 of 1 (latest)

flint wave
#

What is the zig way of traversing a list backwards? A ton of the for loop examples are

const bits = [_]u8{ 1, 0, 1, 1 };
for (bits) |bit, i| {
// do stuff here
}

would it be doing a while loop with the index starting from the end and going to 0?

uncut peak
#

maybe unusual not sure. but i've been doing this recently:

const items = [2]u8{ 0, 1 };
{
    var i = @bitCast(isize, items.len) - 1;
    while (i >= 0) : (i -= 1) { _ = items[@bitCast(usize, i)]; }
}
#

otherwise:

const items = [2]u8{ 0, 1 };
{
    var i =  items.len - 1;
    while (true) : (i -= 1) { 
        _ = items[i]; 
        if(i == 0) break; 
    }
}
flint wave
#

would this work

#
 var index = buffer.len - 1;
 while(index >= 0) : (index--) {
    // do stuff by accessing buffer by doing buffer[index]
}      
uncut peak
#

no, in that case, index is a usize and will underflow.

#

think this would also work if you want less verbose but slightly less perf:

const items = [2]u8{ 0, 1 };
for(0..items.len) |i| {
    _ = items[items.len - i]; 
}

EDIT - fixed

flint wave
#

oh thats true

#

is there some cool std thing that would allow one to create an iterator of a list?

#

or a revers iterator?

uncut peak
#

not that i know of.

flint wave
#

i like this one

#
const items = [2]u8{ 0, 1 };
{
    var i =  items.len - 1;
    while (true) : (i -= 1) { 
        _ = items[i]; 
        if(i == 0) break; 
    }
}
#

thank you 🙂

#

is there a reason you do i -= 1 and not i--

#

?

uncut peak
#

i-- not a thing in zig 😆

flint wave
#

damn im slipping ha

#

been reading too much C learning material

uncut peak
#

ha no worries. pretty sure i've typed that into a zig file a few times.

slim heath
#

Alas, I think the while-true is probably the best you can do.
There might be a slightly better alternative that someone suggested a while ago, but I cannot find it in the search unfortunately.
It would certainly be very nice if you just do this though:

for reverse (items) |e| {
    ...
}