Home > Software engineering >  DrRacket – Finding total number of vowels in list of characters
DrRacket – Finding total number of vowels in list of characters

Time:02-08

I am using DrRacket on the Beginner Language mode.

Code below:

(define vowels '(#\a #\e #\i #\o #\u))

(define total 0)

(define (any-in-list lst check)
  (cond
    [(empty? lst) (  0 total)]
    [(member? (first lst) check) (add1 total)]
    [else (any-in-list (rest lst) check)]))

(define (count-vowels string)
  (any-in-list (string->list string) vowels))

(count-vowels "how do i do this?")

The total value stays stuck at 1. After debugging, I realized that the 2nd cond statement evaluates to #true and then stops. How can I keep it going for the rest of the list after updating the total value?

CodePudding user response:

You forgot to recurse when you found a match.
Also, since total is 0, ( 0 total) is always 0, and (add1 total) is always 1.

Don't try to use global variables and mutation - recurse and use the recursive value.

(cond
    ; The empty list contains nothing, so the result is 0.
    [(empty? lst) 0]
    ; If the first element is a member, the result is
    ; one more than the count in the tail.
    [(member? (first lst) check) (add1 (any-in-list (rest lst) check))]
    ; Otherwise, the count is the same as in the tail.
    [else (any-in-list (rest lst) check)]))
  •  Tags:  
  • Related