Task

Write a function to flatten the nesting in an arbitrary list of values.

Your program should work on the equivalent of this list:

  [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]

Where the correct result would be the list:

   [1, 2, 3, 4, 5, 6, 7, 8]

Related task

   Tree traversal


void
show_list(list l)
{
    integer i, k;
 
    o_text("[");
 
    i = 0;
    while (i < ~l) {
        o_text(i ? ", " : "");
        if (l_j_integer(k, l, i)) {
            o_integer(k);
        } else {
            show_list(l[i]);
        }
        i += 1;
    }
 
    o_text("]");
}
 
list
flatten(list c, object o)
{
    if (__id(o) == INTEGER_ID) {
        c.append(o);
    } else {
        l_ucall(o, flatten, 1, c);
    }
 
    c;
}
 
integer
main(void)
{
    list l;
 
    l = list(list(1), 2, list(list(3, 4), 5),
             list(list(list())), list(list(list(6))), 7, 8, list());
 
    show_list(l);
    o_byte('\n');
 
    show_list(flatten(list(), l));
    o_byte('\n');
 
    return 0;
}