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

Idiom #189 Filter and transform list

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

import std.algorithm;
y = x.filter!(P).map!(T);
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();
y = pack (t(x), mask=p(x))
var y []Result
for _, e := range x {
	if P(e) {
		y = append(y, T(e))
	}
}
y = x.filter(e => P(e)).map(e => T(e))
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 = x.each_with_object([]){|e, ar| ar << t(e) if p(e)}
list.collect { case x if p(x) => T(x) }

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

beltiras