Duplication in a simple sum functionby edA-qa mort-ora-y on Monday July 07 2008 @ 20:28:15 (25/-7920 Points) |
|
| Computing ↪Technology ✑ Reply ✓ Stick It ✗ Ditch It ⚐ Tag It |
Recently, while proponing my zero redundancy↗ method, a friend observed that to a functional programmer even the below piece of code contains duplication.
List::sum() {
int total = 0;
foreach( value in values )
total += value;
return total;
}Now in general I don't like dealing with trivial examples. It's like attempting to describe the theory of relatively using an atom as an example: it just doesn't work. But let's humour this for a second and see what we can find out.
We will assume the language being used doesn't have a sum function on this data type. Otherwise this is a very simple duplication requiring a very simple adjustment, and is not really of any interest. We will also assume there is no other sum logic in the overall program; that is, we assume the programmer has already replaced all such duplication with a call to this function. Thus we can focus strictly on this function as presented.
Our first question of redundancy is whether the language exposes a fold operator or function. If yes, then one might argue there is some wasted coding, for the same function could be expressed as below.
List::sum() {
return fold( +, values );
}This looks better, and for the sum function it likely is. But you have to be quite careful here: this is not the exact same as the function we've replaced. The initial function gave an explicit ordering to the individual additions, the new function does not. Perhaps that order was there for a reason. To make this clearer, suppose we had a division sequence instead.
List::quotient() {
int q = values[0];
foreach( value in values[1..*] )
q /= value;
return q;
}Division is not associative, therefore the precise ordering of the calculations is important. Simply replacing this with a fold operation is wrong, as it gives no indication of the ordering. If you are lucky then perhaps your language specifies a left fold, which is the type you need here. If not, then there is little you can do to reduce this code.
In general though, doing such small reductions is not really worth the effort. Considering the overall scope of a normal program this would be like picking pebbles out of a landslide. Furthermore, the above code is a leaf-node: it has no further internal dependencies (it doesn't call any of your functions). Such leaves always get special status with regards to reduction, as they enter the realm of cost benefit analysis, but that, is truly a different topic.
BrainBrain Duplication in a simple sum function
