how to return map(fn)

steve stevethe1st at
Wed Feb 23 16:48:00 UTC 2022

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!

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.]));

More information about the Digitalmars-d-learn mailing list