I'd like to split a list in Qore like this:
list a = (1,2,3,4,5,6);
list pieces = split_list_into_pieces(a, 2);
printf("%y\n", pieces);
Desired output:
[[1,2], [3,4], [5,6]]
I.e. I want to take a (supposedly long) list and split it into pieces of given (max) length.
I can do it like:
list sub split_list_into_pieces(list a, int length)
{
    int i = 0;
    list ret = ();
    list temp = ();
    foreach any x in (a)
    {
        temp += x;
        i++;
        if (i == length)
        {
            push ret, temp;
            temp = ();
            i = 0;
        }
    }
    if (temp)
    {
        push ret, temp;
    }
    return ret;
}
But it is not very elegant, is it?
Any better solution?
you can do it this way:
list sub list_chunk(list a, int length) {
    list result = ();
    while (a)
        push (result, extract (a, 0, length));
    return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With