⬆️ ⬇️

Why cycles must die

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?





And what's wrong with that, ask the farmer? We list those things that can not be done with the cycle:





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



, , . «» . %)



. :)











UPD: (JS -> C), ( tass voicer)

Source: https://habr.com/ru/post/47429/



All Articles