Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In D how do i apply a function to all elements in an array?

Tags:

arrays

d

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?

like image 846
Gary Willoughby Avatar asked Jan 04 '12 23:01

Gary Willoughby


2 Answers

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);
}
like image 55
eco Avatar answered Oct 01 '22 10:10

eco


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]));
}
like image 26
user541686 Avatar answered Oct 01 '22 12:10

user541686