Skip to content

Instantly share code, notes, and snippets.

@pragdave
Last active September 24, 2019 02:21
Show Gist options
  • Save pragdave/44fcdffc9b6fca024212 to your computer and use it in GitHub Desktop.
Save pragdave/44fcdffc9b6fca024212 to your computer and use it in GitHub Desktop.
defmodule RomanNumeral do
@mapping [
{1000, 'M'},
{900, 'CM'},
{500, 'D'},
{400, 'CD'},
{100, 'C'},
{90, 'XC'},
{50, 'L'},
{40, 'XL'},
{10, 'X'},
{9, 'IX'},
{5, 'V'},
{4, 'IV'},
{1, 'I'},
]
def to_arabic(roman_numeral) do
to_arabic(String.to_char_list(roman_numeral), @mapping)
end
defp to_arabic([], _mapping), do: 0
defp to_arabic([ h1, h2 | rest ], mapping = [{arabic_value, [h1, h2]} | _]) do
arabic_value + to_arabic(rest, mapping)
end
defp to_arabic([ h1 | rest ], mapping = [{arabic_value, [h1]} | _]) do
arabic_value + to_arabic(rest, mapping)
end
defp to_arabic(roman, [ _ | other_mappings]) do
to_arabic(roman, other_mappings)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment