Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
non tail-recursive version
-module(roman_to_num).
% https://github.com/ruby-fatecsp/dojos/blob/8cb15023eec6d4a5c9cdcf1723adff1ed5864a03/roman_to_numerals/lib/roman_to_num.rb
-export([convert/1, test/0]).
digit_to_num(D) ->
case D of
$I -> 1;
$V -> 5;
$X -> 10;
$L -> 50;
$C -> 100;
$D -> 500;
$M -> 1000;
_ -> erlang:error(badarg)
end.
convert([Head|[]]) -> digit_to_num(Head);
convert([Head1, Head2 | Tail]) ->
Head1AsNum = digit_to_num(Head1),
Head2AsNum = digit_to_num(Head2),
if
Head1AsNum < Head2AsNum ->
convert([Head2|Tail]) - Head1AsNum;
true ->
convert([Head2|Tail]) + Head1AsNum
end .
test() ->
20 = convert("XX"),
22 = convert("XXII"),
4 = convert("IV"),
5 = convert("V"),
6 = convert("VI"),
7 = convert("VII"),
9 = convert("IX"),
11 = convert("XI"),
2011 = convert("MDDXI"),
test_passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment