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

前端 未结 18 1921
不思量自难忘°
不思量自难忘° 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:11

    A for loop can always be replaced by a recursive function that doesn't involve the use of a loop. A recursive function is a more functional stye of programming.

    But if you blindly replace for loops with recursive functions, then kittens and puppies will both die by the millions, and you will be done in by a velocirapter.

    OK, here's an example. But please keep in mind that I do not advocate making this change!

    The for loop

    for (int index = 0; index < args.Length; ++index)
        Console.WriteLine(args[index]);
    

    Can be changed to this recursive function call

    WriteValuesToTheConsole(args, 0);
    
    
    static void WriteValuesToTheConsole(T[] values, int startingIndex)
    {
        if (startingIndex < values.Length)
        {
            Console.WriteLine(values[startingIndex]);
            WriteValuesToTheConsole(values, startingIndex + 1);
        }
    }
    

    This should work just the same for most values, but it is far less clear, less effecient, and could exhaust the stack if the array is too large.

提交回复
热议问题