Converting numbers to english letter list

后端 未结 1 909
不知归路
不知归路 2021-01-29 00:51

I have the function below which converts an input of numbers into the partially translated word output of those numbers.

Using product and quotient, it adds the word rep

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 01:18

    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)
    

    0 讨论(0)
提交回复
热议问题