我有下面的函数,它将数字输入转换为这些数字的部分翻译字输出。
使用产品和商,它会在将数字分组时添加数字的单词表示。
例如:
(number-name 87969087) -> '(87 million 969 thousand 87)
(number-name 1000000) -> '(1 million)
我试图通过完全翻译那些小于1000的数字来完成我的问题。我试图实现一个小于1000的函数,当列表正在构建时,它将显示那些较小的数字。旁边:
;; for less than 1000
; state words for 1-19
(define baseNumbers '(one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen))
和
; state words for multiples of ten
(define multiples '(twenty thirty forty fifty sixty seventy eighty ninety))
所以
(number-name 1110) -> '(one thousand one hundred ten)
如果输入为0以外的任何一种方式,显示输入0以显示为0的方法也是很困难的,如果输入不是0,则不显示零。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~
(define (number n)
(define units '(thousand million billion trillion quadrillion))
(define (nsplit n units acc lst)
(define q (quotient n 1000))
(define r (remainder n 1000))
(if (zero? n) lst
(cond [(zero? acc)
(if (zero? r)
(nsplit q units (add1 acc) lst)
(nsplit q units (add1 acc) (cons r lst)))]
[(zero? r)
(nsplit q (cdr units) acc lst)]
[else
(nsplit q (cdr units) acc (cons r (cons (car units) lst)))])))
(nsplit n units 0 empty))
答案 0 :(得分:0)
您可以将整数转换为符号列表,方法是将数字拆分为3位数组,将单位附加到每个组,然后将3位数组进一步转换为符号列表。以下是一个示例实现:
(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
将1000以下的数字转换为符号列表。
nsplit
将数字分成3位数组并将单位附加到每个组,同时使用below-1000
转换3位数。
例如,
> (num->lst 0)
'(zero)
> (num->lst 1000000001)
'(one billion one)
> (num->lst 35579005)
'(thirty five million five hundred seventy nine thousand five)