Numbers to words
This code defines an operator, n2w, that maps positive integers to their English equivalent.
Here is the code:
-- convert numbers to words: -- usage: n2w |12345> -- updated to the version 3.1.1 language ones |1> => |one> ones |2> => |two> ones |3> => |three> ones |4> => |four> ones |5> => |five> ones |6> => |six> ones |7> => |seven> ones |8> => |eight> ones |9> => |nine> tens |10> => |ten> tens |11> => |eleven> tens |12> => |twelve> tens |13> => |thirteen> tens |14> => |fourteen> tens |15> => |fifteen> tens |16> => |sixteen> tens |17> => |seventeen> tens |18> => |eighteen> tens |19> => |nineteen> ten |20> => |twenty> ten |30> => |thirty> ten |40> => |forty> ten |50> => |fifty> ten |60> => |sixty> ten |70> => |seventy> ten |80> => |eighty> ten |90> => |ninety> tens |*> #=> smerge[" "] sdrop ( ten times-by[10] int-divide-by[10] |_self> . ones mod[10] |_self> ) hundreds-rule |*> #=> smerge[" and "] (hundreds int-divide-by[100] mod[1000] |_self> . tens mod[100] |_self>) hundreds |0> #=> |> hundreds |*> #=> ones |_self> __ |hundred> thousands |0> #=> |> thousands |*> #=> hundreds-rule |_self> __ |thousand> millions |0> #=> |> millions |*> #=> hundreds-rule |_self> __ |million> billions |0> #=> |> billions |*> #=> hundreds-rule |_self> __ |billion> trillions |0> #=> |> trillions |*> #=> hundreds-rule |_self> __ |trillion> op |seq> => |op: hundreds-rule> . |op: thousands> . |op: millions> . |op: billions> . |op: trillions> -- our numbers to words operator: n2w |0> => |zero> n2w |*> #=> smerge[", "] sreverse op-zip(op |seq>) split-num |_self> -- the split-number operator: split-num |*> #=> if( is-less-than[1000] |__self> ): |__self> else: mod[1000] |__self> . split-num int-divide-by[1000] |__self> end:
And here are a couple of examples of n2w in action:
sa: n2w |31> |thirty one> sa: n2w |00037> |thirty seven> sa: n2w |3700> |three thousand, seven hundred> sa: n2w |1234567890> |one billion, two hundred and thirty four million, five hundred and sixty seven thousand, eight hundred and ninety>
Noting that there is a limit to the size of the integers due to the back end C++.
Raw file here.