gpt4 book ai didi

lisp - 尝试返回当前列表中偶数位置的值列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:57:08 26 4
gpt4 key购买 nike

这里的目标是将一个列表传递给函数,并让它返回一个列表,其中包含前一个列表中偶数位置的值。

例如。返回偶数 '(1 2 3) => (2) , 返回偶数 '() => ()

我终于创建了这个函数,但是它只在我输入 0-3 个值时才起作用。当我输入 0 或 1 个值时,它不会返回“()”,而是返回“NIL”。

我怎样才能让它与超过 3 个值一起工作,我怎样才能返回它以便它以列表的形式打印出来,并用括号括起来?

(defun return-evens (lst)
(let ((return-list ()) (i 1))
(loop for x in lst
while (numberp x)
do (if (= (mod i 2) 0)
(setf return-list (append return-list x))
()
)
do (setq i (1+ i))
finally (return return-list))))

最佳答案

对您的代码的一些反馈。

第一个大问题:缩进不正确

(defun return-evens (lst)          ; in Lisp you can call it list instead of lst
; return is not a useful prefix.
; Every function returns something

(let ((return-list ()) (i 1)) ; LOOP can return lists and iterate.
; No need for this at all.

(loop for x in lst

while (numberp x) ; why this test? Are there non-numbers in the list?

do (if (= (mod i 2) 0) ; Lisp has a function EVENP
; but generally it is not necessary

(setf return-list (append return-list x))
; never append to the end. Never ever.
; Let LOOP collect a list, don't do it this way

()
)

do (setq i (1+ i)) ; iterating manually is not necessary
; that's what LOOP is for

finally (return return-list))))
; if you would let LOOP do the work, no RETURN necessary

一个更简单的解决方案:

(defun elements-at-even-positions (list)
(loop for element in list
for even-position = nil then (not even-position)
when even-position collect element))

关于lisp - 尝试返回当前列表中偶数位置的值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36349117/

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