这里的目标是将一个列表传递给该函数,并让它返回一个列表,其中的值位于上一个列表中的偶数位置。
例如。 return-evens'(1 2 3)=> (2),return-evens'()=> ()
我终于创建了这个功能,但只有在我输入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))))
答案 0 :(得分:4)
对您的代码提供一些反馈。
第一个大问题:没有正确缩进。
(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))