Last active
October 26, 2019 05:21
-
-
Save AlbertMoscow/6018774 to your computer and use it in GitHub Desktop.
Roman Numerals kata implemented in elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule RomanNumerals do | |
@moduledoc """ | |
Task definition: Create a function taking a positive integer as its parameter and | |
returning a string containing the Roman Numeral representation of that integer. | |
""" | |
def convert(number) do | |
convert(number, [[10,'X'], [9,'IX'], [5,'V'], [4,'IV'], [1,'I']]) | |
end | |
defp convert(0, _) do | |
'' | |
end | |
defp convert(number, [[arabic, roman]|_] = l) when number >= arabic do | |
roman ++ convert(number - arabic, l) | |
end | |
defp convert(number, [_|t]) do | |
convert(number, t) | |
end | |
end | |
ExUnit.start | |
defmodule RomanNumeralsTest do | |
use ExUnit.Case | |
test "converts arabic numbers to roman" do | |
Enum.each [ [1,'I'], | |
[2,'II'], | |
[3,'III'], | |
[4,'IV'], | |
[5,'V'], | |
[6,'VI'], | |
[7,'VII'], | |
[8,'VIII'], | |
[9,'IX'], | |
[10,'X'], | |
[11,'XI'], | |
[14,'XIV'], | |
[19,'XIX'], | |
[20,'XX'], | |
[25,'XXV'], | |
[27,'XXVII'] ], fn [arabic, roman] -> | |
assert roman == RomanNumerals.convert(arabic) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry for the delay. I had expect notification on a reply from github.
It's my understanding that in elixir single quoted strings (char lists) often perform worse than double quoted strings (binaries). Not that it really matters in this small of a problem.
I copied your tests and worked from them. I'm sorry I didn't do intermediate check ins. I feel I need to defend my TDD skills to you. I gave a talk at JavaOne 2002 entitled "Unit Testing Made Easy: Design Principles to Facilitate Testing". I'm having trouble finding much information online about it, but here's 2 links, the first is my comment on the refactoring mailing list about it, and the 2nd is someone's notes of talks they attended:
http://osdir.com/ml/programming.refactoring/2002-07/msg00052.html
http://ziggr.com/javaone2002/#z51
I could have incrementally done red/green/refactor for this exercise. However, given the limited complexity of it, and the fact that I've done the roman numeral kata in several languages, I wouldn't learn anything but new elixir syntax. So, I just focused on that. I built off your "when number >= arabic" idea, then learned elixir syntax for div, rem, and String.duplicate