Reputation: 43
(define remove-leftmost
(lambda (item ls)
(cond
((null? ls) '())
((equal? (car ls) item) (cdr ls))
(pair? (car ls))
(let ((rem-list (remove-leftmost item (car ls)))
(cons rem-list (cond
((equal? (car ls) rem-list)
(remove-leftmost item (cdr ls)))
(else (cdr ls))))))
(else (cons (car ls) (remove-leftmost item (cdr ls)))))))
Now evaluate (remove-leftmost 'b (a (b c) (c (b a)))):
(cons a (remove-leftmost 'b ((b c) (c (b a)))))
(cons a (cons (c) ((c (b a)))))
(cons a ((c)(c (b a))))
(a (c)(c (b a)))
Does the evaluation work? If not, how to fix it?
Upvotes: 1
Views: 49
Reputation: 48745
You really need to ident your code. After pasting your code into DrRacket and pressing CTRL+i it's very obvious there are many errors in your code:
(define remove-leftmost
(lambda (item ls)
(cond
((null? ls) '())
((equal? (car ls) item) (cdr ls))
(pair? (car ls))
(let ((rem-list (remove-leftmost item (car ls)))
(cons rem-list (cond
((equal? (car ls) rem-list)
(remove-leftmost item (cdr ls)))
(else (cdr ls))))))
(else (cons (car ls) (remove-leftmost item (cdr ls)))))))
When the two first terms are not met you have the value pair?
as a predicate expression.The rest of the terms are never tried since pair?
is always true, thus (car ls)
is the most likely outcome of your procedure (Scheme does not have functions).
Just trying to guess I think the code perhaps should have looked like this:
(define remove-leftmost
(lambda (item ls)
(cond
((null? ls) '())
((equal? (car ls) item) (cdr ls))
((pair? (car ls))
(let ((rem-list (remove-leftmost item (car ls))))
(cons rem-list
(cond
((equal? (car ls) rem-list)
(remove-leftmost item (cdr ls)))
(else (cdr ls))))))
(else
(cons (car ls)
(remove-leftmost item (cdr ls)))))))
(remove-leftmost 'b '(a (b c) (c (b a))))
; ==> (a (c) (c (b a)))
I have put some linefeeds in as well as DrRacket has idented it according to the code. Notice the extra parentheses which are almost invisible to humans but not to IDEs that formats such code.
Upvotes: 2