开发者

Sum of Squares in Lisp

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.


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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜