Hello,
After reading a recent discussion about PHP, it turned out that many people are afraid of recursion as fire. Such a myth must be exposed!
Today we will justify why the cycles are bad, and why they should be soaked. In the process we will pesat in the Orthodox language Haskel, which is very incomprehensible. You have been warned!
')
So what is the “for” loop?
- this is an “operator” (or rather, an instruction, statement) that allows you to change the program’s control flow
- this is a syntax abstraction
- it is a disguised goto, which are evil (Dijkstra proved already in his work “Goto is considered harmful”, EMNIP)
- this is another way to "repeat yourself"
And what's wrong with that, ask the farmer? We list those things that can not be done with the cycle:
- pass in functions as arguments and return from other functions
- build other cycles with them
, (
for (int i = 0; i < 10; i++);
?), ( , goto).
(, , , , ), , - -. , , .
? ! , -, , -, .
. ( ), .
©:
int sum(int *a, size_t length) {
int x = 0;
size_t i = 0;
for (; i < length; i++) {
x += a[i];
}
return x;
}
— , :
-- , " "
sum = foldr (+) 0
foldr :
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
. , , , , , , !
, .
C, — , :
int sumEven(int *a, size_t length) {
int x = 0;
size_t i = 0;
for (; i < length; i++) {
if (a[i] % 2 == 0)
x += a[i];
}
return x;
}
:
-- " ",
-- :)
even x = x `mod` 2 == 0
sumEven = sum . filter even
, , even, sum.
, , . «» . %)
. :)
- - , . , . -, , , (, , ) .
- , , . :)
- , foldr , , .
- ( , ), Adam Turoff
UPD: (JS -> C), (
tass voicer)