2017-04-15 150 views
0

我想寫一個接收列表並返回每個元素列表的函數。 例如: GET - (x 3 4 5 (x 4) 3 x (6)))和接收:Scheme:在列表和子列表中搜索元素

(lookForX '(x 3 4 5 (x 4) 3 x (6))) 
-> (x x) 

我在做什麼錯:爲(x (x) x())

(define (lookForX lst) 
    (cond 
    ((null? lst) '()) 
    ((eq? (car lst) 'x) (cons (car lst) (lookForX (cdr lst)))) 
    (else (lookForX (cdr lst))))) 

我的代碼的結果?

回答

0

在你工作,你只是在尋找x爲列表元素,你是不是做子列表:

(define (filter-x lst) 
    (cond 
    ((null? lst) '()) 
    ((eq? (car lst) 'x) 
    (cons (car lst) 
      (filter-x (cdr lst)))) 
    ((pair? (car lst)) 
    (cons (filter-x (car lst)) 
      (filter-x (cdr lst)))) 
    (else (filter-x (cdr lst))))) 

(filter-x '(x 3 4 5 (x 4) 3 x (6))) 
; ==> (x (x) x()) 

通知我改名這更像口齒不清。 Lisp代碼通常不使用camelCase,而是使用lisp-case。你可以做得更一般:

(define (filter-tree predicate? lst) 
    (cond 
    ((null? lst) '()) 
    ((predicate? (car lst)) 
    (cons (car lst) 
      (filter-tree predicate? (cdr lst)))) 
    ((pair? (car lst)) 
    (cons (filter-tree predicate? (car lst)) 
      (filter-tree predicate? (cdr lst)))) 
    (else (filter-tree predicate? (cdr lst))))) 

(define (filter-tree-x lst) 
    (filter-tree (lambda (v) (eq? v 'x)) lst)) 

(filter-tree-x '(x 3 4 5 (x 4) 3 x (6))) 
; ==> (x (x) x()) 

(define (filter-tree-numbers lst) 
    (filter-tree number? lst)) 

(filter-tree-numbers '(x 3 4 5 (x 4) 3 x (6))) 
; ==> (3 4 5 (4) 3 (6)) 
+0

謝謝!它幫助! – user2953423