gpt4 book ai didi

loops - LISP 遍历列表

转载 作者:太空宇宙 更新时间:2023-11-03 19:04:38 25 4
gpt4 key购买 nike

我有一个函数“power”,它给出数字的平方,而其他函数需要对列表中的每个数字的平方求和。但它告诉我未定义的函数我和我真的不能让它工作。

(defun power (x)
(if (numberp x) (* x x) 0)
)
(defun sum (l)
(loop for i in l do(setq s(+ (power (i)) s)))
print s)

最佳答案

例子:

CL-USER 12 > (loop for i in '(1 2 3 4) sum (power i))
30

CL-USER 11 > (reduce #'+ '(1 2 3 4) :key #'power)
30

CL-USER 14 > (defun sum (l &aux (sum 0))
(dolist (i l sum)
(incf sum (power i))))
SUM

CL-USER 15 > (sum '(1 2 3 4))
30

关于loops - LISP 遍历列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com