0

我对 LISP 比较陌生,并且正在为我尝试为演示文稿创建的 Lisp 程序尝试一些新东西。

我需要能够打印列表中的所有其他字符,例如, (ABCDEF) 将返回 (ACE) .. 但我很容易混淆......

我通常是编程 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...

任何帮助将不胜感激..

谢谢!

4

5 回答 5

2

既然您说您希望它以递归方式完成,请逐个考虑。

  1. 列表为 null -> 返回空列表 [空列表为 '()]。
  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)
于 2014-09-11T01:02:14.167 回答
2

为了好玩,loop基于 - 的解决方案:

(defun every-other (lst)
  (loop 
    for i in lst
    for keep = t then (not keep) 
    if keep collect i))
于 2014-09-11T08:26:26.850 回答
2

只需使用一个循环。

(loop :for c :in '(a b c d e f) :by #'cddr
      :collect c)

:Byfor-in子句中设置步进函数(默认为#'cdr)。为了得到所有其他元素,每次都分两步。 Cddr是申请cdr两次的捷径。

于 2014-09-12T07:18:44.013 回答
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)))))

这是一个愚蠢的案例哈哈~

于 2015-11-13T06:14:34.753 回答
0

更短的递归解决方案:

(defun every-other (l)
  (unless (null l)
    (cons (first l) (every-other (cddr l)))))
于 2017-01-09T16:05:55.043 回答