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
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.