how to return map(fn)

Steven Schveighoffer schveiguy at gmail.com
Tue Feb 22 16:44:43 UTC 2022


On Tuesday, 22 February 2022 at 13:53:34 UTC, steve wrote:
> On Monday, 21 February 2022 at 23:07:44 UTC, Ali Çehreli wrote:
>> On 2/21/22 12:44, steve wrote:
>>...
>
>
> thanks for your help. I'm unfortunately still a bit confused. 
> Maybe I wasn't clear or maybe I'm just missing something here. 
> What I was trying to return is function that can then be 
> applied to e.g. an array. As I understand the mapped function 
> you wrote expects a range and a function argument something 
> that would let me do
>
>
> ```d
> float my_function(float x){ return 2*x;}
>
> auto my_function_mapped = mapped(my_function);
> assert(my_function_mapped([1.,2.,3.]) == [2.,4.,6.]);
>
> ```

`map` does not eagerly allocate or process data. `map` is 
actually a lazy function, meaning it doesn't actually run until 
you look at the elements.

If you want a *concrete* range, you can use `array` from 
`std.array` as follows:

```d
float[] get_map(alias f)(float[] input){
    import std.algorithm : map;
    import std.array : array;
    return input.map!(f).array;
}
```

`array` iterates all elements in the range and allocates a new 
array to hold the data.

I know in other languages, people are used to just using arrays 
for all high-level composition, but D tries not to incur the 
allocation/copy penalty if it can help it. So it's worth 
questioning if you actually need an array, or if you can just use 
the map result directly.

-Steve


More information about the Digitalmars-d-learn mailing list