Logo

Programming-Idioms

  • D
  • Ada
  • Rust
  • Perl

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.

# 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;
import std.algorithm;
auto y = [1, 2, 3, 4, 5].filter!(a => a%2==0);

Actual example.
y is a range containing only [2, 4]
import std.algorithm.iteration;
auto y = x.filter!(p);

Using UFCS, we can write filter!(p)(x) as x.filter!(p)
for Item of X loop
   if P (Item) then
      Y.Append (Item);
   end if;
end loop;
let y: Vec<_> = x.iter().filter(p).collect();

This collects into a vector (other collections are possible)
(def y (filter p x))

New implementation...