I’ve been reading Programming Erlang and also casually looking into Haskell. So yesterday when I tinkered with Processing just a little bit, code like this just looks barbaric:
for(int i=0; i<width; i++) {
doSomething(i);
}
Compare to Erlang:
% Closer to Java and PHP. Nearly, but not quite, tolerable
lists:foreach(DoSomething, lists:seq(1, 50)).
% More Ruby/Lisp like. I can dig it.
lists:map(DoSomething, lists:seq(1, 50)).
% List Comprehensions FTW
[doSomething(I) || I <- lists:seq(1, 50)].
I mean, really. If you’re writing for loops in 2008, don’t pass go, don’t collect $200. Or even 200 Euro.
The caveat is if you’re implementing a language or compiler. Then I’ll forgive you. But if you could work that out by 2009 or so, we’d all thank you.
-
Hi, found your blog through OBJO on Twitter. He and I met at Codemash this past week.
For loops have their place in the programming paradigm. I have done a lot of benchmarks in languages over the years and when you need to loop through something the for loop is still faster than a while or a foreach or whatever other shortcut syntax you boil it down to.
Just because it isn’t pretty doesn’t mean it shouldn’t still be used.
-
I don’t think it is premature optimization if I know that I am dealing with a zero indexed array of data. The fastest way to process through that data is a for loop. Now with that said that doesn’t mean I will use a for loop I may use a foreach because it is more convenient for me and I honestly could at that moment care less about speed.
I write mainly in C# so I don’t have a “map” function. My point is it is still useful and to say it just shouldn’t ever be considered or used because you have to think more to use it doesn’t equate to throwing it out of the tool bag all together.
-Keith




7 comments
Comments feed for this article
Trackback link: http://therealadam.com/archive/2008/01/06/the-barbarism-of-the-for-loop/trackback/