Logo

Programming-Idioms

  • D
  • Ruby

Idiom #189 Filter and transform list

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.

y = x.filter_map{|e| t(e) if p(e)}

filter_map is available for enumerables since Ruby 2.7.
y = x.each_with_object([]){|e, ar| ar << t(e) if p(e)}
import std.algorithm;
y = x.filter!(P).map!(T);
(def y 
  (eduction (filter P)
            (map T))
            x)

New implementation...