2014-09-11 47 views
0

我对LISP相对比较陌生,并且正在为一个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... 

任何帮助,将不胜感激的....行..

谢谢!

回答

2

既然你说你想要递归地完成,只要通过个案思考。

  1. 该列表为空 - >返回空列表[空列表是'()]。
  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) 
+0

优秀的帮助!谢谢!! – Ignacious 2014-09-11 02:07:13

2

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

(defun every-other (lst) 
    (loop 
    for i in lst 
    for keep = t then (not keep) 
    if keep collect i)) 
2

只需使用一个循环。

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

for:By - in子句将步进功能(默认为#'cdr)。为了获得其他每个元素,每次都要执行两个步骤。 Cddr是两次应用cdr的快捷方式。

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))))) 

这是一个愚蠢的情况下笑〜

0

较短的递归解决方案:

(defun every-other (l) 
    (unless (null l) 
    (cons (first l) (every-other (cddr l))))) 
相关问题