Reverse And Add 110502 in Erlang

Carrying on from Cedric’s Challenge (C#, Erlang) I decided to do some of the Programming Challenges problems in Erlang, because the problems are small, but fun.

My first is Reverse And Add #110502 and here is my solution:

-export([rev_and_add/1, test/0]).%% number to list
ntl(Num) ->
    ntl(Num, []).
ntl(0, List) ->

ntl(Num, List) ->
    ntl(Num div 10, [Num rem 10]++List).

%% list to number
ltn(List) ->
    ltn(List, 0).

ltn([], Num) ->
ltn([H|T], Num) ->
    ltn(T, (Num*10)+H).

%% is palindrome
is_pal(Num) ->
    ntl(Num) == lists:reverse(ntl(Num)).

rev_and_add(Num) ->
    rev_and_add(Num, 1).

rev_and_add(Num, Count) ->
    Pal = ltn(lists:reverse(ntl(Num))) + Num,
    case is_pal(Pal) of
    true ->
    false ->
        rev_and_add(Pal, Count+1)

test() ->
[4,9339] = rev_and_add(195),
[5,45254] = rev_and_add(265),
[3,6666] = rev_and_add(750),

I’m not too happy with the number-to-list functions as I’m sure there should be a built in way to-do this already, which Joe implies therefore there probably is.



Tobias 2008-07-11 02:11:59

You’re looking for integer_to_list(Integer) and list_to_integer(List), they’re built-in functions (often referred to as “BIFs”) and usable just like that (no module).

They’re actually part of the “erlang” module

which is a bit confusing, because most (but not all!) of the functions in that module can be used without specifying “erlang:” in front of the name.

Simeon Pilgrim 2008-07-11 09:32:52

Thank you so much Tobias, I will now go read that section, so I’m more informed from now on…

integer_to_list(Integer) and list_to_integer(List) make a list of the text digits, where-as I was using just a list of the digits in numerical value, but as I’m just reversing and comparing, those functions will do.