In D how do i apply a function to all elements in an array?
For example i want to apply the std.string.leftJustify()
function to all elements in a string array.
I know i could use a loop but is there a nice map function? I see there is one in the std.algorithm
library but i've no idea how to use templates in D yet.
Any examples?
There are a lot of options to specify the lambda. map
returns a range that lazily evaluates as it is consumed. You can force immediate evaluation using the function array
from std.array
.
import std.algorithm;
import std.stdio;
import std.string;
void main()
{
auto x = ["test", "foo", "bar"];
writeln(x);
auto lj = map!"a.leftJustify(10)"(x); // using string mixins
// alternative syntaxes:
// auto lj = map!q{a.leftJustify(10)}(x);
// auto lj = map!(delegate(a) { return a.leftJustify(10) })(x);
// auto lj = map!(a => a.leftJustify(10))(x); available in dmd 2.058
writeln(lj);
}
import std.algorithm;
import std.stdio;
void main()
{
writeln(map!(a => a * 2)([1, 2, 3]));
writeln(map!(delegate(a) { return a * 2; })([1, 2, 3]));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With