Count digits in list Racket

旧城冷巷雨未停 提交于 2021-01-27 20:04:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!