开发者

Sum of Squares in Lisp

开发者 https://www.devze.com 2022-12-27 09:54 出处:网络
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:

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

精彩评论

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