I want to write a function that receives list and returns a list of each element. For example: get - (x 3 4 5 (x 4) 3 x (6)))
and receive: (x (x) x ())
(define (lookForX lst)
(cond
((null? lst) '())
((eq? (car lst) 'x) (cons (car lst) (lookForX (cdr lst))) )
(else (lookForX (cdr lst)))))
my code result for:
(lookForX '(x 3 4 5 (x 4) 3 x (6)))
-> (x x)
What am I doing wrong?
In you function you are only looking for x
as element in the list and you are not doing sub lists:
(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 ())
Notice I renamed this to be more lisp like. Lisp code usually don't use camelCase but lisp-case. You can do it more general:
(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))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments