Skip to content

Instantly share code, notes, and snippets.

@devstopfix
Last active June 15, 2016 20:07
Show Gist options
  • Save devstopfix/c412104ff5746e5b54fbb522d65187c0 to your computer and use it in GitHub Desktop.
Save devstopfix/c412104ff5746e5b54fbb522d65187c0 to your computer and use it in GitHub Desktop.
defmodule RomanNumerals do
# Roman Numerals (Elixir)
@digits %{"I" => 1,
"V" => 5,
"X" => 10,
"L" => 50,
"C" => 100,
"D" => 500,
"M" => 1000}
@doc """
Integer value of a String of Roman Numerals.
"""
def value(s) do
String.codepoints(s)
|> Enum.map(fn d -> Map.get(@digits, d, 0) end)
|> Enum.chunk(2, 1, [0])
|> Enum.reduce(0, &RomanNumerals.accumulate/2)
end
def accumulate([a, b], acc) do
if a >= b do
acc + a
else
acc - a
end
end
end
@devstopfix
Copy link
Author

With pattern matching:

defmodule RomanNumerals do

  def value("I") do    1 end
  def value("V") do    5 end
  def value("X") do   10 end
  def value("L") do   50 end
  def value("C") do  100 end
  def value("D") do  500 end
  def value("M") do 1000 end

  @doc """
  Integer value of a String of Roman Numerals.
  """
  def value(s) do
    s
    |> String.codepoints
    |> Enum.map(fn d -> value(d) end)
    |> Enum.chunk(2, 1, [0])
    |> Enum.reduce(0, &RomanNumerals.accumulate/2)    
  end

  def accumulate([a, b], acc) do
    if a >= b do
      acc + a
    else
      acc - a
    end
  end

end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment