0

The Program is supposed to find each symbol in the List, that comes after a certain symbol. The function gets to parameters passed in. A List which could contain nested-lists and a symbol. The function has to scan thru the list and search for the given symbol and print the symbols that come after the given symbol.

Examples:

(find-all 'a '((b a) ((c a b)))) --> (c b)
 (find-all 'a '(b (a a) c)) --> (a c)
 (find-all 'a '(b d c e)) --> nil

My Code So Far:

(defun find-all (a list)
    (if (consp list)
        (if (consp (car list))
            (find-all a (car list))
        (if (eq a (car list))
            (cons (car(cdr list)) (find-all a(cdr list)))
            (find-all a(cdr list))))))

This code works except when the symbol its looking for is the last atom in the list. it fails in these test cases:

 (find-all 'a '((b a) ((c a b)))) --> (c b)
 (find-all 'a '(b (a a) c)) --> (a c)

but works fine in these cases:

(find-all 'a '(b a c a e)) --> (c e)

The issue is probably at my cons statement and i am unable to fix this.

4

1 に答える 1

0

あなたのコードは正しくないと思います。まず、正しくインデントされていないため、読みにくくなっています。正しいインデントは次のとおりです。

(defun find-all (a list)
  (if (consp list)
      (if (consp (car list))
          (find-all a (car list))
          (if (eq a (car list)) ; if properly intended here
              (cons (car(cdr list)) (find-all a(cdr list)))
              (find-all a(cdr list)))))))))

その後も、あなたの論理に従うのに苦労しています。たとえば、何かが短所である場合、carと の両方を処理する必要cdrがありますが、そうではありません。私はデバッグ プロセスを実行しませんでしたが、実行する必要があります。


代わりに、代替案を示したいと思います。問題を 2 つの部分に分割することをお勧めします。

リストの平坦化

ネストされたリストから始めてフラットなリストになるため、最初にリストをフラット化する方が簡単です。以下は、古典的な flatten 関数です。

(defun flatten (sxp)
  (labels
   ((sub (sxp res)
      (cond
       ((null sxp)  res)
       ((consp sxp) (sub (car sxp) (sub (cdr sxp) res)))
       (t           (cons sxp res)))))
   (sub sxp nil)))

フラットリストの処理

ここで、フラット リストを使用すると、関数を使用して残りが明らかになります (そして、REPL で自分の関数と区別するためにmembermy 関数を呼び出します)。find-from

(defun find-from (a lst)
  (labels
      ((sub (lst)
         (when lst
           (let ((rst (cdr (member a lst))))
             (when rst
               (cons (car rst) (sub rst)))))))
    (sub (flatten lst))))

テスト

? (find-from 'a '((b a) ((c a b))))
(C B)
? (find-from 'a '(b (a a) c))  
(A C)
? (find-from 'a '(b d c e)) 
NIL
? (find-from 'a '(b a c a e)) 
(C E)
于 2014-11-02T21:13:35.533 に答える