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.