Integer to RomanNumeral in Erlang

Posted by okkez Sat, 02 Jun 2007 16:50:00 GMT

Erlang 勉強会#1の宿題ができたので公開。

to_roman_numeral
-module(math). -export([i2r/1,to_s/2]). -import(lib_misc,[p/1]). old_roman_unit(N) when N =:= 1000 -> "M"; old_roman_unit(N) when N =:= 500 -> "D"; old_roman_unit(N) when N =:= 100 -> "C"; old_roman_unit(N) when N =:= 50 -> "L"; old_roman_unit(N) when N =:= 10 -> "X"; old_roman_unit(N) when N =:= 5 -> "V"; old_roman_unit(N) when N =:= 1 -> "I". i2r(Num) -> [H|T] = [1000, 500, 100, 50, 10, 5, 1], {Div, Mod} = {Num div H, Num rem H}, lists:flatten(i2r(Mod, T, to_s(old_roman_unit(H),Div))). i2r(_,[],Str) -> Str; i2r(Num, [H|T], Str) -> {Div, Mod} = {Num div H, Num rem H}, if Div > 0 -> i2r(Mod, T, Str ++ to_s(old_roman_unit(H), Div)); true -> i2r(Mod, T, Str) end. to_s(C, Num) -> if Num > 0 -> lists:map(fun(_) -> C end,lists:seq(1,Num)); true -> [] end.

ダサい部分はたくさんあるけど自力で書いたのが偉いと思ったので公開。エラーメッセージの読み方がなんとなくわかってきたような気がする。

ついでに。

lib_misc
-module(lib_misc). -export([p/1]). p(X) -> io:format("~p~n",[X]), X.

こんな感じで使う。 関数の途中の値を知りたいときに使うと便利かも?

sample
to_s(C, Num) -> if Num > 0 -> lib_misc:p(lists:map(fun(_) -> C end,lists:seq(1,Num))); true -> [] end.

Posted in | コメントはありません | タグ | atom

Trackbacks

Use the following link to trackback from your own site:
http://typo.okkez.net/trackbacks?article_id=integer-to-romannumeral-in-erlang&day=03&month=06&year=2007

  1. 勉強会に参加していないので宿題の内容は知らないのだけども,すぐに書けそうだったの

Comments

Leave a response

Leave a comment