Racket Function - Character comparison from a string

Asked

Viewed 40 times

0

Good evening, I’m starting now to learn Racket for college and I have an implemented function that I don’t understand why it’s not working. The goal is to receive a string and a character and return how many times the character appears in the string. ex: In "banana" the character "# a" appears 3 times, so the function should return 3. But I only have 0 to answer.

(define (numCaracter c s1 numC x)
   (cond
     [(equal? x (string-length s1)) numC]
     [(equal? c (string-ref s1 x)) (numCaracter c s1 (add1 numC) (add1 x))]
     [else (numCaracter c s1 numC (add1 x))]))

Even if worth mentioning I am testing the function as follows (numCaracter "# a" "banana" 0 0). Thanks for your attention.

1 answer

0


Error is in passing "# a" instead of # a in evaluation:

(numCaracter "#\a" "banana" 0 0)

However I suggest you do it with an auxiliary function and just send the character and string in the evaluation, like this:

(define (numCaracter character string1)
  (numCaracter-aux character string1 0 0))

    (define (numCaracter-aux c s1 numC x)
       (cond
         ((= x (string-length s1)) numC)
         ((equal? c (string-ref s1 x)) (numCaracter-aux c s1 (+ 1 numC) (+ 1 x)))
         (else (numCaracter-aux c s1 numC (+ 1 x))))) 

    (numCaracter #\a "banana")

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.