Logo

Programming-Idioms

History of Idiom 57 > diff from v18 to v19

Edit summary for version 19 by :

Version 18

2015-08-23, 00:44:13

Version 19

2015-08-23, 00:46:37

Idiom #57 Filter list

Create list y containing items from list x satisfying predicate p. Respect original ordering. Don't modify x in-place.

Idiom #57 Filter list

Create list y containing items from list x satisfying predicate p. Respect original ordering. Don't modify x in-place.

Code
function Filter(vv:integer):boolean;

begin
  result :=  vv mod 2= 0;
end;

type TFilter=function(v:integer):boolean;

function FilteredArray(const x:TBoundArray;p:TFilter):TBoundArray;
var
  Idx: Integer;

begin
  setlength(result,high(x)+1);
  Idx := 0;
  for v in x do
    if p(v) then
    begin
      result[Idx] := v;
      inc(Idx);
    end;
  setlength(result,Idx);
end;
[...]
  y := FilteredArray(x,@Filter);
Code
function Filter(vv:integer):boolean;

begin
  result :=  vv mod 2= 0;
end;

type TFilter=function(v:integer):boolean;

function FilteredArray(const x:TBoundArray;p:TFilter):TBoundArray;
var
  Idx: Integer;
  v : Integer;

begin
  setlength(result,high(x)+1);
  Idx := 0;
  for v in x do
    if p(v) then
    begin
      result[Idx] := v;
      inc(Idx);
    end;
  setlength(result,Idx);
end;
[...]
  y := FilteredArray(x,@Filter);
Comments bubble
The function Filter defines a demo-filter.
This is/can be passed to the FilteredArray-function.
TBoundArray is a standard type for array of integer;
On some implementation's (e.G: delphi) you have to omit the @ before Filter.
Comments bubble
The function Filter defines a demo-filter.
This is/can be passed to the FilteredArray-function.
TBoundArray is a standard type for array of integer;
On some implementation's (e.G: delphi) you have to omit the @ before Filter.