5 ms·
Imperative code is more explicit, but higher-level loop abstractions like map and filter are more restrictive and thus both easier to reason about and less erro
by RodgerTheGreat 11y ago
Imperative code is more explicit, but higher-level loop abstractions like map and filter are more restrictive and thus both easier to reason about and less error prone. When you program with functional patterns you remove whole classes of possible mistakes (or, when reading code, overlooked subtleties) surrounding the explicit mutation of index variables.
The APL family eschews explicit "for" loops entirely in favor of functional forms and assigns special symbols to each of them. This results in extremely dense code, but at the same time code which often has fewer "moving parts" and is less likely to be subtly incorrect.
In JavaScript I could write
var sum=0; for(var x=0; x<100; x++) { sum += x; }
or I could write
var sum=range(100).reduce(function(a,b) { return a+b; });
(provided an appropriate definition of `range()`)
In K I would write
+/!100
The sum (+) over (/) the range 0 up to but not including (!) 100.
In the first example, I have to worry about all sorts of boundary conditions and typos. The second example is easier to reason about, but it's fairly wordy. The third is so simple and concise it is "obviously correct". These examples are contrived, but I think they provide some food for thought.
- ta0967 11y agoif you were to program in JS in a style which calls for passing operations around you would have the operator `+` wrapped, so the second version would probably look like this var sum = range(100).reduce(0, plus); or rather var total = sum(range(100)); this does not take away from the beauty of APL.