问题
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?
回答1:
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
回答2:
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))]))
来源:https://stackoverflow.com/questions/46019105/count-digits-in-list-racket