[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: why tail recursion matters and why Java isn't it, was Re: lisp performance was Re: problems with lisp




   Date: Thu, 04 Sep 2003 10:48:00 +0200
   From: Pascal Costanza <costanza@iai.uni-bonn.de>
   To: ll1-discuss@ai.mit.edu
   
   You seem to suggest that recursion is always the most "natural" solution 
   but that's just not true. In many cases, an iteration expresses much 
   more clearly the intention of a programmer. Here are three Common Lisp 
   versions of an example of a collector I repeatedly need in a current 
   project:
   
   (loop for element in list
          do collect (car element))
   
   (defun collect-elements (list)
      (unless list
        (cons (caar list) (collect-elements (cdr list)))))
   
   (reduce 'cons list :key 'car :from-end t :initial-value nil)
   
   I am strongly convinced that the first version is objectively the best 
   because it is much simpler and direct than the others. For the recursive 
   version you even need to define a function. (Unless you want to use a Y 
   combinator instead, of course.)

Of course, if you "repeatedly need" it, then defining a function
is exactly what you should be doing.

Or use (mapcar #'car list).

--Guy Steele