Home > front end >  How does this count-even racket function work?
How does this count-even racket function work?

Time:02-25

I am trying to understand how the count-even function given in my textbook works and I'm not sure if I completely understand it.

I have provided my understanding of the function in comments next to code. Can someone explain what is happening and correct me in each step of this function.

And I don't understand how this function is recursive. What is the base case ?

(define (ce x)           ; x is an argument that takes in a list
 (if (pair? x)                    ; I don't understand why this is here
  (  (ce (car x))        ; Add the resuls of recursive call together (0 or 1)
     (ce (cdr x)))
  (if (and (number? x) (even? x)) ; if x is a number and x is even then return 1 ? Else return 0 ?
      1
      0) ) )

CodePudding user response:

In a recursive function there are usually two cases:

  1. The result is a call to the same function
  2. The result is a simple value, the base case

You choose between the two cases with an if.

Hence the base case is:

(if (and (number? x) (even? x))
    1
    0) ) )

And the recursive case is:

  (  (count-evens (car x))        
     (count-evens (cdr x)))

Comments:

  1. The argument x doesn't need to be a list. pairs? tests for a list. If it is just a value then we have the base case. If an even number then result is one, else zero.
  2. If the argument x is a list, we split it into two parts, the head (car) and the tail (cdr). The head is just a value, and so when we rerun count-evens on it we end up with the base case.
  3. The tail is passed to count-evens which keeps slicing off a value at a time until we have a value in the car and empty list in cdr. In the base case, the first value is assessed for an even number, and the empty list is always evaluated as zero.
  • Related