How to replace for-loops with a functional statement in C#?

前端 未结 18 1781
不思量自难忘°
不思量自难忘° 2021-01-31 08:59

A colleague once said that God is killing a kitten every time I write a for-loop.

When asked how to avoid for-loops, his answer was to use a functional language. However

18条回答
  •  天涯浪人
    2021-01-31 09:24

    If you abstract the for loop directly you get:

    void For(T initial, Func whilePredicate, Func step, Action action)
    {
        for (T t = initial; whilePredicate(t); step(t))
        {
            action(t);
        }
    }
    

    The problem I have with this from a functional programming perspective is the void return type. It essentially means that for loops do not compose nicely with anything. So the goal is not to have a 1-1 conversion from for loop to some function, it is to think functionally and avoid doing things that do not compose. Instead of thinking of looping and acting think of the whole problem and what you are mapping from and to.

提交回复
热议问题