Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #57 Filter list

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

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);
for Item of X loop
   if P (Item) then
      Y.Append (Item);
   end if;
end loop;
(def y (filter p x))
#include <ranges>
auto y = x | std::views::filter(p);
#include <algorithm>
#include <iterator>
std::copy_if (x.begin (), x.end (), std::back_inserter(y), p);
using System.Linq;
var y = x.Where(p).ToList();
var y = x.FindAll(p);
import std.algorithm.iteration;
auto y = x.filter!(p);
import std.algorithm;
auto y = [1, 2, 3, 4, 5].filter!(a => a%2==0);
var y = x.where(p).toList();
y = for item <- x, p.(item), do: item
y = Enum.filter(x, p)
Y = lists:filter(P, X).
Y = [I || I <- X, P(X)].
y = pack(x,mask=p(x))
import "slices"
del := func(t *T) bool { return !p(t) }

y := slices.DeleteFunc(slices.Clone(x), del)
func filter[S ~[]T, T any](x S, p func(T) bool) S {
	var y S
	for _, v := range x {
		if p(v) {
			y = append(y, v)
		}
	}
	return y
}
n := 0
for _, v := range x {
	if p(v) {
		n++
	}
}
y := make([]T, 0, n)
for _, v := range x {
	if p(v) {
		y = append(y, v)
	}
}
y := make([]T, 0, len(x))
for _, v := range x{
	if p(v){
		y = append(y, v)
	}
}
def y = x.findAll(p)
y = filter p x
y = x.filter(p);
import java.util.ArrayList;
import java.util.List;
List<T> y = new ArrayList<>();
for (T t : x) if (p.test(t)) y.add(t);
List<T> y = x.stream().filter(p).toList();
val y = x.filter(p)
(setf y (remove-if-not p x))
y = {}
for _, v in ipairs(x) do
	if p(v) then y[#y+1] = v end
end
local y={}
for _,v in ipairs(x) do
 if p(v)==true then 
  table.insert(y,v)
 end
end
@import Foundation;
NSArray *y=[x filteredArrayUsingPredicate:p];
function p($element) {  /* .... */ }

$y = array_filter ($x, "p");
# You can use a subroutine as your predicate
@primes_less_than_100 = grep { is_prime($_) } 1 .. 99;

# You can also write your predicate inline
@odd_numbers = grep { $_%2 == 1 } 1 .. 99;
y = [element for element in x if p(element)]
y = list(filter(p, x))
y = x.select(&:p)
let y: Vec<_> = x.iter().filter(p).collect();
val y = x.filter(p)
(define y (filter p x))
y := x select: [:item | item p].

New implementation...