exercism/elixir/roman-numerals/lib/roman_numerals.ex

34 lines
757 B
Elixir

defmodule RomanNumerals do
@doc """
Convert the number to a roman number.
"""
@romans %{
1 => ["I", "X", "C", "M"],
2 => ["II", "XX", "CC", "MM"],
3 => ["III", "XXX", "CCC", "MMM"],
4 => ["IV", "XL", "CD"],
5 => ["V", "L", "D"],
6 => ["VI", "LX", "DC"],
7 => ["VII", "LXX", "DCC"],
8 => ["VIII", "LXXX", "DCCC"],
9 => ["IX", "XC", "CM"]
}
@spec numeral(pos_integer) :: String.t()
def numeral(number) do
number
|> Integer.digits()
|> Enum.reverse()
|> Enum.with_index(&to_roman_digit/2)
|> Enum.reverse()
|> Enum.join()
end
defp to_roman_digit(0, _index), do: ""
defp to_roman_digit(digit, index) do
@romans
|> Map.fetch!(digit)
|> Enum.at(index)
end
end