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.




;;; Generic filtering procedure which selects from ar elements
;;; satisfying pred
define filter_array(ar, pred);
lvars i, k;
    stacklength() -> k;
    for i from 1 to length(ar) do
       ;;; if element satisfies pred we leave it on the stack
       if pred(ar(i)) then ar(i) endif;
    endfor;
    ;;; Collect elements from the stack into a vector
    return (consvector(stacklength() - k));
enddefine;
;;; Use it
filter_array({1, 2, 3, 4, 5},
             procedure(x); not(testbit(x, 0)); endprocedure) =>