Assigning map result, and in-place map

Nick Sabalausky a at a.a
Fri Sep 3 03:00:34 PDT 2010


"Bert van Leeuwen" <bert at e.co.za> wrote in message 
news:i5qftb$2a25$1 at digitalmars.com...
> I'm a D n00b, so excuse my question if it is silly. I've cursorily 
> "followed" D for a few years, but only now bought "The D Programming 
> Language" (great book, very nicely written!) and started to really play 
> with it.
>

Welcome! :)

> I've run into two questions which I have not been able to find the answers 
> to online.
>
> 1) I have an int array which I want to replace elements of with 
> compile-time string expression, e.g.
>
> i=new int[100];
> auto b=map!("(a==0)?42:a")(i);
> writeln(b);
>
> Cool, that works. But now I want to get at the resulting array. If I 
> replace "auto b" with:
> int[] b = map ...
> that does not work ("cannot implicitly convert expression (map(i)) of type 
> Map!(result,int[]) to int[]")... fine, but how do I get to the int[] ?
>

Instead of returning an array, map returns a range that computes the values 
lazily (on-demand when they're needed, instead of always computing all of 
them right away). This is done for performance reasons. But you can get an 
array with the array() function from the "std.array" module:

auto b = array( map!("(a==0)?42:a")(i) );

or

auto b=map!("(a==0)?42:a")(i);
auto ba = array(b);

BTW, instead of:

map!("(a==0)?42:a")(i)

You can do:

map!"(a==0)?42:a"(i)

A nifty little bit of syntax sugar for when there's only one template 
parameter.

> 2) Related to above, I want to do something like map, but not return a new 
> array, I want to modify elements in-place in the array. How do I do that? 
> (without explicitly iterating with foreach etc.)

I'll leave this one for someone else to answer, as I don't know whether or 
not something like this is already in phobos. If not, such a function can 
definitely be made, and maybe someone has already done so...?





More information about the Digitalmars-d mailing list