The unacceptable part of the explanation is as follows.
This example shows you step by step how to calculate the amount. At some point, you can convince yourself that this is really the sum of the elements in the list. For example, it is not known why sum=0 at first; should it be 0 at all; you go through the correct indexes; what sum+=i gives you.
sum=0 -- why? it may become clear if you consider what happens in the loop, -- but not on its own for i in l: sum += i -- what do we get? it will become clear only after the loop ends -- at no step of iteration you have *the sum of the list* -- so the step on its own is not meaningful
In this regard, the declarative example is very different. In this particular case, you start by declaring that the sum of the empty list is 0. This is already part of the answer to what constitutes the sum. Then you add the instruction for non-empty lists - the sum for a non-empty list is the sum of the tail with the head element added to it. This is a declaration of what the amount is. You can demonstrate inductively that it finds a solution for any list.
Pay attention to this trial part. In this case, this is obvious. In more complex algorithms, this is not obvious, so proving correctness is an essential part - and remember that the imperative case makes sense only in general.
Another way to calculate the amount, where, I hope, declarativeness and profitability will become clearer:
sum [] = 0 -- the sum of the empty list is 0 sum [x] = x -- the sum of the list with 1 element is that element sum xs = sum $ p xs where -- the sum of any other list is -- the sum of the list reduced with p p (x:y:xs) = x+y : p xs -- p reduces the list by replacing a pair of elements -- with their sum p xs = xs -- if there was no pair of elements, leave the list as is
Here we can convince ourselves that: 1. p makes the list shorter, so the calculation of the sum will stop; 2. p creates a list of sums, therefore, summing up all the shorter lists, we get a list of only one element; 3. since (+) associative, the value obtained by repeatedly applying p coincides with the sum of all the elements in the original list; 4. we can demonstrate that the number of applications (+) less than in a simple implementation.
In other words, the order in which the elements are added does not matter, so we can first sum the elements ( [a,b,c,d,e] ) in pairs ( a+b , c+d ), which gives us a shorter list of [a+b,c+d,e] , the sum of which coincides with the sum of the original list and which can now be reduced in the same way: [(a+b)+(c+d),e] , then [((a+b)+(c+d))+e] .