Task

Select certain elements from an Array into a new Array in a generic way.



To demonstrate, select all even numbers from an Array.

As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.




integer
even(integer e)
{
    return !(e & 1);
}
 
list
filter(list l, integer (*f)(integer))
{
    integer i;
    list v;
 
    i = 0;
    while (i < l_length(l)) {
        integer e;
 
        e = l_q_integer(l, i);
        if (f(e)) {
            lb_p_integer(v, e);
        }
 
        i += 1;
    }
 
    return v;
}
 
integer
main(void)
{
    integer i;
    list l;
 
    i = 0;
    while (i < 10) {
        lb_p_integer(l, i);
        i += 1;
    }
 
    l = filter(l, even);
 
    i = 0;
    while (i < l_length(l)) {
        o_space(1);
        o_integer(l_q_integer(l, i));
        i += 1;
    }
    o_byte('\n');
 
    return 0;
}