miércoles, 6 de agosto de 2014

Decimal to Romans - Erlang Style

As I keep going with my Erlang enlightenment...I decided to try to make a Decimal to Roman Numbers application...as I have done with other programming languages in the past...and it wasn't that easy -:)

First...there's no such thing as associative arrays in Erlang...also...you can only assign variables once...on top of that there's no loops...but...who cares...functional programming is cool -;)

Of course...my code might be have done better...but...I'm learning...and by coding I learn more...so that's fine with me...

Here's why I wrote -;)

roman_numerals.erl
-module(roman_numerals).
-export([showRomans/1]).
-define(DECIMALS,{1000,900,500,400,100,90,50,40,10,9,5,4,1}).

showRomans(Number) when is_integer(Number) ->
 showRomans(Number,1,"").

showRomans(0,_,Acc) ->
 io:format("~s~n",[Acc]);
showRomans(Number,Counter,Acc) ->
 case Number >= element(Counter,?DECIMALS) of 
  true -> showRomans(Number - element(Counter,?DECIMALS),
         Counter,Acc ++ make_roman(element(Counter,?DECIMALS)));
  false -> showRomans(Number,Counter + 1,Acc)
 end.
  
make_roman(1) -> "I";make_roman(4) -> "IV";make_roman(5) -> "V";
make_roman(9) -> "IX";make_roman(10) -> "X";make_roman(40) -> "XL";
make_roman(50) -> "L";make_roman(90) -> "XC";make_roman(100) -> "C";
make_roman(400) -> "CD";make_roman(500) -> "D";make_roman(900) -> "CM";
make_roman(1000) -> "M".

When we execute it...we can see that it works nicely -;)


As you can see...Erlang is all about functions, recursion, accumulators and a new way of thinking -:)

Greetings,

Blag.
Development Culture.