2014-09-11 66 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))))) 
相關問題