Search code examples
recursionschemecons

Scheme Recursion/Cons


I am at the beginning of the road. I tried to understand this cons part for 2-3 hours, but I have fallen into trouble. I couldn't understand this cons part. How does it combine 'a d' according to result?

(define remv
  (lambda (x ls)
    (cond
      [(null? ls) '()]
      [(eqv? (car ls) x) (remv x (cdr ls))]
      [else (cons (car ls) (remv x (cdr ls)))])))

When I put a input like this:

> (remv 'b '(a b b d)) 

I get (a d).

But I couldn't understand how it became 'a d'.


Solution

  • To remove all occurrences of x from a list ls, you have three cases to consider:

    1. ls is empty, in which case the result is also empty,
    2. The first element of ls is equal to x, in which case you just drop it and return the rest of the list after you have removed all xes from it,
    3. The first element of ls is different from x, in which case you keep that element and stick it at the front of a list which has no xes in it.