Range golf challenge: apply predicate to a subrange, returning the original range modified.
Ali Çehreli
acehreli at yahoo.com
Fri Oct 7 16:41:40 UTC 2022
On 10/7/22 09:35, Andrey Zherikov wrote:
> On Friday, 7 October 2022 at 16:32:07 UTC, Andrey Zherikov wrote:
>> ```d
>> 10.iota.map!(_ => _.isEven ? _*2 : _); // => [0, 1, 4, 3, 8, 5, 12, 7,
>> 16, 9]
>> ```
>
> You can even generalize this:
> ```d
> alias mapSubrange(alias filter, alias transform) = map!(_ => filter(_) ?
> transform(_) : _);
> 10.iota.mapSubrange!(isEven, _ => _*2);
> ```
I was trying something similar where I left .map to the user code:
import std;
bool isEven(T)(T value) {
return !(value % 2);
}
alias applyIf(alias pred, alias func) = value => (pred(value) ?
func(value) : value);
void main() {
auto result = 10.iota.map!(applyIf!(isEven, a => a * 2));
assert(result.equal([0, 1, 4, 3, 8, 5, 12, 7, 16, 9]));
}
Ali
More information about the Digitalmars-d
mailing list