Reputation: 128
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
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
Reputation: 236122
Here's a possible solution:
(define (countDigits lst)
(apply +
(map (compose string-length number->string)
lst)))
Explanation:
For example:
(countDigits '(4 5 6 78))
=> 5
Upvotes: 2