1

Is there a golden standard optimal way of stacking several Func in a row?

I my case I have some point transformations in a list of Func.

List<Func<Point3D, Point3D>> combined = new List<Func<Point3D, Point3D>>();

Point3D translateVector = new (10,0,0);
Func<Point3D, Point3D> translate = (p) => p + translateVector;
combined.Add(translate);

Func<Point3D, Point3D> scale = (p) => p * 123;
combined.Add(translate);

So far so good. Now comes the ugly part: I want to nicely apply the functions to my points.

for (int p = 0; p < points.Count; p++)
{
   foreach(var function in combined )
   { 
      points[p] =  function(points[p]);
   }
}

This seems like a clunky way of achieving the combined Func.

Is there a better way?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    I’m voting to close this question because it is asking to improve working code. please ask on [codereview.se] – Daniel A. White Apr 27 '23 at 13:34
  • 2
    @DanielA.White It would need more context before it's ready on Code Review. For anyone considering posting on CR, please see [A guide to Code Review for Stack Overflow users](https://codereview.meta.stackexchange.com/q/5777/52915) first. – Mast Apr 27 '23 at 13:35
  • Is it ugly because you haven't formatted it properly or do you think it has too many lines or something else? – shingo Apr 27 '23 at 13:36
  • 2
    I recommend reading about delegate.Combine or the addition operator for delegates. People have voted to close, but I don’t think this belongs on code review. This is about a specific issue, and you gave an example. You can read about the addition here: https://stackoverflow.com/questions/13549043/how-does-the-operator-work-for-combining-delegates – SupaMaggie70 b Apr 27 '23 at 13:38
  • You could use Linq Aggregate to replace the `foreach` and you can even do it in one line if you don't mind replacing `points` instead of mutating it. `points = points.Select(point => combined.Aggregate(point, (p, f) => f(p))).ToList();` – juharr Apr 27 '23 at 13:56
  • Try `var combine = (Func)Delegate.Combine(translate, scale);` – Guru Stron Apr 27 '23 at 14:00
  • @juharr Thanks a ton! This at least looks nice. I was hoping for some runtime optimized way of achieving the function stacking, but maybe it does not get much better. I doubt your suggestion is more runtime optimized, but it looks less messy. Again thanks! and thanks to all your suggestions. – Folmer Gringer Brem Apr 27 '23 at 14:15
  • I guess beauty is in the eye of the beholder. Two simple loops are easy to read and debug, and use less memory than the single line that is less intuitive to understand (to me) and impossible to step-through debug. – Rufus L Apr 27 '23 at 14:44

0 Answers0