How to apply a function to a container/array ?
bearophile via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Oct 15 17:12:05 PDT 2014
Domingo:
> Ideally I want to use something like this:
> ---------
> import std.stdio;
> import std.string;
> import std.algorithm;
> import std.conv;
>
> void main()
> {
> string[] ar = [" dad ", " blue "];
> writeln(typeid(ar));
>
> //ar.each(writeln);
> //ar.map!writeln;
> //ar.apply!writeln;
>
> //string[] ar_striped = ar.map!strip;
> //string[] ar_striped = ar.apply!strip;
> //string[] ar_striped = ar.each!strip;
>
> //ar_striped.each!writeln;
> //ar_striped.apply!writeln;
> //ar_striped.map!writeln;
>
>
> alias stringize = map!(to!string);
> auto sz = stringize([ 1, 2, 3, 4 ]);
> writeln(typeid(sz));
> assert(equal(sz, [ "1", "2", "3", "4" ]));
> }
> ---------
>
> But none of then work, any idea of how to that in D ?
D algorithms like "map" don't return an array, but a lazy range.
Use ".array" if you need an array:
void main() {
import std.stdio;
import std.algorithm;
import std.array;
import std.string;
import std.conv;
immutable ar = [" dad ", " blue "];
pragma(msg, typeof(ar));
ar.writeln;
auto arStriped = ar.map!strip;
arStriped.writeln;
pragma(msg, typeof(arStriped));
immutable arStripedArray = arStriped.array;
pragma(msg, typeof(arStripedArray));
alias stringize = map!text;
auto sz = stringize([ 1, 2, 3, 4 ]);
assert(sz.equal(["1", "2", "3", "4"]));
}
Usually it's better to use pragma+typeof, typeid is used less
often, for run time management/use of types.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list