This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
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.
- Clojure
- C++
- C++
- C#
- D
- Dart
- Elixir
- Fortran
- Go
- Groovy
- Haskell
- JS
- Java
- Java
- Lisp
- PHP
- Pascal
- Perl
- Python
- Python
- Ruby
- Ruby
- Rust
- Scala
- Smalltalk
- Smalltalk
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;
}
Can just return the first line if you don't actually need a vector, and just need something with begin and end.
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;
}
var y []Result
for _, e := range x {
if P(e) {
y = append(y, T(e))
}
}
No functional style: just a regular loop.
y is not fully allocated upfront because the number of matching elements is not known yet.
y is not fully allocated upfront because the number of matching elements is not known yet.
my @y = map { T($_) } grep { P($_) } @x;
$_ inside grep block represents each element e of array x