Renato D' Oyague
Renato D' Oyague

Reputation: 31

Scheme remove element of first instance

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

Answers (1)

Óscar López
Óscar López

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:

  • You're missing the base case - what happens when you traverse the whole list?
  • When you find the element, then you must skip it and add the rest of the list
  • The list can contain numbers and strings, so it's necessary to use equal? for the comparison, because = only works for numbers
  • And finally, when the recursion is called, you must add the current element to the output list that's being built

Here'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

Related Questions