4 ms·
A couple of years back, I wrote an implementation of a list in C that provided a List_ForEach(list, callback, context) function, because I really liked that idi
by demallien 16y ago
A couple of years back, I wrote an implementation of a list in C that provided a List_ForEach(list, callback, context) function, because I really liked that idiom in Ruby. 2 years down the track, I almost never use that function, preferring to simply do this:
for (pItem = List_First(pList); pItem; pItem = List_Next(pList))
{
//do stuff to pItem
}
It really isn't that much wordier than the ruby (or lisp, or python etc, they all have similar styles for this):
list.each do |item|
#do stuff to item
end
and as you do it all of the time, you don't even have a high cognitive load, your fingers can pretty much type it without having to engage the brain.
OK, so it's implemented using control structures rather than closures. Is that really such a terrible thing? Am I missing some big advantage here?
- torpor 16y agoYour for(;;) loop is fine for read-only processing .. unless you want to selectively delete elements in the list, remove the underlying structure, and repair the hole .. but then you can add a ", pItem_next = (p_iTem != NULL) ? List_Next(pList) : NULL" qualifier to the for(;;) iterator ..
- jules 16y agoSmall stuff adds up. Also, in Ruby you can use the same construct to iterate over any collection.
- djacobs 16y agoA lot of people use #each this way in Ruby, yes, but I don't think it's usually justified. #each is primarily designed to handle side effects. "Do stuff to item" is usually better accomplished with a chain of #map, #select, #inject, #grep, etc. If "do stuff to item" is a multiline set of steps, sure you can use #each. I prefer, though, to abstract that set of steps into a lambda or named function and then map the function onto each item. Then again, I'm biased. I really like Ruby for its higher-order Lispiness, and not for its webbiness.