ryanzidago

ryanzidago

What do you think of my solution for converting integers to roman numerals?

What do you think of my solution for converting integers to roman numerals?

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

Most Liked

kokolegorille

kokolegorille

Nice, but your spec is wrong. It should be non_neg_integer() as You do include 0 :slight_smile:

NobbZ

NobbZ

Also, the spec does make the function appear unbound towards positive infinity.

In reality the spec should be numeral(0..4999) :: String.t().

In general, I do consider this appraoch as quite noisy, and also since iodata_to_binary/1 is used on each recursion step, nothing is gained by it. It might even perform worse than just using <>/2.

Last but not least, I’m not a friend of not using mix format.

ryanzidago

ryanzidago

Nice catch!

Thanks @kokolegorille ! This is for such comments that I like to post on this forum.

NobbZ

NobbZ

Macro/Metaprogramming approaches are possible, though my approach usually just takes an ordered list of conversions and iterates over them.

My take inside, it might spoil you!`
defmodule Roman do
  @arab_to_roman [
    {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"}
  ]

  @doc """
  Convert the number to a roman number.
  """
  @spec numerals(1..3999) :: String.t
  def numerals(number) do
    Enum.reduce(@arab_to_roman, {"", number}, fn ({ar, rm}, {acc, n}) ->
      {acc <> String.duplicate(rm, div(n, ar)), rem(n, ar)}
    end) |> elem(0)
  end
end

PS: This was created when mix format did not yet exist.

kip

kip

ex_cldr Core Team

@nobbz’s solution is also using recursion. Everything is recursion, Enum.reduce/3 just makes it look a little like iteration.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

We're in Beta

About us Mission Statement