Lisp vs. C++ (not off-topic)

Sean Kelly sean at f4.ca
Wed Oct 11 09:39:35 PDT 2006


It's an interesting analysis, but I think some of the points of 
comparison aren't as strong has the writer implies.  For example, he 
begins by saying that his initial C++ attempt is shorter than average 
and suggests that this is because his is the only C++ attempt to use the 
STL.  Later he goes on to make a direct comparison of some of his code 
and some of Peter Norvig's code (in the Style section) and concludes 
that because Norvig's code is shorter and doesn't modify the sequence in 
place, functional programming is better.  He's forgotten his original 
statement regarding his code vs. the other C++ entrants however, and 
perhaps doesn't have enough experience with the STL to know that:

     words.reverse();
     cout << num << ":";
     for (list<string>::const_iterator i = words.begin();
          i != words.end(); ++i)
         cout << *i << " ";
     cout << "\n";

can be rewritten as:

     std::cout << num << ':';
     std::reverse_copy( words.begin(),
                        words.end(),
                        std::ostream_iterator<std::string>( std::cout,
                                                            " " ) );
     std::cout << '\n';

This rewrite addresses his concern about reversing the list in place to 
print it out (it doesn't modify the original sequence), and partially 
addresses the comment about having to print out the list manually.  It 
also reduces his LOC count by two and is almost as expressive as the 
Lisp version.  A further reading of his code shows that he doesn't use 
the algorithm library at all, which is IMO one of the greatest strengths 
of C++.

That said, I do agree with the general thrust of the article.  While 
tricks like the above are possible in C++, they tend to require a good 
degree of knowledge or experience to be aware of.  By comparison, I 
think Lisp naturally lends itself to the type of code in Norvig's 
example.  The Lisp code is also more succinct and more clear than even 
an algorithm-aware rewrite of the C++ version, though I believe the gap 
would be narrower than the original comparison suggests.

I believe that D has a definite opportunity to do better than C++ in 
code clarity and ease of programming, but I'm not sure the library is 
sufficient quiet yet.  The C++ algorithm/iterator model is extremely 
powerful and D's foreach and delegates aren't enough by themselves.  For 
example, writing the code snippet above in D would be much more like the 
original C++ version than my rewrite.  For D to be great, I think it 
will need an standard algorithm-oriented library that exploits D's 
unique language features.  DTL seemed a likely candidate, but 
development on it stalled ages ago.  But perhaps it contains ideas worth 
pursuing.  I'll admit it's been so long that I've forgotten a lot of the 
details of how it works.


Sean



More information about the Digitalmars-d mailing list