Skip to content

Instantly share code, notes, and snippets.

@ryanzidago
Created April 11, 2020 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanzidago/76d95c0faf1eb27b7386bc49adb07e06 to your computer and use it in GitHub Desktop.
Save ryanzidago/76d95c0faf1eb27b7386bc49adb07e06 to your computer and use it in GitHub Desktop.
Here is my solution to Exercism's Roman Numerals exercise.
defmodule RomanNumerals do
import IO, only: [iodata_to_binary: 1]
@doc """
Convert the number to a roman number.
"""
@spec numeral(pos_integer) :: String.t()
def numeral(0), do: ""
def numeral(1), do: "I"
def numeral(2), do: "II"
def numeral(3), do: "III"
def numeral(4), do: "IV"
def numeral(5), do: "V"
def numeral(6), do: "VI"
def numeral(7), do: "VII"
def numeral(8), do: "VIII"
def numeral(9), do: "IX"
def numeral(10), do: "X"
def numeral(50), do: "L"
def numeral(100), do: "C"
def numeral(500), do: "D"
def numeral(1000), do: "M"
def numeral(n) when n < 40, do: [numeral(10), numeral(n - 10)] |> iodata_to_binary()
def numeral(n) when n < 50, do: [numeral(10), numeral(50), numeral(n - 40)] |> iodata_to_binary()
def numeral(n) when n < 90, do: [numeral(50), numeral(n - 50)] |> iodata_to_binary()
def numeral(n) when n < 100, do: [numeral(10), numeral(100), numeral(n - 90)] |> iodata_to_binary()
def numeral(n) when n < 400, do: [numeral(100), numeral(n - 100)] |> iodata_to_binary()
def numeral(n) when n < 500, do: [numeral(100), numeral(500), numeral(n - 400)] |> iodata_to_binary()
def numeral(n) when n < 900, do: [numeral(500), numeral(n - 500)] |> iodata_to_binary()
def numeral(n) when n < 1000, do: [numeral(100), numeral(1000), numeral(n - 900)] |> iodata_to_binary()
def numeral(n) when n < 5000, do: [numeral(1000), numeral(n - 1000)] |> iodata_to_binary()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment