Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scheme 方案:在列表和子列表中搜索元素_Scheme - Fatal编程技术网

Scheme 方案:在列表和子列表中搜索元素

Scheme 方案:在列表和子列表中搜索元素,scheme,Scheme,我想写一个函数,它接收列表并返回每个元素的列表。 例如: 获取-(x345(x4)3x6))并接收:(x(x)x()) 我的代码结果用于: (lookForX '(x 3 4 5 (x 4) 3 x (6))) -> (x x) 我做错了什么?在您的函数中,您只在列表中查找x作为元素,而没有执行子列表: (define (filter-x lst) (cond ((null? lst) '()) ((eq? (car lst) 'x) (cons (ca

我想写一个函数,它接收列表并返回每个元素的列表。 例如: 获取-
(x345(x4)3x6))
并接收:
(x(x)x())

我的代码结果用于:

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

我做错了什么?

在您的函数中,您只在列表中查找
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。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))
(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))