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 are stuck with a non-functional language, say C#, what techniques are there to avoid for-loops or to get rid of them by refactoring? With lambda expressions and LINQ perhaps? If so, how?
Questions
So the question boils down to:
Bookmark this question. Show activity on this post. We dont use for loop in functional programming, instead, we use higher order functions like map, filter, reduce etc. These are fine for iterating through an array.
C# foreach loop is used to iterate through items in collections (Lists, Arrays etc.). When you have a list of items, instead of using a for loop and iterate over the list using its index, you can directly access each element in the list using a foreach loop.
Map() Function in Python The map() function is a replacement to a for a loop. It applies a function for each element of an iterable.
for() loop can always be replaced with while() loop, but sometimes, you cannot use for() loop and while() loop must be used.
Functional constructs often express your intent more clearly than for-loops in cases where you operate on some data set and want to transform, filter or aggregate the elements.
Loops are very appropriate when you want to repeatedly execute some action.
For example
int x = array.Sum();
much more clearly expresses your intent than
int x = 0; for (int i = 0; i < array.Length; i++) { x += array[i]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With