Logo

Programming-Idioms

Produce a new list y containing the result of the function T applied to all elements e of the list x that match the predicate P.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
(def y 
  (eduction (filter P)
            (map T))
            x)
#include <ranges>
#include <iterator>
constexpr auto transform_matches(const auto& x, auto p, auto t) {
    auto result = x 
	| std::views::filter(p)
        | std::views::transform(t);

    std::vector<std::ranges::range_value_t<decltype(result)>> y;
    std::copy(result.begin(), result.end(), std::back_inserter(y));
    return y;
}
template <typename SeqT>
auto transform_copy_if(const SeqT i, auto p, auto f)
{
 using namespace std;

 SeqT o;

 for_each(begin(i), end(i),
          [&](const auto& x) {
              if(p(x))
               o.push_back(f(x));
          }
         );

 return o;
}
using System.Linq;
var y = x.Where(P).Select(T).ToList();
import std.algorithm;
y = x.filter!(P).map!(T);
var y = x.where(P).map(T).toList();
y = x
|> Enum.filter(&P/1)
|> Enum.map(&P(&T/1)
y = pack (t(x), mask=p(x))
var y []Result
for _, e := range x {
	if P(e) {
		y = append(y, T(e))
	}
}
def y = x.findAll(p).collect(t)
y = (map t . filter p) x
y = x.filter(e => P(e)).map(e => T(e))
import java.util.List;
List<T> y = x.stream()
             .filter(P)
             .map(T)
             .toList();
import java.util.stream.Collectors;
x.stream().filter(P).map(T).collect(Collectors.toList());
(defvar y (mapcar #'T (remove-if-not p x)))
$y = array_map('T', array_filter($x, 'P'));
uses classes;
type
  TListPredicate = function(e: pointer): Boolean;
  TListElementFunc = function(e: pointer): pointer;

function NewList(X: TList; P: TListPredicate; T: TListElementFunc): TList;
var
  e: pointer;
begin
  Result := TList.Create;
  for e in X do
  begin
    if P(e) then
      Result.Add(T(e));
  end;
end;
my @y = map { T($_) } grep { P($_) } @x;
y = [T(e) for e in x if P(e)]
y = list(map(T, filter(P, x)))
y = x.each_with_object([]){|e, ar| ar << t(e) if p(e)}
y = x.filter_map{|e| t(e) if p(e)}
let y = x.iter()
	.filter(P)
        .map(T)
	.collect::<Vec<_>>();
val y = x.collect { case e if P(e) => T(e) }
y := x 
  collect: [:ea | ea t]
  thenSelect: [:ea | ea p].
y := x 
  select: [:ea | ea p]
  thenCollect: [:ea | ea t].