I was recently asked to write the following function:
“12345.67″ -> “twelve thousand three hundred and forty-five dollars and sixty-seven cents”
“41000023″ -> “forty-one million and twenty-three dollars and zero cents”
“1.01″ -> “one dollar and one cent”
“”7abc.def4ghi3jkl3″” -> “seven dollars and forty-three cents”
and so on
I was originally asked to write it in any programming language, so I chose a reasonably practical one at first. However, it turns out I should have written it in C#, so I did that too. Then I wondered how well I could write it using Functional Java. Here is my original program is a more practical programming language (sorry about the formatting):
import Data.Char
import Data.Maybe
import Data.List
import Data.Foldable(toList)
import Data.Sequence hiding (length, take, null)
import Control.Arrow
import Control.Applicative
data Digit = Zero | One | Two | Three | Four | Five | Six | Seven | Eight | Nine deriving (Show, Eq, Enum, Bounded)
show' d = toLower show d
k ! a = fromJust $ lookup k a
data Digit3 = D1 Digit | D2 Digit Digit | D3 Digit Digit Digit deriving Eq
instance Show Digit3 where
show (D1 a) = show' a
show (D2 Zero b) = show' b
show (D2 One b) = let een = [minBound ..] `zip` ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
in b ! een
show (D2 a b) = let nty = [Two ..] `zip` ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
in (a ! nty) ++ if b == Zero then [] else '-' : show' b
show (D3 Zero Zero Zero) = []
show (D3 Zero b c) = show (D2 b c)
show (D3 a Zero Zero) = show' a ++ " hundred"
show (D3 a b c) = show' a ++ " hundred and " ++ show (D2 b c)
write s = case dc s of (d, c) -> let d' = fst d
in intercalate " " $ dollars d ++ d' ~> "dollar" : "and" : cents c : [[c] ~> "cent"]
where
[(D1 One)] ~> s = s
[(D2 Zero One)] ~> s = s
_ ~> s = s ++ "s"
dc s = case break (== '.') s of (d, c) -> let d' = z length $ dropWhile (== Zero) . k $ d
dig [] = D1 Zero
dig [d1] = D1 d1
dig [d1, d2] = D2 d1 d2
dig [d1, d2, d3] = D3 d1 d2 d3
z a n = let ds = foldr (\(k, i) z -> if i `mod` 3 == 0
then [k] : z
else (k : head z) : tail z) [] $ a `zip` [n-1, n-2..0]
n' = (n `div` 3) + (signum $ n `mod` 3)
in (dig ds) `zip` [n'-1, n'-2..0]
in (d', dig take 2 $ k c)
where
k = (toEnum . digitToInt ) . filter isDigit
dollars ds = if null ds
then ["zero"]
else toList $ foldl' k Data.Sequence.empty ds
where
k s (d, n) = ill n d (illion (n - 1)) ((d show d) (and' s))
where
illion = (!!) ["thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion"]
c = flip (|>)
(D3 Zero Zero Zero) _ = id
_ k = c k
ill n d k = if n == 0 then id else d k
and' = if n == 0 && and d then c "and" else id
where
and (D3 Zero a b) = (/= Zero) `any` [a, b]
and _ = False
cents (D3 a b _) = cents (D2 a b)
cents (D1 a) = cents (D2 a Zero)
cents a = show' a
-------- BEGIN TESTS -------
tests = (\(k, v) -> if k == v
then print "Test Passed"
else error $ "Test Failed: " ++ k ++ " not equal to " ++ v) `mapM_` t
where
t = [(show $ D1 One, "one"),
(show $ D1 Zero, "zero"),
(show $ D2 One Zero, "ten"),
(show $ D2 One Five, "fifteen"),
(show $ D2 Four Zero, "forty"),
(show $ D2 Four Five, "forty-five")] ++
(first write
[("0", "zero dollars and zero cents"),
("1", "one dollar and zero cents"),
("1.", "one dollar and zero cents"),
("0.", "zero dollars and zero cents"),
("0.0", "zero dollars and zero cents"),
("1.0", "one dollar and zero cents"),
("a1a", "one dollar and zero cents"),
("a1a.a0.7b", "one dollar and seven cents"),
("100", "one hundred dollars and zero cents"),
("100.45", "one hundred dollars and forty-five cents"),
("100.07", "one hundred dollars and seven cents"),
("9abc9def9ghi.jkl9mno", "nine hundred and ninety-nine dollars and ninety cents"),
("12345.67", "twelve thousand three hundred and forty-five dollars and sixty-seven cents"),
("456789123456789012345678901234567890123456789012345678901234567890.12", "four hundred and fifty-six vigintillion seven hundred and eighty-nine novemdecillion one hundred and twenty-three octodecillion four hundred and fifty-six septendecillion seven hundred and eighty-nine sexdecillion twelve quindecillion three hundred and forty-five quattuordecillion six hundred and seventy-eight tredecillion nine hundred and one duodecillion two hundred and thirty-four undecillion five hundred and sixty-seven decillion eight hundred and ninety nonillion one hundred and twenty-three octillion four hundred and fifty-six septillion seven hundred and eighty-nine sextillion twelve quintillion three hundred and forty-five quadrillion six hundred and seventy-eight trillion nine hundred and one billion two hundred and thirty-four million five hundred and sixty-seven thousand eight hundred and ninety dollars and twelve cents")])
-------- END TESTS -------
And here is the same problem solved using Functional Java:
import fj.data.List;
import fj.data.Option;
import fj.data.Stream;
import static fj.data.List.*;
import static fj.data.List.asString;
import static fj.data.Stream.stream;
import static fj.data.Option.some;
import fj.*;
import static fj.P.p;
import fj.function.Characters;
import static fj.pre.Equal.charEqual;
import static fj.pre.Equal.listEqual;
import static fj.pre.Show.*;
public final class ChequeWrite {
private ChequeWrite() {}
static List<Integer> toZero(final int from) {
return unfold(new F<Integer, Option<P2<Integer, Integer>>>() {
public Option<P2<Integer, Integer>> f(final Integer i) {
return (i < 0) ? Option.<P2<Integer, Integer>>none() : some(p(i, i - 1));
}
}, from);
}
static int signum(final int i) {
return i == 0 ? 0 : i < 0 ? -1 : 1;
}
static List<Character> show(final char c) {
return stringShow.show(list("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine").index(c - '0')).toList();
}
static List<Character> show(final List<Character> cs) {
if(cs.isEmpty())
return List.nil();
else {
final char d1 = cs.head();
final List<Character> d1r = cs.tail();
if(d1r.isEmpty())
return show(d1);
else {
final char d2 = d1r.head();
final List<Character> d2r = d1r.tail();
return d2r.isEmpty()
? d1 == '0'
? show(d2)
: d1 == '1'
? stringShow.showl(list("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen").index(d2 - '0'))
: stringShow.showl(list("twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety").index(d1 - '0' - 2))
.append(d2 == '0' ? List.<Character>nil() : show(d2).cons('-'))
: d1 == '0' && d2 == '0' && d2r.head() == '0'
? List.<Character>nil()
: d1 == '0'
? show(list(d2, d2r.head()))
: d2 == '0' && d2r.head() == '0'
? show(d1).append(stringShow.showl(" hundred"))
: show(d1).append(stringShow.showl(" hundred and ")).append(show(list(d2, d2r.head())));
}
}
}
static <A> List<P2<List<A>, Integer>> split(final List<A> as) {
final int len = as.length();
final List<List<A>> ds = as.zip(toZero(len - 1)).foldRight(new F2<P2<A, Integer>, List<List<A>>, List<List<A>>>() {
public List<List<A>> f(final P2<A, Integer> ki, final List<List<A>> z) {
return ki._2() % 3 == 0 ? z.conss(single(ki._1())) : z.tail().conss(z.head().cons(ki._1()));
}
}, List.<List<A>>nil());
return ds.zip(toZero(len / 3 + signum(len % 3) - 1));
}
static List<Character> illion(final int i) {
return stringShow.show(stream("thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion")
.append(Stream.repeat("<unsupported ?illion>")).index(i)).toList();
}
static boolean and(final List<Character> cs) {
return cs.length() == 3 && cs.head() == '0' && (cs.tail().head() != '0' || cs.tail().tail().head() != '0');
}
static boolean existsNotZero(final List<Character> cs) {
return cs.exists(new F<Character, Boolean>() {
public Boolean f(final Character c) {
return c != '0';
}
});
}
static boolean eq(final List<Character> a, final List<Character> b) {
return listEqual(charEqual).eq(a, b);
}
final static F<List<Character>, List<Character>> dollars = new F<List<Character>, List<Character>>() {
public List<Character> f(final List<Character> cs) {
if(cs.isEmpty())
return fromString("zero dollars");
else {
final List.Buffer<List<Character>> x = new List.Buffer<List<Character>>();
final List<P2<List<Character>, Integer>> k = split(cs);
final int c = k.head()._2();
k.foreach(new Effect<P2<List<Character>, Integer>>() {
public void e(final P2<List<Character>, Integer> z) {
final List<Character> w = z._1();
final int i = z._2();
if(i == 0 && c > 0 && and(w))
x.snoc(fromString("and"));
if(existsNotZero(w)) {
x.snoc(show(w));
if(i != 0)
x.snoc(illion(i - 1));
}
}
});
x.snoc(fromString(eq(cs, list('1')) ? "dollar" : "dollars"));
return fromString(" ").intercalate(x.toList());
}
}
};
final static F<List<Character>, List<Character>> cents = new F<List<Character>, List<Character>>() {
public List<Character> f(final List<Character> a) {
final int n = a.length();
return n == 0
? fromString("zero cents")
: show(list(a.head(), n == 1 ? '0' : a.tail().head())).append(fromString(eq(a, list('0', '1')) ? " cent" : " cents"));
}
};
public static List<Character> write(final List<Character> cs) {
F<List<Character>, List<Character>> dropNonDigit = new F<List<Character>, List<Character>>() {
public List<Character> f(final List<Character> cs) {
return cs.filter(Characters.isDigit);
}
};
final P2<List<Character>, List<Character>> x = cs.dropWhile(charEqual.eq('0')).breakk(charEqual.eq('.')).map1(dropNonDigit).map1(dollars).map2(dropNonDigit).map2(List.<Character>take().f(2)).map2(cents);
return x._1().append(fromString(" and ")).append(x._2());
}
public static void main(final String[] args) {
if(args.length == 0)
tests();
else
for(final String a : args)
System.out.println(asString(write(fromString(a))));
}
public static void tests() {
// show
for(final P2<String, String> t : list(
p("1", "one"),
p("10", "ten"),
p("15", "fifteen"),
p("40", "forty"),
p("45", "forty-five"))) {
assert(eq(show(fromString(t._1())), fromString(t._2())));
}
// write
for(final P2<String, String> t : list(
p("0", "zero dollars and zero cents"),
p("1", "one dollar and zero cents"),
p("1.", "one dollar and zero cents"),
p("0.", "zero dollars and zero cents"),
p("0.0", "zero dollars and zero cents"),
p("1.0", "one dollar and zero cents"),
p("a1a", "one dollar and zero cents"),
p("a1a.a0.7b", "one dollar and seven cents"),
p("100", "one hundred dollars and zero cents"),
p("100.45", "one hundred dollars and forty-five cents"),
p("100.07", "one hundred dollars and seven cents"),
p("9abc9def9ghi.jkl9mno", "nine hundred and ninety-nine dollars and ninety cents"),
p("12345.67", "twelve thousand three hundred and forty-five dollars and sixty-seven cents"),
p("456789123456789012345678901234567890123456789012345678901234567890.12", "four hundred and fifty-six vigintillion seven hundred and eighty-nine novemdecillion one hundred and twenty-three octodecillion four hundred and fifty-six septendecillion seven hundred and eighty-nine sexdecillion twelve quindecillion three hundred and forty-five quattuordecillion six hundred and seventy-eight tredecillion nine hundred and one duodecillion two hundred and thirty-four undecillion five hundred and sixty-seven decillion eight hundred and ninety nonillion one hundred and twenty-three octillion four hundred and fifty-six septillion seven hundred and eighty-nine sextillion twelve quintillion three hundred and forty-five quadrillion six hundred and seventy-eight trillion nine hundred and one billion two hundred and thirty-four million five hundred and sixty-seven thousand eight hundred and ninety dollars and twelve cents"))) {
assert(eq(write(fromString(t._1())), fromString(t._2())));
}
}
}