Map and arrays
Jonathan M Davis
jmdavisProg at gmx.com
Sat Nov 27 23:11:44 PST 2010
On Saturday 27 November 2010 22:48:28 Tom wrote:
> Hi,
>
> I wonder how to solve this kind of stuff...
>
> void foo(string[] sarray) {
> // do something with sarray
> }
>
> void bar(int[] iarray) {
> auto sarray = map!(to!string)(iarray);
> foo(sarray);
> }
>
> And get...
>
> foo (string[] sarray) is not callable using argument types (Map!(to,int[]))
>
> What should I do? Is there some way to get the original array type?
Many functions in std.algorithm return range types specific to that function. A
number of these do lazy evaluation, so the actual work of the function is done
when iterating over the resulting range. map happens to be one of those.
For all such functions, if you want an array out of the deal, what you do is
pass the result to std.array.array(). That will take an arbitrary range and
return its contents as an array - which also forces the processing of the range
in the case of lazy evaluation like you get with map. So, if you want to delay
the evaluation at all, or if it's really only go to make sense that some of the
range be processed, you may not want to actually put it in an array. The
combination of auto and templates can avoid making you actually turn it into an
array in many cases. But if you do want an array, std.array.array() is what
you're looking for.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list