tags:

views:

174

answers:

1

Hi,

I need to write a non-recursive version of the function sum-squares and Use a do-loop that is based on the length of the argument list.

+1  A: 

Here's how it's done generally:

(defun sum-squares (list) (loop for x in list
              for y = (* x x)
              summing y into total
              finally (return total)))

A do loop solution is even simpler, but not half as elegant:

(defun sum-squares (list)
         (let ((sum 0)) (do ((i 0 (1+ i)))
              ((>= i (length list)))
            (setq sum (+ sum (* (nth i list) (nth i list)))))
              sum))
Bozhidar Batsov
Thanks a lot...
bubdada
Why not (loop for x in list summing (* x x)). Any your do loop solution is O(n^2); try iterating directly on the list items, instead of the indices.
huaiyuan
+ 1 from me for the great comment. I wrote the loop especially verbose, so that the example could show the full structure of a loop construct - I thought it might be informative to a beginner in this manner. As for the second example - orcik wanted a solution that used the length of the argument list - otherwise I would have surely iterated over the elements themselves.
Bozhidar Batsov