Luiz Miranda
Luiz Miranda

Reputation: 128

Count digits in list Racket

I have a doubt, I'm using Racket, and I wanna count the digits of a list, but I can't. I try with length but it doesn't work as I want because

(countDigits '(4 5 6 78)) > 5

the answer has to be 5 but, i don't know how to, i have a code for count digits in a number but I don't knowhow to do it in a list. ¿How could I do it?

Upvotes: 2

Views: 1089

Answers (2)

Tyler Nichols
Tyler Nichols

Reputation: 196

A more naive example that wouldn't make your professor look twice :)

Regular Recursion:

(define (countDigits list-of-digits)
  (cond [(empty? list-of-digits) 0]
        [else (+ 1 (countDigits (rest list-of-digits)))]))

Tail Recursion:

(define (countDigits list-of-digits sum)
  (cond [(empty? list-of-digits) sum]
        [else (countDigits (rest list-of-digits) (+ 1 sum))]))

Upvotes: 0

Óscar López
Óscar López

Reputation: 236122

Here's a possible solution:

(define (countDigits lst)
  (apply +
         (map (compose string-length number->string)
              lst)))

Explanation:

  • For each number in the list, we convert it to a string
  • Then, we obtain the length of each string - that will tell us the number of digits
  • Finally, we add together all the lengths

For example:

(countDigits '(4 5 6 78))
=> 5

Upvotes: 2

Related Questions