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.




class MARRAY{T} < $ARR{T} is
  include ARRAY{T};
 
  filter_by(r:ROUT{T}:BOOL):SAME is
    o:MARRAY{T} := #;
    loop e ::= elt!;
      if r.call(e) then
        o := o.append(#MARRAY{T}(|e|));
      end;
    end;
    return o;
  end;
 
end;
 
class MAIN is
  main is
    a ::= #MARRAY{INT}(|5, 6, 7, 8, 9, 10, 11|);
    sel ::= a.filter_by( bind(_.is_even) );
    loop #OUT + sel.elt! + " "; end;
    #OUT + "\n";
  end;
end;