1 ! Copyright (c) 2007, 2008 Aaron Schaefer.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: combinators.short-circuit grouping kernel math math.parser
4 math.text.utils namespaces sequences ;
9 : small-numbers ( n -- str )
11 "zero" "one" "two" "three" "four" "five" "six"
12 "seven" "eight" "nine" "ten" "eleven" "twelve"
13 "thirteen" "fourteen" "fifteen" "sixteen" "seventeen"
19 f f "twenty" "thirty" "forty" "fifty" "sixty"
20 "seventy" "eighty" "ninety"
23 : scale-numbers ( n -- str ) ! up to 10^99
25 f "thousand" "million" "billion" "trillion" "quadrillion"
26 "quintillion" "sextillion" "septillion" "octillion"
27 "nonillion" "decillion" "undecillion" "duodecillion"
28 "tredecillion" "quattuordecillion" "quindecillion"
29 "sexdecillion" "septendecillion" "octodecillion" "novemdecillion"
30 "vigintillion" "unvigintillion" "duovigintillion" "trevigintillion"
31 "quattuorvigintillion" "quinvigintillion" "sexvigintillion"
32 "septvigintillion" "octovigintillion" "novemvigintillion"
33 "trigintillion" "untrigintillion" "duotrigintillion"
37 : set-conjunction ( seq -- )
38 first { [ 100 < ] [ 0 > ] } 1&& and-needed? set ;
40 : negative-text ( n -- str )
41 0 < "negative " "" ? ;
43 : hundreds-place ( n -- str )
47 [ small-numbers " hundred" append ] dip
48 0 = [ " and " append ] unless
51 : tens-place ( n -- str )
54 dup 0 = [ drop ] [ small-numbers "-" glue ] if
56 dup 0 = [ drop "" ] [ small-numbers ] if
59 : 3digits>text ( n -- str )
60 [ hundreds-place ] [ tens-place ] bi append ;
62 : text-with-scale ( index seq -- str )
63 [ nth 3digits>text ] [ drop scale-numbers ] 2bi
64 [ " " glue ] unless-empty ;
66 : append-with-conjunction ( str1 str2 -- newstr )
70 swap and-needed? get " and " ", " ?
74 : (recombine) ( str index seq -- newstr )
78 text-with-scale append-with-conjunction
81 : recombine ( seq -- str )
85 [ set-conjunction "" ] [ length ] [ ] tri
86 [ (recombine) ] curry each
89 : (number>text) ( n -- str )
90 [ negative-text ] [ abs 3 digit-groups recombine ] bi append ;
94 : number>text ( n -- str )
95 dup zero? [ small-numbers ] [ [ (number>text) ] with-scope ] if ;