我对LISP比较陌生,我正在尝试为一个演示文稿创建的Lisp程序尝试一些新东西。
我需要能够打印列表中的所有其他字符,例如,(A B C D E F)将返回(A C E)..但我很容易混淆......
我通常是程序Java,所以这对我来说有点不同。
我正在尝试使用纯粹的递归来编程。所以......就像......
(defun every-other (lst)
(cond ((null lst) 0)
(( **** now this is where I get confused as to what I should do..
I've tried adding a counter to only remove even numbered elements, but I think I implemented the counter wrong, I also tried remove(cadr lst) lst, but that would only return zeros...
任何帮助将不胜感激..
谢谢!
答案 0 :(得分:2)
既然你说你希望它以递归的方式完成,那就考虑一下。
将此案例分析转换为代码如下所示:
(defun every-other (lst)
(cond
;; If the list is null return the empty list.
((null lst) '())
;; If the list is not null, construct [cons] a new list with the first element of lst
;; and every-other element of the list after the first two elements [rest returns the
;; list without the first element, so we can just use it twice].
(t (cons (first lst) (every-other (rest (rest lst)))))))
现在对这段代码的评估看起来应该是这样的:
(every-other '(a b c d e f))
=> (cons 'a (every-other '(c d e f)))
=> (cons 'a (cons 'c (every-other '(e f))))
=> (cons 'a (cons 'c (cons 'e (every-other '())))
=> (cons 'a (cons 'c (cons 'e '())))
=> (cons 'a (cons 'c '(e)))
=> (cons 'a '(c e))
=> '(a c e)
答案 1 :(得分:2)
为了好玩,基于loop
的解决方案:
(defun every-other (lst)
(loop
for i in lst
for keep = t then (not keep)
if keep collect i))
答案 2 :(得分:2)
只需使用循环。
(loop :for c :in '(a b c d e f) :by #'cddr
:collect c)
:By
- for
子句中的 in
设置步进功能(默认为#'cdr
)。为了获得所有其他元素,每次都要执行两步。 Cddr
是两次应用cdr
的快捷方式。
答案 3 :(得分:0)
(defun aaa (x)
(aa (length x) x))
(defun aa (n x)
(cond ((null x) nil)
((evenp (- n (length x))) (cons (car x) (aa n (cdr x))))
(t (aa n (cdr x)))))
这是一个愚蠢的案例lol~
答案 4 :(得分:0)
更短的递归解决方案:
(defun every-other (l)
(unless (null l)
(cons (first l) (every-other (cddr l)))))