how to return map(fn)

Steven Schveighoffer schveiguy at gmail.com
Wed Feb 23 23:58:55 UTC 2022


On Wednesday, 23 February 2022 at 16:48:00 UTC, steve wrote:
> Thank you both a lot for your help. I am new to D so all of 
> this is incredibly helpful. This seems like an amazing 
> community!
>
> @Ali I will have a look at std.functional as I think this is 
> really what I was looking for. Until then, I have solved the 
> problem with a simple class (e.g. below). I'm sure its not a 
> particularly good way of doing it but it will work for now :). 
> Also thank you for your book, its amazing!
>
>
> ```d
> class Mapper
> {
>     float function(float) fn;
>
>     this(float function(float) func)  {this.fn = func;}
>
>     float[] opCall(float[] x){
>         auto arr = new float[x.length];
>         foreach (i,elem; x) { arr[i] = fn(elem);}
>         return arr;
>     }
>
> }
>
>
> float times_two(float x) {return 2*x;}
>
>
> void main() {
>
>     import std.stdio;
>
>     Mapper map2x = new Mapper(&times_two);
>     writeln(map2x([1., 2., 3.]));
> }
> ```

I'm not sure what programming languages you are used to, so let 
me just show you the idiomatic D way ;)

```d
float times_two(float x) {return 2*x;}

// if you would rather make sure the result is an array
float[] times_two_array(float[] arr) {
    import std.algorithm; // for map
    import std.array; // for array
    return arr
       .map!times_two // map your function
       .array; // convert to an array
}

void main() {
    import std.stdio;
    import std.algorithm; // for map
    alias map2x = map!times_two;
    writeln(map2x([1., 2., 3.]));
    float[] arr2 = times_two_array([1., 2., 3.]);
    writeln(arr2);
}
```

-Steve



More information about the Digitalmars-d-learn mailing list