Monday, 20 February 2012

Learning Erlang Recursion

I’m learning the Erlang Programming Language and am currently working on the recursion exercise in the erlang course.

The min and max functions seemed pretty straightforward;

min([X,Y]) when X > Y -> Y;
min([X,_]) -> X;
min([H|T]) -> min(H,min(T)).

max([X,Y]) when X > Y -> X;
max([_,Y]) -> Y;
max([H|T]) -> max(H,max(T)).

min_max(List) -> {min(List),max(List)}.

But this is the best I could come up with for the Swedish Date problem; convert an Erlang date in the format {2001,02,03} to “010203″ recursively.

swedish_date() -> swedish_date(date()). 

swedish_date(Date) -> swedish_date(tuple_to_list(Date), "").

swedish_date([H|T], DateString) ->
        List = "0" ++ integer_to_list(H),
        String = lists:sublist(List, length(List)-1, 2),
        swedish_date(T, DateString ++ String);
swedish_date([], DateString) -> DateString.

Can anyone improve on that? I feel sure that recursion could help with the number of digits in each part of the tuple. 2001 → 01, 2 -> 02, etc.

3 comments:

  1. Let's play together on the website of the online casino BGAOC. great gambling sites Do not miss the chance to win with us.

    ReplyDelete
  2. Star Sands Casino | Shootercasino
    Star Sands Casino in San Diego is your 카지노사이트 place to クイーンカジノ play some of the best casino games at California's premier gaming and entertainment destination. 샌즈카지노 Book today!

    ReplyDelete