Converting numbers to english letter list

谁都会走 提交于 2019-12-02 09:42:53

You can translate an integer into a list of symbols by breaking apart the number into 3-digit groups, attaching units to each group, and then further translating the 3-digit groups to list of symbols. Here is a sample implementation:

(define (num->lst num)
  (define bases '(one two three four five six seven eight nine ten eleven twelve
                  thirteen fourteen fifteen sixteen seventeen eighteen nineteen))
  (define multiples '(twenty thirty forty fifty sixty seventy eighty ninety))
  (define units '(empty thousand million billion trillion quadrillion quintillion
                        sextillion septillion octillion nonillion decillion))
  (define (below-1000 num bases mults)
    (cond [(zero? num) empty]
          [(< num 20) (list (list-ref bases (sub1 num)))]
          [(< num 100) (list* (list-ref mults (- (quotient num 10) 2))
                              (below-1000 (remainder num 10) bases mults))]
          [else (list* (list-ref bases (sub1 (quotient num 100))) 'hundred
                       (below-1000 (remainder num 100) bases mults))]))
  (define (nsplit num lst units)
    (define q (quotient num 1000))
    (define r (remainder num 1000))
    (if (zero? num) lst
        (cond [(zero? r) (nsplit q lst (cdr units))]
              [else (nsplit q (append (below-1000 r bases multiples)
                                      (cons (car units) lst)) (cdr units))])))
  (if (zero? num) '(zero)
      (remove 'empty (nsplit num empty units))))

below-1000 converts numbers below 1000 into list of symbols. nsplit breaks the number into 3-digit groups and attaches units to each group, while converting the 3-digits using below-1000.

For example,

> (num->lst 0)
'(zero)
> (num->lst 1000000001)
'(one billion one)
> (num->lst 35579005)
'(thirty five million five hundred seventy nine thousand five)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!