Integer to RomanNumeral in Erlang 2
Haskell で書いたのを参考に書き直してみた。 なんとなく Haskell っぽくなった?
convert.erl
-module(convert).
-compile(export_all).
-import(lib_misc,[p/1]).
old_roman_unit(1000) -> "M";
old_roman_unit( 500) -> "D";
old_roman_unit( 100) -> "C";
old_roman_unit( 50) -> "L";
old_roman_unit( 10) -> "X";
old_roman_unit( 5) -> "V";
old_roman_unit( 1) -> "I".
i2r(Num) ->
lists:flatten(i2r(Num, [1000, 500, 100, 50, 10, 5, 1])).
i2r(_,[]) ->
[];
i2r(Num, [H|T]) ->
lists:duplicate(Num div H, old_roman_unit(H)) ++ i2r(Num rem H, T).
参考
Ruby で同じロジックで書いてみた。
convert.rb
class Numeric
OLD_ROMAN_UNIT = {
1000 => 'M',
500 => 'D',
100 => 'C',
50 => 'L',
10 => 'X',
5 => 'V',
1 => 'I'
}
def to_old_roman
i2r(self, [1000,500,100,50,10,5,1])
end
def i2r(num, units)
return '' if units.empty?
digits, mod = num.divmod(h = units.shift)
OLD_ROMAN_UNIT[h] * digits + i2r(mod, units)
end
endやっと再帰の使い方が理解できたかも?
Posted in Programming, Ruby | atom