Scheme统计元音函数报错‘contains?: undefined’求解决方案
Fixing Your Scheme Vowel Counting Function
Hey there! Let's walk through the issues with your current code and get that vowel counter working properly. The error contains?: undefined is the first red flag, but there are a few other pieces we need to adjust too.
What's Going Wrong
contains?isn't a built-in Scheme function: Scheme doesn't have a nativecontains?—we'll usememberinstead, which checks if an element exists in a list and returns the sublist starting at that element (or#fif it doesn't exist).- Undefined variables: You reference
vowelsandcounterbut never define them. Plus, Scheme is a functional language—we can't mutate acountervariable like in imperative languages; instead, we'll pass an accumulator through recursion. - Flawed logic & missing base case: Your current code only handles very specific list scenarios (length 1, or checking the first two elements) and doesn't account for empty lists, which will break recursion. Also, using
listas a parameter name is a bad idea—it overrides Scheme's built-inlistfunction!
Corrected Code
First, let's define our vowels, then build a proper recursive counter:
; Define the list of vowels (include both uppercase and lowercase) (define vowels '(a e i o u A E I O U)) (define (count-vowels lst) ; Helper function that carries our running count (accumulator) (define (count-helper remaining current-count) (cond ; Base case: if the list is empty, return the total count ((null? remaining) current-count) ; If the first element is a vowel, increment count and recurse ((member (car remaining) vowels) (count-helper (cdr remaining) (+ current-count 1))) ; If not a vowel, just recurse with the same count (else (count-helper (cdr remaining) current-count)))) ; Start the recursion with an initial count of 0 (count-helper lst 0))
How This Works
- Vowel List: We explicitly define
vowelsso the function knows which characters to look for. - Helper Function:
count-helpertakes two arguments: the remaining part of the list to check, and the current number of vowels we've found. This is how we "track" the count without mutable variables. - Recursion Cases:
- When the list is empty (
null? remaining), we return the accumulated count—this stops the recursion. - If the first element is in the
vowelslist (checked viamember), we add 1 to the count and recurse on the rest of the list. - If it's not a vowel, we recurse without changing the count.
- When the list is empty (
Testing It Out
Try these examples to verify:
(count-vowels '(a b c e i)) ; Returns 3 (count-vowels '()) ; Returns 0 (empty list case) (count-vowels '(A B o y)) ; Returns 2 (A and o are vowels)
内容的提问来源于stack exchange,提问作者Amir1312
相关产品推荐
相关产品推荐

