Better HN
topnewbestaskshowjobs
Log inSign up

ezrakilty

4 karma · joined Feb 24, 2012 (14y ago) · 1 submissions

Submissions

comment 14y ago · link · parent

The bog-standard for loop that transforms an array mentions the array twice and the index variable five times, giving you, let's say, 6 unnecessary chances to goof something:

for (int i = 0; i < array.length; i++) { newarray[i] = f(array[i]) }

by contrast, the functional-programming method allows you to define the new array immediately in terms of the old one, just mentioning the latter once and without an index variable:

  newlist = map f oldlist
To my eye, this gives me far fewer chances to botch it, and my reader can instantly tell that

  (1) newlist corresponds to oldlist in length and order
  (2) the only difference between the two is that the elements are related by the function f.
Every time I come across a for loop that builds up an array, I worry whether the bounds checking is wrong, whether the right index variable is used (esp. if there are nested loops), and whether an elements were added to the array before or after the loop. Lots to worry about.