Tail/Non tail recursion

Peter Lund <>
Thu Aug 28 14:45:28 CEST 2003


Possibly:

square([H|T]) -> [H*H|square(T)];
square([]) -> [].

Since the one you wrote will not compile. :)

No, I think this is one of the most efficient ways to do it and it is
tail-recursive.

An alternative would be:

lists:map(fun(X) -> X*X end,
          ListOfNumbers).

/Peter

> Hi All,
> Is there a better way to write this code when there is a lot of
> elements in  the list?
>
> square([H|T]) -> [(H*H|square(T)];
> square([]) -> [].
>
> Thanks.
>
> jilani






More information about the erlang-questions mailing list