DEV Community

Discussion on: Daily Challenge #19 - Turn numbers into words

Collapse
 
oscherler profile image
Olivier “Ölbaum” Scherler • Edited

I’m learning Erlang, and I got to use file I/O and a list comprehension for the unit tests (in the Gist version).

Short version:

-module( words ).
-export( [ num_to_words/1, test_words/2 ] ).

-include_lib("eunit/include/eunit.hrl").

words() -> #{
    units => [
        "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
        "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
    ],
    tens => [ "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" ]
}.
word( N, Cat ) ->
    lists:nth( N, maps:get( Cat, words() ) ).

join_num_words( _, 0 ) ->
    "";
join_num_words( Joint, N ) ->
    Joint ++ num_to_words( N ).

num_to_words( N ) when N > 0, N < 20 ->
    word( N, units );
num_to_words( N ) when N < 100 ->
    word( N div 10, tens ) ++ join_num_words( "-", N rem 10 );
num_to_words( N ) when N < 1000 ->
    word( N div 100, units ) ++ " hundred" ++ join_num_words( " and ", N rem 100 ).

% TESTS

num_to_words_test_() -> [
    ?_assertEqual( "one", num_to_words( 1 ) ),
    ?_assertEqual( "four", num_to_words( 4 ) ),
    ?_assertEqual( "ten", num_to_words( 10 ) ),
    ?_assertEqual( "twelve", num_to_words( 12 ) ),
    ?_assertEqual( "twenty", num_to_words( 20 ) ),
    ?_assertEqual( "forty-two", num_to_words( 42 ) ),
    ?_assertEqual( "one hundred", num_to_words( 100 ) ),
    ?_assertEqual( "one hundred and one", num_to_words( 101 ) ),
    ?_assertEqual( "one hundred and fifty-six", num_to_words( 156 ) ),
    ?_assertEqual( "eight hundred and sixty-five", num_to_words( 865 ) ),
    ?_assertEqual( "nine hundred and ninety-nine", num_to_words( 999 ) )
].

In this Gist, there’s a test file with all values from 1 to 999, and a EUnit test that loads this file and generates a test for each value.