Alias parameter predicates considered harmful?
Paul Backus
snarwin at gmail.com
Sat Mar 20 01:03:39 UTC 2021
On Saturday, 20 March 2021 at 00:29:54 UTC, Vladimir Panteleev
wrote:
> Currently we use alias parameters to specify predicates for
> map, filter, sort etc. This generally works well, but has some
> limitations.
>
> One big limitation is the necessity to create a closure to
> access variables that are not part of the range. This is a
> reoccurring problem:
>
> https://forum.dlang.org/post/lwcciwwvwdizlrwoxyiu@forum.dlang.org
> https://forum.dlang.org/thread/mgcflvidsuentxvwbmih@forum.dlang.org
> https://forum.dlang.org/post/rkfezigmrvuzkztxqqxy@forum.dlang.org
>
> Example illustrating the problem:
>
> auto fun() @nogc
> {
> int toAdd = 1;
> return iota(10).map!(n => n + toAdd);
> }
>
> In order to make toAdd accessible to the predicate, it must
> create a closure to host it (and nest the map instantiation
> inside the closure).
Here's an idiom I've found useful in situations like this:
/// Pass struct members as arguments to a function
alias apply(alias fun) = args => fun(args.tupleof);
auto fun() @nogc
{
int toAdd = 1;
return iota(10)
.zip(repeat(toAdd))
.map!(apply!((n, toAdd) => n + toAdd));
}
More information about the Digitalmars-d
mailing list