Reputation: 31
I want to remove the first element encounter on a list
example
> (remove-first '(10 20 30 40 50 40 30 20 10) 10)
(20 30 40 50 40 30 20 10)
> (remove-first '(10 20 30 40 50 40 30 20 10) 40)
(10 20 30 50 40 30 20 10)
> (remove-first '("A" "B" "C" "d" "e" "F") "d")
("A" "B" "C" "e" "F")
> (remove-first '(10 20 30 40 50 40 30 20 10) 60)
(10 20 30 40 50 40 30 20 10)
> (remove-first (remove-first '(10 20 30 40 50 40 30 20 10) 40) 40)
(10 20 30 50 30 20 10)
but I don't know what I'm missing in my code, maybe I got stuck in a infinite loop
(define remove-first
(lambda (li num)
(if
(= num (car li))
(else
(remove-first (cdr li) num)
)
)
)
)
Upvotes: 0
Views: 487
Reputation: 236044
You should study the standard template for traversing an input list and building an output list as answer, the same solution structure is used for many problems, and your code currently doesn't adhere to it. Other bugs include:
equal?
for the comparison, because =
only works for numbersHere's a fixed version:
(define remove-first
(lambda (li val)
(cond ((null? li) '())
((equal? val (car li)) (cdr li))
(else (cons (car li) (remove-first (cdr li) val))))))
Upvotes: 2